4b1030397593e70ded7d4e4432d3d56dcc323629
[platform/upstream/gcc.git] / gcc / ada / gnat_ugn.texi
1 \input texinfo   @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c                                                                            o
6 @c                            GNAT DOCUMENTATION                              o
7 @c                                                                            o
8 @c                             G N A T _ U G N                                o
9 @c                                                                            o
10 @c           Copyright (C) 1992-2013, Free Software Foundation, Inc.          o
11 @c                                                                            o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
13
14 @setfilename gnat_ugn.info
15
16 @copying
17 Copyright @copyright{} 1995-2009 Free Software Foundation,
18 Inc.
19
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.3 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24 Texts.  A copy of the license is included in the section entitled
25 ``GNU Free Documentation License''.
26 @end copying
27
28 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
29 @c
30 @c                           GNAT_UGN Style Guide
31 @c
32 @c  1. Always put a @noindent on the line before the first paragraph
33 @c     after any of these commands:
34 @c
35 @c          @chapter
36 @c          @section
37 @c          @subsection
38 @c          @subsubsection
39 @c          @subsubsubsection
40 @c
41 @c          @end smallexample
42 @c          @end itemize
43 @c          @end enumerate
44 @c
45 @c  2. DO NOT use @example. Use @smallexample instead.
46 @c     a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
47 @c        context.  These can interfere with the readability of the texi
48 @c        source file.  Instead, use one of the following annotated
49 @c        @smallexample commands, and preprocess the texi file with the
50 @c        ada2texi tool (which generates appropriate highlighting):
51 @c        @smallexample @c ada
52 @c        @smallexample @c adanocomment
53 @c        @smallexample @c projectfile
54 @c     b) The "@c ada" markup will result in boldface for reserved words
55 @c        and italics for comments
56 @c     c) The "@c adanocomment" markup will result only in boldface for
57 @c        reserved words (comments are left alone)
58 @c     d) The "@c projectfile" markup is like "@c ada" except that the set
59 @c        of reserved words include the new reserved words for project files
60 @c
61 @c  3. Each @chapter, @section, @subsection, @subsubsection, etc.
62 @c     command must be preceded by two empty lines
63 @c
64 @c  4. The @item command should be on a line of its own if it is in an
65 @c     @itemize or @enumerate command.
66 @c
67 @c  5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
68 @c     or "ali".
69 @c
70 @c  6. DO NOT put trailing spaces at the end of a line.  Such spaces will
71 @c     cause the document build to fail.
72 @c
73 @c  7. DO NOT use @cartouche for examples that are longer than around 10 lines.
74 @c     This command inhibits page breaks, so long examples in a @cartouche can
75 @c     lead to large, ugly patches of empty space on a page.
76 @c
77 @c  NOTE: This file should be submitted to xgnatugn with either the vms flag
78 @c        or the unw flag set.  The unw flag covers topics for both Unix and
79 @c        Windows.
80 @c
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
82
83 @set NOW January 2007
84 @c This flag is used where the text refers to conditions that exist when the
85 @c text was entered into the document but which may change over time.
86 @c Update the setting for the flag, and (if necessary) the text surrounding,
87 @c the references to the flag, on future doc revisions:
88 @c search for @value{NOW}.
89
90 @set FSFEDITION
91 @set EDITION GNAT
92
93 @ifset unw
94 @set PLATFORM
95 @set TITLESUFFIX
96 @end ifset
97
98 @ifset vms
99 @set PLATFORM OpenVMS
100 @set TITLESUFFIX for OpenVMS
101 @end ifset
102
103 @c @ovar(ARG)
104 @c ----------
105 @c The ARG is an optional argument.  To be used for macro arguments in
106 @c their documentation (@defmac).
107 @macro ovar{varname}
108 @r{[}@var{\varname\}@r{]}@c
109 @end macro
110 @c Status as of November 2009:
111 @c Unfortunately texi2pdf and texi2html treat the trailing "@c"
112 @c differently, and faulty output is produced by one or the other
113 @c depending on whether the "@c" is present or absent.
114 @c As a result, the @ovar macro is not used, and all invocations
115 @c of the @ovar macro have been expanded inline.
116
117
118 @settitle @value{EDITION} User's Guide @value{TITLESUFFIX}
119 @dircategory GNU Ada tools
120 @direntry
121 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
122 @end direntry
123
124 @include gcc-common.texi
125
126 @setchapternewpage odd
127 @syncodeindex fn cp
128 @c %**end of header
129
130 @titlepage
131 @title @value{EDITION} User's Guide
132 @ifset vms
133 @sp 1
134 @flushright
135 @titlefont{@i{@value{PLATFORM}}}
136 @end flushright
137 @end ifset
138
139 @sp 2
140
141 @subtitle GNAT, The GNU Ada Compiler
142 @versionsubtitle
143 @author AdaCore
144
145 @page
146 @vskip 0pt plus 1filll
147
148 @insertcopying
149
150 @end titlepage
151
152 @ifnottex
153 @node Top, About This Guide, (dir), (dir)
154 @top @value{EDITION} User's Guide
155
156 @noindent
157 @value{EDITION} User's Guide @value{PLATFORM}
158
159 @noindent
160 GNAT, The GNU Ada Compiler@*
161 GCC version @value{version-GCC}@*
162
163 @noindent
164 AdaCore@*
165
166 @menu
167 * About This Guide::
168 * Getting Started with GNAT::
169 * The GNAT Compilation Model::
170 * Compiling with gcc::
171 * Binding with gnatbind::
172 * Linking with gnatlink::
173 * The GNAT Make Program gnatmake::
174 * Improving Performance::
175 * Renaming Files with gnatchop::
176 * Configuration Pragmas::
177 * Handling Arbitrary File Naming Conventions with gnatname::
178 * GNAT Project Manager::
179 * Tools Supporting Project Files::
180 * The Cross-Referencing Tools gnatxref and gnatfind::
181 * The GNAT Pretty-Printer gnatpp::
182 @ifclear vms
183 * The Ada-to-XML converter gnat2xml::
184 @end ifclear
185 * The GNAT Metrics Tool gnatmetric::
186 * File Name Krunching with gnatkr::
187 * Preprocessing with gnatprep::
188 * The GNAT Library Browser gnatls::
189 * Cleaning Up with gnatclean::
190 @ifclear vms
191 * GNAT and Libraries::
192 * Using the GNU make Utility::
193 @end ifclear
194 * Memory Management Issues::
195 * Stack Related Facilities::
196 * Verifying Properties with gnatcheck::
197 * Creating Sample Bodies with gnatstub::
198 * Creating Unit Tests with gnattest::
199 * Performing Dimensionality Analysis in GNAT::
200 * Generating Ada Bindings for C and C++ headers::
201 * Other Utility Programs::
202 @ifclear vms
203 * Code Coverage and Profiling::
204 @end ifclear
205 * Running and Debugging Ada Programs::
206 @ifset vms
207 * Compatibility with HP Ada::
208 @end ifset
209 * Platform-Specific Information for the Run-Time Libraries::
210 * Example of Binder Output File::
211 * Elaboration Order Handling in GNAT::
212 * Overflow Check Handling in GNAT::
213 * Conditional Compilation::
214 * Inline Assembler::
215 * Compatibility and Porting Guide::
216 * Microsoft Windows Topics::
217 * Mac OS Topics::
218 * GNU Free Documentation License::
219 * Index::
220 @end menu
221 @end ifnottex
222
223 @node About This Guide
224 @unnumbered About This Guide
225
226 @noindent
227 @ifset vms
228 This guide describes the use of @value{EDITION},
229 a compiler and software development toolset for the full Ada
230 programming language, implemented on OpenVMS for HP's Alpha and
231 Integrity server (I64) platforms.
232 @end ifset
233 @ifclear vms
234 This guide describes the use of @value{EDITION},
235 a compiler and software development
236 toolset for the full Ada programming language.
237 @end ifclear
238 It documents the features of the compiler and tools, and explains
239 how to use them to build Ada applications.
240
241 @value{EDITION} implements Ada 95, Ada 2005 and Ada 2012, and it may also be
242 invoked in Ada 83 compatibility mode.
243 By default, @value{EDITION} assumes Ada 2012, but you can override with a
244 compiler switch (@pxref{Compiling Different Versions of Ada})
245 to explicitly specify the language version.
246 Throughout this manual, references to ``Ada'' without a year suffix
247 apply to all Ada 95/2005/2012 versions of the language.
248
249 @ifclear FSFEDITION
250 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
251 ``GNAT'' in the remainder of this document.
252 @end ifclear
253
254
255 @menu
256 * What This Guide Contains::
257 * What You Should Know before Reading This Guide::
258 * Related Information::
259 * Conventions::
260 @end menu
261
262 @node What This Guide Contains
263 @unnumberedsec What This Guide Contains
264
265 @noindent
266 This guide contains the following chapters:
267 @itemize @bullet
268
269 @item
270 @ref{Getting Started with GNAT}, describes how to get started compiling
271 and running Ada programs with the GNAT Ada programming environment.
272 @item
273 @ref{The GNAT Compilation Model}, describes the compilation model used
274 by GNAT.
275
276 @item
277 @ref{Compiling with gcc}, describes how to compile
278 Ada programs with @command{gcc}, the Ada compiler.
279
280 @item
281 @ref{Binding with gnatbind}, describes how to
282 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
283 utility.
284
285 @item
286 @ref{Linking with gnatlink},
287 describes @command{gnatlink}, a
288 program that provides for linking using the GNAT run-time library to
289 construct a program. @command{gnatlink} can also incorporate foreign language
290 object units into the executable.
291
292 @item
293 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
294 utility that automatically determines the set of sources
295 needed by an Ada compilation unit, and executes the necessary compilations
296 binding and link.
297
298 @item
299 @ref{Improving Performance}, shows various techniques for making your
300 Ada program run faster or take less space.
301 It discusses the effect of the compiler's optimization switch and
302 also describes the @command{gnatelim} tool and unused subprogram/data
303 elimination.
304
305 @item
306 @ref{Renaming Files with gnatchop}, describes
307 @code{gnatchop}, a utility that allows you to preprocess a file that
308 contains Ada source code, and split it into one or more new files, one
309 for each compilation unit.
310
311 @item
312 @ref{Configuration Pragmas}, describes the configuration pragmas
313 handled by GNAT.
314
315 @item
316 @ref{Handling Arbitrary File Naming Conventions with gnatname},
317 shows how to override the default GNAT file naming conventions,
318 either for an individual unit or globally.
319
320 @item
321 @ref{GNAT Project Manager}, describes how to use project files
322 to organize large projects.
323
324 @item
325 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
326 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
327 way to navigate through sources.
328
329 @item
330 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
331 version of an Ada source file with control over casing, indentation,
332 comment placement, and other elements of program presentation style.
333
334 @ifclear vms
335 @item
336 @ref{The Ada-to-XML converter gnat2xml}, shows how to convert Ada
337 source code into XML.
338 @end ifclear
339
340 @item
341 @ref{The GNAT Metrics Tool gnatmetric}, shows how to compute various
342 metrics for an Ada source file, such as the number of types and subprograms,
343 and assorted complexity measures.
344
345 @item
346 @ref{File Name Krunching with gnatkr}, describes the @code{gnatkr}
347 file name krunching utility, used to handle shortened
348 file names on operating systems with a limit on the length of names.
349
350 @item
351 @ref{Preprocessing with gnatprep}, describes @code{gnatprep}, a
352 preprocessor utility that allows a single source file to be used to
353 generate multiple or parameterized source files by means of macro
354 substitution.
355
356 @item
357 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
358 utility that displays information about compiled units, including dependences
359 on the corresponding sources files, and consistency of compilations.
360
361 @item
362 @ref{Cleaning Up with gnatclean}, describes @code{gnatclean}, a utility
363 to delete files that are produced by the compiler, binder and linker.
364
365 @ifclear vms
366 @item
367 @ref{GNAT and Libraries}, describes the process of creating and using
368 Libraries with GNAT. It also describes how to recompile the GNAT run-time
369 library.
370
371 @item
372 @ref{Using the GNU make Utility}, describes some techniques for using
373 the GNAT toolset in Makefiles.
374 @end ifclear
375
376 @item
377 @ref{Memory Management Issues}, describes some useful predefined storage pools
378 and in particular the GNAT Debug Pool facility, which helps detect incorrect
379 memory references.
380 @ifclear vms
381 It also describes @command{gnatmem}, a utility that monitors dynamic
382 allocation and deallocation and helps detect ``memory leaks''.
383 @end ifclear
384
385 @item
386 @ref{Stack Related Facilities}, describes some useful tools associated with
387 stack checking and analysis.
388
389 @item
390 @ref{Verifying Properties with gnatcheck}, discusses @code{gnatcheck},
391 a utility that checks Ada code against a set of rules.
392
393 @item
394 @ref{Creating Sample Bodies with gnatstub}, discusses @code{gnatstub},
395 a utility that generates empty but compilable bodies for library units.
396
397 @item
398 @ref{Creating Unit Tests with gnattest}, discusses @code{gnattest},
399 a utility that generates unit testing templates for library units.
400
401 @item
402 @ref{Performing Dimensionality Analysis in GNAT}, describes the Ada 2012
403 facilities used in GNAT to declare dimensioned objects, and to verify that
404 uses of these objects are consistent with their given physical dimensions
405 (so that meters cannot be assigned to kilograms, and so on).
406
407 @item
408 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
409 generate automatically Ada bindings from C and C++ headers.
410
411 @item
412 @ref{Other Utility Programs}, discusses several other GNAT utilities,
413 including @code{gnathtml}.
414
415 @ifclear vms
416 @item
417 @ref{Code Coverage and Profiling}, describes how to perform a structural
418 coverage and profile the execution of Ada programs.
419 @end ifclear
420
421 @item
422 @ref{Running and Debugging Ada Programs}, describes how to run and debug
423 Ada programs.
424
425 @ifset vms
426 @item
427 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
428 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
429 developed by Digital Equipment Corporation and currently supported by HP.}
430 for OpenVMS Alpha. This product was formerly known as DEC Ada,
431 @cindex DEC Ada
432 and for
433 historical compatibility reasons, the relevant libraries still use the
434 DEC prefix.
435 @end ifset
436
437 @item
438 @ref{Platform-Specific Information for the Run-Time Libraries},
439 describes the various run-time
440 libraries supported by GNAT on various platforms and explains how to
441 choose a particular library.
442
443 @item
444 @ref{Example of Binder Output File}, shows the source code for the binder
445 output file for a sample program.
446
447 @item
448 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
449 you deal with elaboration order issues.
450
451 @item
452 @ref{Overflow Check Handling in GNAT}, describes how GNAT helps
453 you deal with arithmetic overflow issues.
454
455 @item
456 @ref{Conditional Compilation}, describes how to model conditional compilation,
457 both with Ada in general and with GNAT facilities in particular.
458
459 @item
460 @ref{Inline Assembler}, shows how to use the inline assembly facility
461 in an Ada program.
462
463 @item
464 @ref{Compatibility and Porting Guide}, contains sections on compatibility
465 of GNAT with other Ada development environments (including Ada 83 systems),
466 to assist in porting code from those environments.
467
468 @ifset unw
469 @item
470 @ref{Microsoft Windows Topics}, presents information relevant to the
471 Microsoft Windows platform.
472
473 @item
474 @ref{Mac OS Topics}, presents information relevant to Apple's OS X
475 platform.
476 @end ifset
477 @end itemize
478
479 @c *************************************************
480 @node What You Should Know before Reading This Guide
481 @c *************************************************
482 @unnumberedsec What You Should Know before Reading This Guide
483
484 @cindex Ada 95 Language Reference Manual
485 @cindex Ada 2005 Language Reference Manual
486 @noindent
487 This guide assumes a basic familiarity with the Ada 95 language, as
488 described in the International Standard ANSI/ISO/IEC-8652:1995, January
489 1995.
490 It does not require knowledge of the new features introduced by Ada 2005,
491 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
492 and Amendment 1).
493 Both reference manuals are included in the GNAT documentation
494 package.
495
496 @node Related Information
497 @unnumberedsec Related Information
498
499 @noindent
500 For further information about related tools, refer to the following
501 documents:
502
503 @itemize @bullet
504 @item
505 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
506 Reference Manual}, which contains all reference material for the GNAT
507 implementation of Ada.
508
509 @ifset unw
510 @item
511 @cite{Using the GNAT Programming Studio}, which describes the GPS
512 Integrated Development Environment.
513
514 @item
515 @cite{GNAT Programming Studio Tutorial}, which introduces the
516 main GPS features through examples.
517 @end ifset
518
519 @item
520 @cite{Ada 95 Reference Manual}, which contains reference
521 material for the Ada 95 programming language.
522
523 @item
524 @cite{Ada 2005 Reference Manual}, which contains reference
525 material for the Ada 2005 programming language.
526
527 @item
528 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
529 @ifset vms
530 in the GNU:[DOCS] directory,
531 @end ifset
532 for all details on the use of the GNU source-level debugger.
533
534 @item
535 @xref{Top,, The extensible self-documenting text editor, emacs,
536 GNU Emacs Manual},
537 @ifset vms
538 located in the GNU:[DOCS] directory if the EMACS kit is installed,
539 @end ifset
540 for full information on the extensible editor and programming
541 environment Emacs.
542
543 @end itemize
544
545 @c **************
546 @node Conventions
547 @unnumberedsec Conventions
548 @cindex Conventions
549 @cindex Typographical conventions
550
551 @noindent
552 Following are examples of the typographical and graphic conventions used
553 in this guide:
554
555 @itemize @bullet
556 @item
557 @code{Functions}, @command{utility program names}, @code{standard names},
558 and @code{classes}.
559
560 @item
561 @option{Option flags}
562
563 @item
564 @file{File names}, @samp{button names}, and @samp{field names}.
565
566 @item
567 @code{Variables}, @env{environment variables}, and @var{metasyntactic
568 variables}.
569
570 @item
571 @emph{Emphasis}.
572
573 @item
574 @r{[}optional information or parameters@r{]}
575
576 @item
577 Examples are described by text
578 @smallexample
579 and then shown this way.
580 @end smallexample
581 @end itemize
582
583 @noindent
584 Commands that are entered by the user are preceded in this manual by the
585 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
586 uses this sequence as a prompt, then the commands will appear exactly as
587 you see them in the manual. If your system uses some other prompt, then
588 the command will appear with the @code{$} replaced by whatever prompt
589 character you are using.
590
591 @ifset unw
592 Full file names are shown with the ``@code{/}'' character
593 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
594 If you are using GNAT on a Windows platform, please note that
595 the ``@code{\}'' character should be used instead.
596 @end ifset
597
598 @c ****************************
599 @node Getting Started with GNAT
600 @chapter Getting Started with GNAT
601
602 @noindent
603 This chapter describes some simple ways of using GNAT to build
604 executable Ada programs.
605 @ifset unw
606 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
607 show how to use the command line environment.
608 @ref{Introduction to GPS}, provides a brief
609 introduction to the GNAT Programming Studio, a visually-oriented
610 Integrated Development Environment for GNAT.
611 GPS offers a graphical ``look and feel'', support for development in
612 other programming languages, comprehensive browsing features, and
613 many other capabilities.
614 For information on GPS please refer to
615 @cite{Using the GNAT Programming Studio}.
616 @end ifset
617
618 @menu
619 * Running GNAT::
620 * Running a Simple Ada Program::
621 * Running a Program with Multiple Units::
622 * Using the gnatmake Utility::
623 @ifset vms
624 * Editing with Emacs::
625 @end ifset
626 @ifclear vms
627 * Introduction to GPS::
628 @end ifclear
629 @end menu
630
631 @node Running GNAT
632 @section Running GNAT
633
634 @noindent
635 Three steps are needed to create an executable file from an Ada source
636 file:
637
638 @enumerate
639 @item
640 The source file(s) must be compiled.
641 @item
642 The file(s) must be bound using the GNAT binder.
643 @item
644 All appropriate object files must be linked to produce an executable.
645 @end enumerate
646
647 @noindent
648 All three steps are most commonly handled by using the @command{gnatmake}
649 utility program that, given the name of the main program, automatically
650 performs the necessary compilation, binding and linking steps.
651
652 @node Running a Simple Ada Program
653 @section Running a Simple Ada Program
654
655 @noindent
656 Any text editor may be used to prepare an Ada program.
657 (If @code{Emacs} is
658 used, the optional Ada mode may be helpful in laying out the program.)
659 The
660 program text is a normal text file. We will assume in our initial
661 example that you have used your editor to prepare the following
662 standard format text file:
663
664 @smallexample @c ada
665 @cartouche
666 with Ada.Text_IO; use Ada.Text_IO;
667 procedure Hello is
668 begin
669    Put_Line ("Hello WORLD!");
670 end Hello;
671 @end cartouche
672 @end smallexample
673
674 @noindent
675 This file should be named @file{hello.adb}.
676 With the normal default file naming conventions, GNAT requires
677 that each file
678 contain a single compilation unit whose file name is the
679 unit name,
680 with periods replaced by hyphens; the
681 extension is @file{ads} for a
682 spec and @file{adb} for a body.
683 You can override this default file naming convention by use of the
684 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
685 Alternatively, if you want to rename your files according to this default
686 convention, which is probably more convenient if you will be using GNAT
687 for all your compilations, then the @code{gnatchop} utility
688 can be used to generate correctly-named source files
689 (@pxref{Renaming Files with gnatchop}).
690
691 You can compile the program using the following command (@code{$} is used
692 as the command prompt in the examples in this document):
693
694 @smallexample
695 $ gcc -c hello.adb
696 @end smallexample
697
698 @noindent
699 @command{gcc} is the command used to run the compiler. This compiler is
700 capable of compiling programs in several languages, including Ada and
701 C. It assumes that you have given it an Ada program if the file extension is
702 either @file{.ads} or @file{.adb}, and it will then call
703 the GNAT compiler to compile the specified file.
704
705 @ifclear vms
706 The @option{-c} switch is required. It tells @command{gcc} to only do a
707 compilation. (For C programs, @command{gcc} can also do linking, but this
708 capability is not used directly for Ada programs, so the @option{-c}
709 switch must always be present.)
710 @end ifclear
711
712 This compile command generates a file
713 @file{hello.o}, which is the object
714 file corresponding to your Ada program. It also generates
715 an ``Ada Library Information'' file @file{hello.ali},
716 which contains additional information used to check
717 that an Ada program is consistent.
718 To build an executable file,
719 use @code{gnatbind} to bind the program
720 and @command{gnatlink} to link it. The
721 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
722 @file{ALI} file, but the default extension of @file{.ali} can
723 be omitted. This means that in the most common case, the argument
724 is simply the name of the main program:
725
726 @smallexample
727 $ gnatbind hello
728 $ gnatlink hello
729 @end smallexample
730
731 @noindent
732 A simpler method of carrying out these steps is to use
733 @command{gnatmake},
734 a master program that invokes all the required
735 compilation, binding and linking tools in the correct order. In particular,
736 @command{gnatmake} automatically recompiles any sources that have been
737 modified since they were last compiled, or sources that depend
738 on such modified sources, so that ``version skew'' is avoided.
739 @cindex Version skew (avoided by @command{gnatmake})
740
741 @smallexample
742 $ gnatmake hello.adb
743 @end smallexample
744
745 @noindent
746 The result is an executable program called @file{hello}, which can be
747 run by entering:
748
749 @smallexample
750 $ ^hello^RUN HELLO^
751 @end smallexample
752
753 @noindent
754 assuming that the current directory is on the search path
755 for executable programs.
756
757 @noindent
758 and, if all has gone well, you will see
759
760 @smallexample
761 Hello WORLD!
762 @end smallexample
763
764 @noindent
765 appear in response to this command.
766
767 @c ****************************************
768 @node Running a Program with Multiple Units
769 @section Running a Program with Multiple Units
770
771 @noindent
772 Consider a slightly more complicated example that has three files: a
773 main program, and the spec and body of a package:
774
775 @smallexample @c ada
776 @cartouche
777 @group
778 package Greetings is
779    procedure Hello;
780    procedure Goodbye;
781 end Greetings;
782
783 with Ada.Text_IO; use Ada.Text_IO;
784 package body Greetings is
785    procedure Hello is
786    begin
787       Put_Line ("Hello WORLD!");
788    end Hello;
789
790    procedure Goodbye is
791    begin
792       Put_Line ("Goodbye WORLD!");
793    end Goodbye;
794 end Greetings;
795 @end group
796
797 @group
798 with Greetings;
799 procedure Gmain is
800 begin
801    Greetings.Hello;
802    Greetings.Goodbye;
803 end Gmain;
804 @end group
805 @end cartouche
806 @end smallexample
807
808 @noindent
809 Following the one-unit-per-file rule, place this program in the
810 following three separate files:
811
812 @table @file
813 @item greetings.ads
814 spec of package @code{Greetings}
815
816 @item greetings.adb
817 body of package @code{Greetings}
818
819 @item gmain.adb
820 body of main program
821 @end table
822
823 @noindent
824 To build an executable version of
825 this program, we could use four separate steps to compile, bind, and link
826 the program, as follows:
827
828 @smallexample
829 $ gcc -c gmain.adb
830 $ gcc -c greetings.adb
831 $ gnatbind gmain
832 $ gnatlink gmain
833 @end smallexample
834
835 @noindent
836 Note that there is no required order of compilation when using GNAT.
837 In particular it is perfectly fine to compile the main program first.
838 Also, it is not necessary to compile package specs in the case where
839 there is an accompanying body; you only need to compile the body. If you want
840 to submit these files to the compiler for semantic checking and not code
841 generation, then use the
842 @option{-gnatc} switch:
843
844 @smallexample
845 $ gcc -c greetings.ads -gnatc
846 @end smallexample
847
848 @noindent
849 Although the compilation can be done in separate steps as in the
850 above example, in practice it is almost always more convenient
851 to use the @command{gnatmake} tool. All you need to know in this case
852 is the name of the main program's source file. The effect of the above four
853 commands can be achieved with a single one:
854
855 @smallexample
856 $ gnatmake gmain.adb
857 @end smallexample
858
859 @noindent
860 In the next section we discuss the advantages of using @command{gnatmake} in
861 more detail.
862
863 @c *****************************
864 @node Using the gnatmake Utility
865 @section Using the @command{gnatmake} Utility
866
867 @noindent
868 If you work on a program by compiling single components at a time using
869 @command{gcc}, you typically keep track of the units you modify. In order to
870 build a consistent system, you compile not only these units, but also any
871 units that depend on the units you have modified.
872 For example, in the preceding case,
873 if you edit @file{gmain.adb}, you only need to recompile that file. But if
874 you edit @file{greetings.ads}, you must recompile both
875 @file{greetings.adb} and @file{gmain.adb}, because both files contain
876 units that depend on @file{greetings.ads}.
877
878 @code{gnatbind} will warn you if you forget one of these compilation
879 steps, so that it is impossible to generate an inconsistent program as a
880 result of forgetting to do a compilation. Nevertheless it is tedious and
881 error-prone to keep track of dependencies among units.
882 One approach to handle the dependency-bookkeeping is to use a
883 makefile. However, makefiles present maintenance problems of their own:
884 if the dependencies change as you change the program, you must make
885 sure that the makefile is kept up-to-date manually, which is also an
886 error-prone process.
887
888 The @command{gnatmake} utility takes care of these details automatically.
889 Invoke it using either one of the following forms:
890
891 @smallexample
892 $ gnatmake gmain.adb
893 $ gnatmake ^gmain^GMAIN^
894 @end smallexample
895
896 @noindent
897 The argument is the name of the file containing the main program;
898 you may omit the extension. @command{gnatmake}
899 examines the environment, automatically recompiles any files that need
900 recompiling, and binds and links the resulting set of object files,
901 generating the executable file, @file{^gmain^GMAIN.EXE^}.
902 In a large program, it
903 can be extremely helpful to use @command{gnatmake}, because working out by hand
904 what needs to be recompiled can be difficult.
905
906 Note that @command{gnatmake}
907 takes into account all the Ada rules that
908 establish dependencies among units. These include dependencies that result
909 from inlining subprogram bodies, and from
910 generic instantiation. Unlike some other
911 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
912 found by the compiler on a previous compilation, which may possibly
913 be wrong when sources change. @command{gnatmake} determines the exact set of
914 dependencies from scratch each time it is run.
915
916 @ifset vms
917 @node Editing with Emacs
918 @section Editing with Emacs
919 @cindex Emacs
920
921 @noindent
922 Emacs is an extensible self-documenting text editor that is available in a
923 separate VMSINSTAL kit.
924
925 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
926 click on the Emacs Help menu and run the Emacs Tutorial.
927 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
928 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
929
930 Documentation on Emacs and other tools is available in Emacs under the
931 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
932 use the middle mouse button to select a topic (e.g.@: Emacs).
933
934 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
935 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
936 get to the Emacs manual.
937 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
938 prompt.
939
940 The tutorial is highly recommended in order to learn the intricacies of Emacs,
941 which is sufficiently extensible to provide for a complete programming
942 environment and shell for the sophisticated user.
943 @end ifset
944
945 @ifclear vms
946 @node Introduction to GPS
947 @section Introduction to GPS
948 @cindex GPS (GNAT Programming Studio)
949 @cindex GNAT Programming Studio (GPS)
950 @noindent
951 Although the command line interface (@command{gnatmake}, etc.) alone
952 is sufficient, a graphical Interactive Development
953 Environment can make it easier for you to compose, navigate, and debug
954 programs.  This section describes the main features of GPS
955 (``GNAT Programming Studio''), the GNAT graphical IDE.
956 You will see how to use GPS to build and debug an executable, and
957 you will also learn some of the basics of the GNAT ``project'' facility.
958
959 GPS enables you to do much more than is presented here;
960 e.g., you can produce a call graph, interface to a third-party
961 Version Control System, and inspect the generated assembly language
962 for a program.
963 Indeed, GPS also supports languages other than Ada.
964 Such additional information, and an explanation of all of the GPS menu
965 items. may be found in the on-line help, which includes
966 a user's guide and a tutorial (these are also accessible from the GNAT
967 startup menu).
968
969 @menu
970 * Building a New Program with GPS::
971 * Simple Debugging with GPS::
972 @end menu
973
974 @node Building a New Program with GPS
975 @subsection Building a New Program with GPS
976 @noindent
977 GPS invokes the GNAT compilation tools using information
978 contained in a @emph{project} (also known as a @emph{project file}):
979 a collection of properties such
980 as source directories, identities of main subprograms, tool switches, etc.,
981 and their associated values.
982 See @ref{GNAT Project Manager} for details.
983 In order to run GPS, you will need to either create a new project
984 or else open an existing one.
985
986 This section will explain how you can use GPS to create a project,
987 to associate Ada source files with a project, and to build and run
988 programs.
989
990 @enumerate
991 @item @emph{Creating a project}
992
993 Invoke GPS, either from the command line or the platform's IDE.
994 After it starts, GPS will display a ``Welcome'' screen with three
995 radio buttons:
996
997 @itemize @bullet
998 @item
999 @code{Start with default project in directory}
1000
1001 @item
1002 @code{Create new project with wizard}
1003
1004 @item
1005 @code{Open existing project}
1006 @end itemize
1007
1008 @noindent
1009 Select @code{Create new project with wizard} and press @code{OK}.
1010 A new window will appear.  In the text box labeled with
1011 @code{Enter the name of the project to create}, type @file{sample}
1012 as the project name.
1013 In the next box, browse to choose the directory in which you
1014 would like to create the project file.
1015 After selecting an appropriate directory, press @code{Forward}.
1016
1017 A window will appear with the title
1018 @code{Version Control System Configuration}.
1019 Simply press @code{Forward}.
1020
1021 A window will appear with the title
1022 @code{Please select the source directories for this project}.
1023 The directory that you specified for the project file will be selected
1024 by default as the one to use for sources; simply press @code{Forward}.
1025
1026 A window will appear with the title
1027 @code{Please select the build directory for this project}.
1028 The directory that you specified for the project file will be selected
1029 by default for object files and executables;
1030 simply press @code{Forward}.
1031
1032 A window will appear with the title
1033 @code{Please select the main units for this project}.
1034 You will supply this information later, after creating the source file.
1035 Simply press @code{Forward} for now.
1036
1037 A window will appear with the title
1038 @code{Please select the switches to build the project}.
1039 Press @code{Apply}.  This will create a project file named
1040 @file{sample.prj} in the directory that you had specified.
1041
1042 @item @emph{Creating and saving the source file}
1043
1044 After you create the new project, a GPS window will appear, which is
1045 partitioned into two main sections:
1046
1047 @itemize @bullet
1048 @item
1049 A @emph{Workspace area}, initially greyed out, which you will use for
1050 creating and editing source files
1051
1052 @item
1053 Directly below, a @emph{Messages area}, which initially displays a
1054 ``Welcome'' message.
1055 (If the Messages area is not visible, drag its border upward to expand it.)
1056 @end itemize
1057
1058 @noindent
1059 Select @code{File} on the menu bar, and then the @code{New} command.
1060 The Workspace area will become white, and you can now
1061 enter the source program explicitly.
1062 Type the following text
1063
1064 @smallexample @c ada
1065 @group
1066 with Ada.Text_IO; use Ada.Text_IO;
1067 procedure Hello is
1068 begin
1069   Put_Line("Hello from GPS!");
1070 end Hello;
1071 @end group
1072 @end smallexample
1073
1074 @noindent
1075 Select @code{File}, then @code{Save As}, and enter the source file name
1076 @file{hello.adb}.
1077 The file will be saved in the same directory you specified as the
1078 location of the default project file.
1079
1080 @item @emph{Updating the project file}
1081
1082 You need to add the new source file to the project.
1083 To do this, select
1084 the @code{Project} menu and then @code{Edit project properties}.
1085 Click the @code{Main files} tab on the left, and then the
1086 @code{Add} button.
1087 Choose @file{hello.adb} from the list, and press @code{Open}.
1088 The project settings window will reflect this action.
1089 Click @code{OK}.
1090
1091 @item @emph{Building and running the program}
1092
1093 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1094 and select @file{hello.adb}.
1095 The Messages window will display the resulting invocations of @command{gcc},
1096 @command{gnatbind}, and @command{gnatlink}
1097 (reflecting the default switch settings from the
1098 project file that you created) and then a ``successful compilation/build''
1099 message.
1100
1101 To run the program, choose the @code{Build} menu, then @code{Run}, and
1102 select @command{hello}.
1103 An @emph{Arguments Selection} window will appear.
1104 There are no command line arguments, so just click @code{OK}.
1105
1106 The Messages window will now display the program's output (the string
1107 @code{Hello from GPS}), and at the bottom of the GPS window a status
1108 update is displayed (@code{Run: hello}).
1109 Close the GPS window (or select @code{File}, then @code{Exit}) to
1110 terminate this GPS session.
1111 @end enumerate
1112
1113 @node Simple Debugging with GPS
1114 @subsection Simple Debugging with GPS
1115 @noindent
1116 This section illustrates basic debugging techniques (setting breakpoints,
1117 examining/modifying variables, single stepping).
1118
1119 @enumerate
1120 @item @emph{Opening a project}
1121
1122 Start GPS and select @code{Open existing project}; browse to
1123 specify the project file @file{sample.prj} that you had created in the
1124 earlier example.
1125
1126 @item @emph{Creating a source file}
1127
1128 Select @code{File}, then @code{New}, and type in the following program:
1129
1130 @smallexample @c ada
1131 @group
1132 with Ada.Text_IO; use Ada.Text_IO;
1133 procedure Example is
1134    Line : String (1..80);
1135    N    : Natural;
1136 begin
1137    Put_Line("Type a line of text at each prompt; an empty line to exit");
1138    loop
1139       Put(": ");
1140       Get_Line (Line, N);
1141       Put_Line (Line (1..N) );
1142       exit when N=0;
1143    end loop;
1144 end Example;
1145 @end group
1146 @end smallexample
1147
1148 @noindent
1149 Select @code{File}, then @code{Save as}, and enter the file name
1150 @file{example.adb}.
1151
1152 @item @emph{Updating the project file}
1153
1154 Add @code{Example} as a new main unit for the project:
1155 @enumerate a
1156 @item
1157 Select @code{Project}, then @code{Edit Project Properties}.
1158
1159 @item
1160 Select the @code{Main files} tab, click @code{Add}, then
1161 select the file @file{example.adb} from the list, and
1162 click @code{Open}.
1163 You will see the file name appear in the list of main units
1164
1165 @item
1166 Click @code{OK}
1167 @end enumerate
1168
1169 @item @emph{Building/running the executable}
1170
1171 To build the executable
1172 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1173
1174 Run the program to see its effect (in the Messages area).
1175 Each line that you enter is displayed; an empty line will
1176 cause the loop to exit and the program to terminate.
1177
1178 @item @emph{Debugging the program}
1179
1180 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1181 which are required for debugging, are on by default when you create
1182 a new project.
1183 Thus unless you intentionally remove these settings, you will be able
1184 to debug any program that you develop using GPS.
1185
1186 @enumerate a
1187 @item @emph{Initializing}
1188
1189 Select @code{Debug}, then @code{Initialize}, then @file{example}
1190
1191 @item @emph{Setting a breakpoint}
1192
1193 After performing the initialization step, you will observe a small
1194 icon to the right of each line number.
1195 This serves as a toggle for breakpoints; clicking the icon will
1196 set a breakpoint at the corresponding line (the icon will change to
1197 a red circle with an ``x''), and clicking it again
1198 will remove the breakpoint / reset the icon.
1199
1200 For purposes of this example, set a breakpoint at line 10 (the
1201 statement @code{Put_Line@ (Line@ (1..N));}
1202
1203 @item @emph{Starting program execution}
1204
1205 Select @code{Debug}, then @code{Run}.  When the
1206 @code{Program Arguments} window appears, click @code{OK}.
1207 A console window will appear; enter some line of text,
1208 e.g.@: @code{abcde}, at the prompt.
1209 The program will pause execution when it gets to the
1210 breakpoint, and the corresponding line is highlighted.
1211
1212 @item @emph{Examining a variable}
1213
1214 Move the mouse over one of the occurrences of the variable @code{N}.
1215 You will see the value (5) displayed, in ``tool tip'' fashion.
1216 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1217 You will see information about @code{N} appear in the @code{Debugger Data}
1218 pane, showing the value as 5.
1219
1220 @item @emph{Assigning a new value to a variable}
1221
1222 Right click on the @code{N} in the @code{Debugger Data} pane, and
1223 select @code{Set value of N}.
1224 When the input window appears, enter the value @code{4} and click
1225 @code{OK}.
1226 This value does not automatically appear in the @code{Debugger Data}
1227 pane; to see it, right click again on the @code{N} in the
1228 @code{Debugger Data} pane and select @code{Update value}.
1229 The new value, 4, will appear in red.
1230
1231 @item @emph{Single stepping}
1232
1233 Select @code{Debug}, then @code{Next}.
1234 This will cause the next statement to be executed, in this case the
1235 call of @code{Put_Line} with the string slice.
1236 Notice in the console window that the displayed string is simply
1237 @code{abcd} and not @code{abcde} which you had entered.
1238 This is because the upper bound of the slice is now 4 rather than 5.
1239
1240 @item @emph{Removing a breakpoint}
1241
1242 Toggle the breakpoint icon at line 10.
1243
1244 @item @emph{Resuming execution from a breakpoint}
1245
1246 Select @code{Debug}, then @code{Continue}.
1247 The program will reach the next iteration of the loop, and
1248 wait for input after displaying the prompt.
1249 This time, just hit the @kbd{Enter} key.
1250 The value of @code{N} will be 0, and the program will terminate.
1251 The console window will disappear.
1252 @end enumerate
1253 @end enumerate
1254 @end ifclear
1255
1256 @node The GNAT Compilation Model
1257 @chapter The GNAT Compilation Model
1258 @cindex GNAT compilation model
1259 @cindex Compilation model
1260
1261 @menu
1262 * Source Representation::
1263 * Foreign Language Representation::
1264 * File Naming Rules::
1265 * Using Other File Names::
1266 * Alternative File Naming Schemes::
1267 * Generating Object Files::
1268 * Source Dependencies::
1269 * The Ada Library Information Files::
1270 * Binding an Ada Program::
1271 * Mixed Language Programming::
1272 @ifclear vms
1273 * Building Mixed Ada & C++ Programs::
1274 * Comparison between GNAT and C/C++ Compilation Models::
1275 @end ifclear
1276 * Comparison between GNAT and Conventional Ada Library Models::
1277 @ifset vms
1278 * Placement of temporary files::
1279 @end ifset
1280 @end menu
1281
1282 @noindent
1283 This chapter describes the compilation model used by GNAT. Although
1284 similar to that used by other languages, such as C and C++, this model
1285 is substantially different from the traditional Ada compilation models,
1286 which are based on a library. The model is initially described without
1287 reference to the library-based model. If you have not previously used an
1288 Ada compiler, you need only read the first part of this chapter. The
1289 last section describes and discusses the differences between the GNAT
1290 model and the traditional Ada compiler models. If you have used other
1291 Ada compilers, this section will help you to understand those
1292 differences, and the advantages of the GNAT model.
1293
1294 @node Source Representation
1295 @section Source Representation
1296 @cindex Latin-1
1297
1298 @noindent
1299 Ada source programs are represented in standard text files, using
1300 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1301 7-bit ASCII set, plus additional characters used for
1302 representing foreign languages (@pxref{Foreign Language Representation}
1303 for support of non-USA character sets). The format effector characters
1304 are represented using their standard ASCII encodings, as follows:
1305
1306 @table @code
1307 @item VT
1308 @findex VT
1309 Vertical tab, @code{16#0B#}
1310
1311 @item HT
1312 @findex HT
1313 Horizontal tab, @code{16#09#}
1314
1315 @item CR
1316 @findex CR
1317 Carriage return, @code{16#0D#}
1318
1319 @item LF
1320 @findex LF
1321 Line feed, @code{16#0A#}
1322
1323 @item FF
1324 @findex FF
1325 Form feed, @code{16#0C#}
1326 @end table
1327
1328 @noindent
1329 Source files are in standard text file format. In addition, GNAT will
1330 recognize a wide variety of stream formats, in which the end of
1331 physical lines is marked by any of the following sequences:
1332 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1333 in accommodating files that are imported from other operating systems.
1334
1335 @cindex End of source file
1336 @cindex Source file, end
1337 @findex SUB
1338 The end of a source file is normally represented by the physical end of
1339 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1340 recognized as signalling the end of the source file. Again, this is
1341 provided for compatibility with other operating systems where this
1342 code is used to represent the end of file.
1343
1344 Each file contains a single Ada compilation unit, including any pragmas
1345 associated with the unit. For example, this means you must place a
1346 package declaration (a package @dfn{spec}) and the corresponding body in
1347 separate files. An Ada @dfn{compilation} (which is a sequence of
1348 compilation units) is represented using a sequence of files. Similarly,
1349 you will place each subunit or child unit in a separate file.
1350
1351 @node Foreign Language Representation
1352 @section Foreign Language Representation
1353
1354 @noindent
1355 GNAT supports the standard character sets defined in Ada as well as
1356 several other non-standard character sets for use in localized versions
1357 of the compiler (@pxref{Character Set Control}).
1358 @menu
1359 * Latin-1::
1360 * Other 8-Bit Codes::
1361 * Wide Character Encodings::
1362 @end menu
1363
1364 @node Latin-1
1365 @subsection Latin-1
1366 @cindex Latin-1
1367
1368 @noindent
1369 The basic character set is Latin-1. This character set is defined by ISO
1370 standard 8859, part 1. The lower half (character codes @code{16#00#}
1371 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1372 half is used to represent additional characters. These include extended letters
1373 used by European languages, such as French accents, the vowels with umlauts
1374 used in German, and the extra letter A-ring used in Swedish.
1375
1376 @findex Ada.Characters.Latin_1
1377 For a complete list of Latin-1 codes and their encodings, see the source
1378 file of library unit @code{Ada.Characters.Latin_1} in file
1379 @file{a-chlat1.ads}.
1380 You may use any of these extended characters freely in character or
1381 string literals. In addition, the extended characters that represent
1382 letters can be used in identifiers.
1383
1384 @node Other 8-Bit Codes
1385 @subsection Other 8-Bit Codes
1386
1387 @noindent
1388 GNAT also supports several other 8-bit coding schemes:
1389
1390 @table @asis
1391 @item ISO 8859-2 (Latin-2)
1392 @cindex Latin-2
1393 @cindex ISO 8859-2
1394 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1395 equivalence.
1396
1397 @item ISO 8859-3 (Latin-3)
1398 @cindex Latin-3
1399 @cindex ISO 8859-3
1400 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1401 equivalence.
1402
1403 @item ISO 8859-4 (Latin-4)
1404 @cindex Latin-4
1405 @cindex ISO 8859-4
1406 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1407 equivalence.
1408
1409 @item ISO 8859-5 (Cyrillic)
1410 @cindex ISO 8859-5
1411 @cindex Cyrillic
1412 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1413 lowercase equivalence.
1414
1415 @item ISO 8859-15 (Latin-9)
1416 @cindex ISO 8859-15
1417 @cindex Latin-9
1418 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1419 lowercase equivalence
1420
1421 @item IBM PC (code page 437)
1422 @cindex code page 437
1423 This code page is the normal default for PCs in the U.S. It corresponds
1424 to the original IBM PC character set. This set has some, but not all, of
1425 the extended Latin-1 letters, but these letters do not have the same
1426 encoding as Latin-1. In this mode, these letters are allowed in
1427 identifiers with uppercase and lowercase equivalence.
1428
1429 @item IBM PC (code page 850)
1430 @cindex code page 850
1431 This code page is a modification of 437 extended to include all the
1432 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1433 mode, all these letters are allowed in identifiers with uppercase and
1434 lowercase equivalence.
1435
1436 @item Full Upper 8-bit
1437 Any character in the range 80-FF allowed in identifiers, and all are
1438 considered distinct. In other words, there are no uppercase and lowercase
1439 equivalences in this range. This is useful in conjunction with
1440 certain encoding schemes used for some foreign character sets (e.g.,
1441 the typical method of representing Chinese characters on the PC).
1442
1443 @item No Upper-Half
1444 No upper-half characters in the range 80-FF are allowed in identifiers.
1445 This gives Ada 83 compatibility for identifier names.
1446 @end table
1447
1448 @noindent
1449 For precise data on the encodings permitted, and the uppercase and lowercase
1450 equivalences that are recognized, see the file @file{csets.adb} in
1451 the GNAT compiler sources. You will need to obtain a full source release
1452 of GNAT to obtain this file.
1453
1454 @node Wide Character Encodings
1455 @subsection Wide Character Encodings
1456
1457 @noindent
1458 GNAT allows wide character codes to appear in character and string
1459 literals, and also optionally in identifiers, by means of the following
1460 possible encoding schemes:
1461
1462 @table @asis
1463
1464 @item Hex Coding
1465 In this encoding, a wide character is represented by the following five
1466 character sequence:
1467
1468 @smallexample
1469 ESC a b c d
1470 @end smallexample
1471
1472 @noindent
1473 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1474 characters (using uppercase letters) of the wide character code. For
1475 example, ESC A345 is used to represent the wide character with code
1476 @code{16#A345#}.
1477 This scheme is compatible with use of the full Wide_Character set.
1478
1479 @item Upper-Half Coding
1480 @cindex Upper-Half Coding
1481 The wide character with encoding @code{16#abcd#} where the upper bit is on
1482 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1483 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1484 character, but is not required to be in the upper half. This method can
1485 be also used for shift-JIS or EUC, where the internal coding matches the
1486 external coding.
1487
1488 @item Shift JIS Coding
1489 @cindex Shift JIS Coding
1490 A wide character is represented by a two-character sequence,
1491 @code{16#ab#} and
1492 @code{16#cd#}, with the restrictions described for upper-half encoding as
1493 described above. The internal character code is the corresponding JIS
1494 character according to the standard algorithm for Shift-JIS
1495 conversion. Only characters defined in the JIS code set table can be
1496 used with this encoding method.
1497
1498 @item EUC Coding
1499 @cindex EUC Coding
1500 A wide character is represented by a two-character sequence
1501 @code{16#ab#} and
1502 @code{16#cd#}, with both characters being in the upper half. The internal
1503 character code is the corresponding JIS character according to the EUC
1504 encoding algorithm. Only characters defined in the JIS code set table
1505 can be used with this encoding method.
1506
1507 @item UTF-8 Coding
1508 A wide character is represented using
1509 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1510 10646-1/Am.2. Depending on the character value, the representation
1511 is a one, two, or three byte sequence:
1512 @smallexample
1513 @iftex
1514 @leftskip=.7cm
1515 @end iftex
1516 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1517 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1518 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1519
1520 @end smallexample
1521
1522 @noindent
1523 where the @var{xxx} bits correspond to the left-padded bits of the
1524 16-bit character value. Note that all lower half ASCII characters
1525 are represented as ASCII bytes and all upper half characters and
1526 other wide characters are represented as sequences of upper-half
1527 (The full UTF-8 scheme allows for encoding 31-bit characters as
1528 6-byte sequences, but in this implementation, all UTF-8 sequences
1529 of four or more bytes length will be treated as illegal).
1530 @item Brackets Coding
1531 In this encoding, a wide character is represented by the following eight
1532 character sequence:
1533
1534 @smallexample
1535 [ " a b c d " ]
1536 @end smallexample
1537
1538 @noindent
1539 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1540 characters (using uppercase letters) of the wide character code. For
1541 example, [``A345''] is used to represent the wide character with code
1542 @code{16#A345#}. It is also possible (though not required) to use the
1543 Brackets coding for upper half characters. For example, the code
1544 @code{16#A3#} can be represented as @code{[``A3'']}.
1545
1546 This scheme is compatible with use of the full Wide_Character set,
1547 and is also the method used for wide character encoding in the standard
1548 ACVC (Ada Compiler Validation Capability) test suite distributions.
1549
1550 @end table
1551
1552 @noindent
1553 Note: Some of these coding schemes do not permit the full use of the
1554 Ada character set. For example, neither Shift JIS, nor EUC allow the
1555 use of the upper half of the Latin-1 set.
1556
1557 @node File Naming Rules
1558 @section File Naming Rules
1559
1560 @noindent
1561 The default file name is determined by the name of the unit that the
1562 file contains. The name is formed by taking the full expanded name of
1563 the unit and replacing the separating dots with hyphens and using
1564 ^lowercase^uppercase^ for all letters.
1565
1566 An exception arises if the file name generated by the above rules starts
1567 with one of the characters
1568 @ifset vms
1569 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1570 @end ifset
1571 @ifclear vms
1572 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1573 @end ifclear
1574 and the second character is a
1575 minus. In this case, the character ^tilde^dollar sign^ is used in place
1576 of the minus. The reason for this special rule is to avoid clashes with
1577 the standard names for child units of the packages System, Ada,
1578 Interfaces, and GNAT, which use the prefixes
1579 @ifset vms
1580 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
1581 @end ifset
1582 @ifclear vms
1583 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
1584 @end ifclear
1585 respectively.
1586
1587 The file extension is @file{.ads} for a spec and
1588 @file{.adb} for a body. The following list shows some
1589 examples of these rules.
1590
1591 @table @file
1592 @item main.ads
1593 Main (spec)
1594 @item main.adb
1595 Main (body)
1596 @item arith_functions.ads
1597 Arith_Functions (package spec)
1598 @item arith_functions.adb
1599 Arith_Functions (package body)
1600 @item func-spec.ads
1601 Func.Spec (child package spec)
1602 @item func-spec.adb
1603 Func.Spec (child package body)
1604 @item main-sub.adb
1605 Sub (subunit of Main)
1606 @item ^a~bad.adb^A$BAD.ADB^
1607 A.Bad (child package body)
1608 @end table
1609
1610 @noindent
1611 Following these rules can result in excessively long
1612 file names if corresponding
1613 unit names are long (for example, if child units or subunits are
1614 heavily nested). An option is available to shorten such long file names
1615 (called file name ``krunching''). This may be particularly useful when
1616 programs being developed with GNAT are to be used on operating systems
1617 with limited file name lengths. @xref{Using gnatkr}.
1618
1619 Of course, no file shortening algorithm can guarantee uniqueness over
1620 all possible unit names; if file name krunching is used, it is your
1621 responsibility to ensure no name clashes occur. Alternatively you
1622 can specify the exact file names that you want used, as described
1623 in the next section. Finally, if your Ada programs are migrating from a
1624 compiler with a different naming convention, you can use the gnatchop
1625 utility to produce source files that follow the GNAT naming conventions.
1626 (For details @pxref{Renaming Files with gnatchop}.)
1627
1628 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
1629 systems, case is not significant. So for example on @code{Windows XP}
1630 if the canonical name is @code{main-sub.adb}, you can use the file name
1631 @code{Main-Sub.adb} instead. However, case is significant for other
1632 operating systems, so for example, if you want to use other than
1633 canonically cased file names on a Unix system, you need to follow
1634 the procedures described in the next section.
1635
1636 @node Using Other File Names
1637 @section Using Other File Names
1638 @cindex File names
1639
1640 @noindent
1641 In the previous section, we have described the default rules used by
1642 GNAT to determine the file name in which a given unit resides. It is
1643 often convenient to follow these default rules, and if you follow them,
1644 the compiler knows without being explicitly told where to find all
1645 the files it needs.
1646
1647 However, in some cases, particularly when a program is imported from
1648 another Ada compiler environment, it may be more convenient for the
1649 programmer to specify which file names contain which units. GNAT allows
1650 arbitrary file names to be used by means of the Source_File_Name pragma.
1651 The form of this pragma is as shown in the following examples:
1652 @cindex Source_File_Name pragma
1653
1654 @smallexample @c ada
1655 @cartouche
1656 pragma Source_File_Name (My_Utilities.Stacks,
1657   Spec_File_Name => "myutilst_a.ada");
1658 pragma Source_File_name (My_Utilities.Stacks,
1659   Body_File_Name => "myutilst.ada");
1660 @end cartouche
1661 @end smallexample
1662
1663 @noindent
1664 As shown in this example, the first argument for the pragma is the unit
1665 name (in this example a child unit). The second argument has the form
1666 of a named association. The identifier
1667 indicates whether the file name is for a spec or a body;
1668 the file name itself is given by a string literal.
1669
1670 The source file name pragma is a configuration pragma, which means that
1671 normally it will be placed in the @file{gnat.adc}
1672 file used to hold configuration
1673 pragmas that apply to a complete compilation environment.
1674 For more details on how the @file{gnat.adc} file is created and used
1675 see @ref{Handling of Configuration Pragmas}.
1676 @cindex @file{gnat.adc}
1677
1678 @ifclear vms
1679 GNAT allows completely arbitrary file names to be specified using the
1680 source file name pragma. However, if the file name specified has an
1681 extension other than @file{.ads} or @file{.adb} it is necessary to use
1682 a special syntax when compiling the file. The name in this case must be
1683 preceded by the special sequence @option{-x} followed by a space and the name
1684 of the language, here @code{ada}, as in:
1685
1686 @smallexample
1687 $ gcc -c -x ada peculiar_file_name.sim
1688 @end smallexample
1689 @end ifclear
1690
1691 @noindent
1692 @command{gnatmake} handles non-standard file names in the usual manner (the
1693 non-standard file name for the main program is simply used as the
1694 argument to gnatmake). Note that if the extension is also non-standard,
1695 then it must be included in the @command{gnatmake} command, it may not
1696 be omitted.
1697
1698 @node Alternative File Naming Schemes
1699 @section Alternative File Naming Schemes
1700 @cindex File naming schemes, alternative
1701 @cindex File names
1702
1703 In the previous section, we described the use of the @code{Source_File_Name}
1704 pragma to allow arbitrary names to be assigned to individual source files.
1705 However, this approach requires one pragma for each file, and especially in
1706 large systems can result in very long @file{gnat.adc} files, and also create
1707 a maintenance problem.
1708
1709 GNAT also provides a facility for specifying systematic file naming schemes
1710 other than the standard default naming scheme previously described. An
1711 alternative scheme for naming is specified by the use of
1712 @code{Source_File_Name} pragmas having the following format:
1713 @cindex Source_File_Name pragma
1714
1715 @smallexample @c ada
1716 pragma Source_File_Name (
1717    Spec_File_Name  => FILE_NAME_PATTERN
1718  @r{[},Casing          => CASING_SPEC@r{]}
1719  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1720
1721 pragma Source_File_Name (
1722    Body_File_Name  => FILE_NAME_PATTERN
1723  @r{[},Casing          => CASING_SPEC@r{]}
1724  @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1725
1726 pragma Source_File_Name (
1727    Subunit_File_Name  => FILE_NAME_PATTERN
1728  @r{[},Casing             => CASING_SPEC@r{]}
1729  @r{[},Dot_Replacement    => STRING_LITERAL@r{]});
1730
1731 FILE_NAME_PATTERN ::= STRING_LITERAL
1732 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1733 @end smallexample
1734
1735 @noindent
1736 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1737 It contains a single asterisk character, and the unit name is substituted
1738 systematically for this asterisk. The optional parameter
1739 @code{Casing} indicates
1740 whether the unit name is to be all upper-case letters, all lower-case letters,
1741 or mixed-case. If no
1742 @code{Casing} parameter is used, then the default is all
1743 ^lower-case^upper-case^.
1744
1745 The optional @code{Dot_Replacement} string is used to replace any periods
1746 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1747 argument is used then separating dots appear unchanged in the resulting
1748 file name.
1749 Although the above syntax indicates that the
1750 @code{Casing} argument must appear
1751 before the @code{Dot_Replacement} argument, but it
1752 is also permissible to write these arguments in the opposite order.
1753
1754 As indicated, it is possible to specify different naming schemes for
1755 bodies, specs, and subunits. Quite often the rule for subunits is the
1756 same as the rule for bodies, in which case, there is no need to give
1757 a separate @code{Subunit_File_Name} rule, and in this case the
1758 @code{Body_File_name} rule is used for subunits as well.
1759
1760 The separate rule for subunits can also be used to implement the rather
1761 unusual case of a compilation environment (e.g.@: a single directory) which
1762 contains a subunit and a child unit with the same unit name. Although
1763 both units cannot appear in the same partition, the Ada Reference Manual
1764 allows (but does not require) the possibility of the two units coexisting
1765 in the same environment.
1766
1767 The file name translation works in the following steps:
1768
1769 @itemize @bullet
1770
1771 @item
1772 If there is a specific @code{Source_File_Name} pragma for the given unit,
1773 then this is always used, and any general pattern rules are ignored.
1774
1775 @item
1776 If there is a pattern type @code{Source_File_Name} pragma that applies to
1777 the unit, then the resulting file name will be used if the file exists. If
1778 more than one pattern matches, the latest one will be tried first, and the
1779 first attempt resulting in a reference to a file that exists will be used.
1780
1781 @item
1782 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1783 for which the corresponding file exists, then the standard GNAT default
1784 naming rules are used.
1785
1786 @end itemize
1787
1788 @noindent
1789 As an example of the use of this mechanism, consider a commonly used scheme
1790 in which file names are all lower case, with separating periods copied
1791 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
1792 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
1793 two pragmas appear:
1794
1795 @smallexample @c ada
1796 pragma Source_File_Name
1797   (Spec_File_Name => "*.1.ada");
1798 pragma Source_File_Name
1799   (Body_File_Name => "*.2.ada");
1800 @end smallexample
1801
1802 @noindent
1803 The default GNAT scheme is actually implemented by providing the following
1804 default pragmas internally:
1805
1806 @smallexample @c ada
1807 pragma Source_File_Name
1808   (Spec_File_Name => "*.ads", Dot_Replacement => "-");
1809 pragma Source_File_Name
1810   (Body_File_Name => "*.adb", Dot_Replacement => "-");
1811 @end smallexample
1812
1813 @noindent
1814 Our final example implements a scheme typically used with one of the
1815 Ada 83 compilers, where the separator character for subunits was ``__''
1816 (two underscores), specs were identified by adding @file{_.ADA}, bodies
1817 by adding @file{.ADA}, and subunits by
1818 adding @file{.SEP}. All file names were
1819 upper case. Child units were not present of course since this was an
1820 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1821 the same double underscore separator for child units.
1822
1823 @smallexample @c ada
1824 pragma Source_File_Name
1825   (Spec_File_Name => "*_.ADA",
1826    Dot_Replacement => "__",
1827    Casing = Uppercase);
1828 pragma Source_File_Name
1829   (Body_File_Name => "*.ADA",
1830    Dot_Replacement => "__",
1831    Casing = Uppercase);
1832 pragma Source_File_Name
1833   (Subunit_File_Name => "*.SEP",
1834    Dot_Replacement => "__",
1835    Casing = Uppercase);
1836 @end smallexample
1837
1838 @node Generating Object Files
1839 @section Generating Object Files
1840
1841 @noindent
1842 An Ada program consists of a set of source files, and the first step in
1843 compiling the program is to generate the corresponding object files.
1844 These are generated by compiling a subset of these source files.
1845 The files you need to compile are the following:
1846
1847 @itemize @bullet
1848 @item
1849 If a package spec has no body, compile the package spec to produce the
1850 object file for the package.
1851
1852 @item
1853 If a package has both a spec and a body, compile the body to produce the
1854 object file for the package. The source file for the package spec need
1855 not be compiled in this case because there is only one object file, which
1856 contains the code for both the spec and body of the package.
1857
1858 @item
1859 For a subprogram, compile the subprogram body to produce the object file
1860 for the subprogram. The spec, if one is present, is as usual in a
1861 separate file, and need not be compiled.
1862
1863 @item
1864 @cindex Subunits
1865 In the case of subunits, only compile the parent unit. A single object
1866 file is generated for the entire subunit tree, which includes all the
1867 subunits.
1868
1869 @item
1870 Compile child units independently of their parent units
1871 (though, of course, the spec of all the ancestor unit must be present in order
1872 to compile a child unit).
1873
1874 @item
1875 @cindex Generics
1876 Compile generic units in the same manner as any other units. The object
1877 files in this case are small dummy files that contain at most the
1878 flag used for elaboration checking. This is because GNAT always handles generic
1879 instantiation by means of macro expansion. However, it is still necessary to
1880 compile generic units, for dependency checking and elaboration purposes.
1881 @end itemize
1882
1883 @noindent
1884 The preceding rules describe the set of files that must be compiled to
1885 generate the object files for a program. Each object file has the same
1886 name as the corresponding source file, except that the extension is
1887 @file{.o} as usual.
1888
1889 You may wish to compile other files for the purpose of checking their
1890 syntactic and semantic correctness. For example, in the case where a
1891 package has a separate spec and body, you would not normally compile the
1892 spec. However, it is convenient in practice to compile the spec to make
1893 sure it is error-free before compiling clients of this spec, because such
1894 compilations will fail if there is an error in the spec.
1895
1896 GNAT provides an option for compiling such files purely for the
1897 purposes of checking correctness; such compilations are not required as
1898 part of the process of building a program. To compile a file in this
1899 checking mode, use the @option{-gnatc} switch.
1900
1901 @node Source Dependencies
1902 @section Source Dependencies
1903
1904 @noindent
1905 A given object file clearly depends on the source file which is compiled
1906 to produce it. Here we are using @dfn{depends} in the sense of a typical
1907 @code{make} utility; in other words, an object file depends on a source
1908 file if changes to the source file require the object file to be
1909 recompiled.
1910 In addition to this basic dependency, a given object may depend on
1911 additional source files as follows:
1912
1913 @itemize @bullet
1914 @item
1915 If a file being compiled @code{with}'s a unit @var{X}, the object file
1916 depends on the file containing the spec of unit @var{X}. This includes
1917 files that are @code{with}'ed implicitly either because they are parents
1918 of @code{with}'ed child units or they are run-time units required by the
1919 language constructs used in a particular unit.
1920
1921 @item
1922 If a file being compiled instantiates a library level generic unit, the
1923 object file depends on both the spec and body files for this generic
1924 unit.
1925
1926 @item
1927 If a file being compiled instantiates a generic unit defined within a
1928 package, the object file depends on the body file for the package as
1929 well as the spec file.
1930
1931 @item
1932 @findex Inline
1933 @cindex @option{-gnatn} switch
1934 If a file being compiled contains a call to a subprogram for which
1935 pragma @code{Inline} applies and inlining is activated with the
1936 @option{-gnatn} switch, the object file depends on the file containing the
1937 body of this subprogram as well as on the file containing the spec. Note
1938 that for inlining to actually occur as a result of the use of this switch,
1939 it is necessary to compile in optimizing mode.
1940
1941 @cindex @option{-gnatN} switch
1942 The use of @option{-gnatN} activates  inlining optimization
1943 that is performed by the front end of the compiler. This inlining does
1944 not require that the code generation be optimized. Like @option{-gnatn},
1945 the use of this switch generates additional dependencies.
1946
1947 When using a gcc-based back end (in practice this means using any version
1948 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
1949 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
1950 Historically front end inlining was more extensive than the gcc back end
1951 inlining, but that is no longer the case.
1952
1953 @item
1954 If an object file @file{O} depends on the proper body of a subunit through
1955 inlining or instantiation, it depends on the parent unit of the subunit.
1956 This means that any modification of the parent unit or one of its subunits
1957 affects the compilation of @file{O}.
1958
1959 @item
1960 The object file for a parent unit depends on all its subunit body files.
1961
1962 @item
1963 The previous two rules meant that for purposes of computing dependencies and
1964 recompilation, a body and all its subunits are treated as an indivisible whole.
1965
1966 @noindent
1967 These rules are applied transitively: if unit @code{A} @code{with}'s
1968 unit @code{B}, whose elaboration calls an inlined procedure in package
1969 @code{C}, the object file for unit @code{A} will depend on the body of
1970 @code{C}, in file @file{c.adb}.
1971
1972 The set of dependent files described by these rules includes all the
1973 files on which the unit is semantically dependent, as dictated by the
1974 Ada language standard. However, it is a superset of what the
1975 standard describes, because it includes generic, inline, and subunit
1976 dependencies.
1977
1978 An object file must be recreated by recompiling the corresponding source
1979 file if any of the source files on which it depends are modified. For
1980 example, if the @code{make} utility is used to control compilation,
1981 the rule for an Ada object file must mention all the source files on
1982 which the object file depends, according to the above definition.
1983 The determination of the necessary
1984 recompilations is done automatically when one uses @command{gnatmake}.
1985 @end itemize
1986
1987 @node The Ada Library Information Files
1988 @section The Ada Library Information Files
1989 @cindex Ada Library Information files
1990 @cindex @file{ALI} files
1991
1992 @noindent
1993 Each compilation actually generates two output files. The first of these
1994 is the normal object file that has a @file{.o} extension. The second is a
1995 text file containing full dependency information. It has the same
1996 name as the source file, but an @file{.ali} extension.
1997 This file is known as the Ada Library Information (@file{ALI}) file.
1998 The following information is contained in the @file{ALI} file.
1999
2000 @itemize @bullet
2001 @item
2002 Version information (indicates which version of GNAT was used to compile
2003 the unit(s) in question)
2004
2005 @item
2006 Main program information (including priority and time slice settings,
2007 as well as the wide character encoding used during compilation).
2008
2009 @item
2010 List of arguments used in the @command{gcc} command for the compilation
2011
2012 @item
2013 Attributes of the unit, including configuration pragmas used, an indication
2014 of whether the compilation was successful, exception model used etc.
2015
2016 @item
2017 A list of relevant restrictions applying to the unit (used for consistency)
2018 checking.
2019
2020 @item
2021 Categorization information (e.g.@: use of pragma @code{Pure}).
2022
2023 @item
2024 Information on all @code{with}'ed units, including presence of
2025 @code{Elaborate} or @code{Elaborate_All} pragmas.
2026
2027 @item
2028 Information from any @code{Linker_Options} pragmas used in the unit
2029
2030 @item
2031 Information on the use of @code{Body_Version} or @code{Version}
2032 attributes in the unit.
2033
2034 @item
2035 Dependency information. This is a list of files, together with
2036 time stamp and checksum information. These are files on which
2037 the unit depends in the sense that recompilation is required
2038 if any of these units are modified.
2039
2040 @item
2041 Cross-reference data. Contains information on all entities referenced
2042 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2043 provide cross-reference information.
2044
2045 @end itemize
2046
2047 @noindent
2048 For a full detailed description of the format of the @file{ALI} file,
2049 see the source of the body of unit @code{Lib.Writ}, contained in file
2050 @file{lib-writ.adb} in the GNAT compiler sources.
2051
2052 @node Binding an Ada Program
2053 @section Binding an Ada Program
2054
2055 @noindent
2056 When using languages such as C and C++, once the source files have been
2057 compiled the only remaining step in building an executable program
2058 is linking the object modules together. This means that it is possible to
2059 link an inconsistent version of a program, in which two units have
2060 included different versions of the same header.
2061
2062 The rules of Ada do not permit such an inconsistent program to be built.
2063 For example, if two clients have different versions of the same package,
2064 it is illegal to build a program containing these two clients.
2065 These rules are enforced by the GNAT binder, which also determines an
2066 elaboration order consistent with the Ada rules.
2067
2068 The GNAT binder is run after all the object files for a program have
2069 been created. It is given the name of the main program unit, and from
2070 this it determines the set of units required by the program, by reading the
2071 corresponding ALI files. It generates error messages if the program is
2072 inconsistent or if no valid order of elaboration exists.
2073
2074 If no errors are detected, the binder produces a main program, in Ada by
2075 default, that contains calls to the elaboration procedures of those
2076 compilation unit that require them, followed by
2077 a call to the main program. This Ada program is compiled to generate the
2078 object file for the main program. The name of
2079 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2080 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2081 main program unit.
2082
2083 Finally, the linker is used to build the resulting executable program,
2084 using the object from the main program from the bind step as well as the
2085 object files for the Ada units of the program.
2086
2087 @node Mixed Language Programming
2088 @section Mixed Language Programming
2089 @cindex Mixed Language Programming
2090
2091 @noindent
2092 This section describes how to develop a mixed-language program,
2093 specifically one that comprises units in both Ada and C.
2094
2095 @menu
2096 * Interfacing to C::
2097 * Calling Conventions::
2098 @end menu
2099
2100 @node Interfacing to C
2101 @subsection Interfacing to C
2102 @noindent
2103 Interfacing Ada with a foreign language such as C involves using
2104 compiler directives to import and/or export entity definitions in each
2105 language---using @code{extern} statements in C, for instance, and the
2106 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2107 A full treatment of these topics is provided in Appendix B, section 1
2108 of the Ada Reference Manual.
2109
2110 There are two ways to build a program using GNAT that contains some Ada
2111 sources and some foreign language sources, depending on whether or not
2112 the main subprogram is written in Ada.  Here is a source example with
2113 the main subprogram in Ada:
2114
2115 @smallexample
2116 /* file1.c */
2117 #include <stdio.h>
2118
2119 void print_num (int num)
2120 @{
2121   printf ("num is %d.\n", num);
2122   return;
2123 @}
2124
2125 /* file2.c */
2126
2127 /* num_from_Ada is declared in my_main.adb */
2128 extern int num_from_Ada;
2129
2130 int get_num (void)
2131 @{
2132   return num_from_Ada;
2133 @}
2134 @end smallexample
2135
2136 @smallexample @c ada
2137 --  my_main.adb
2138 procedure My_Main is
2139
2140    --  Declare then export an Integer entity called num_from_Ada
2141    My_Num : Integer := 10;
2142    pragma Export (C, My_Num, "num_from_Ada");
2143
2144    --  Declare an Ada function spec for Get_Num, then use
2145    --  C function get_num for the implementation.
2146    function Get_Num return Integer;
2147    pragma Import (C, Get_Num, "get_num");
2148
2149    --  Declare an Ada procedure spec for Print_Num, then use
2150    --  C function print_num for the implementation.
2151    procedure Print_Num (Num : Integer);
2152    pragma Import (C, Print_Num, "print_num");
2153
2154 begin
2155    Print_Num (Get_Num);
2156 end My_Main;
2157 @end smallexample
2158
2159 @enumerate
2160 @item
2161 To build this example, first compile the foreign language files to
2162 generate object files:
2163 @smallexample
2164 ^gcc -c file1.c^gcc -c FILE1.C^
2165 ^gcc -c file2.c^gcc -c FILE2.C^
2166 @end smallexample
2167
2168 @item
2169 Then, compile the Ada units to produce a set of object files and ALI
2170 files:
2171 @smallexample
2172 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2173 @end smallexample
2174
2175 @item
2176 Run the Ada binder on the Ada main program:
2177 @smallexample
2178 gnatbind my_main.ali
2179 @end smallexample
2180
2181 @item
2182 Link the Ada main program, the Ada objects and the other language
2183 objects:
2184 @smallexample
2185 gnatlink my_main.ali file1.o file2.o
2186 @end smallexample
2187 @end enumerate
2188
2189 The last three steps can be grouped in a single command:
2190 @smallexample
2191 gnatmake my_main.adb -largs file1.o file2.o
2192 @end smallexample
2193
2194 @cindex Binder output file
2195 @noindent
2196 If the main program is in a language other than Ada, then you may have
2197 more than one entry point into the Ada subsystem. You must use a special
2198 binder option to generate callable routines that initialize and
2199 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2200 Calls to the initialization and finalization routines must be inserted
2201 in the main program, or some other appropriate point in the code. The
2202 call to initialize the Ada units must occur before the first Ada
2203 subprogram is called, and the call to finalize the Ada units must occur
2204 after the last Ada subprogram returns. The binder will place the
2205 initialization and finalization subprograms into the
2206 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2207 sources.  To illustrate, we have the following example:
2208
2209 @smallexample
2210 /* main.c */
2211 extern void adainit (void);
2212 extern void adafinal (void);
2213 extern int add (int, int);
2214 extern int sub (int, int);
2215
2216 int main (int argc, char *argv[])
2217 @{
2218   int a = 21, b = 7;
2219
2220   adainit();
2221
2222   /* Should print "21 + 7 = 28" */
2223   printf ("%d + %d = %d\n", a, b, add (a, b));
2224   /* Should print "21 - 7 = 14" */
2225   printf ("%d - %d = %d\n", a, b, sub (a, b));
2226
2227   adafinal();
2228 @}
2229 @end smallexample
2230
2231 @smallexample @c ada
2232 --  unit1.ads
2233 package Unit1 is
2234    function Add (A, B : Integer) return Integer;
2235    pragma Export (C, Add, "add");
2236 end Unit1;
2237
2238 --  unit1.adb
2239 package body Unit1 is
2240    function Add (A, B : Integer) return Integer is
2241    begin
2242       return A + B;
2243    end Add;
2244 end Unit1;
2245
2246 --  unit2.ads
2247 package Unit2 is
2248    function Sub (A, B : Integer) return Integer;
2249    pragma Export (C, Sub, "sub");
2250 end Unit2;
2251
2252 --  unit2.adb
2253 package body Unit2 is
2254    function Sub (A, B : Integer) return Integer is
2255    begin
2256       return A - B;
2257    end Sub;
2258 end Unit2;
2259 @end smallexample
2260
2261 @enumerate
2262 @item
2263 The build procedure for this application is similar to the last
2264 example's.  First, compile the foreign language files to generate object
2265 files:
2266 @smallexample
2267 ^gcc -c main.c^gcc -c main.c^
2268 @end smallexample
2269
2270 @item
2271 Next, compile the Ada units to produce a set of object files and ALI
2272 files:
2273 @smallexample
2274 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2275 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2276 @end smallexample
2277
2278 @item
2279 Run the Ada binder on every generated ALI file.  Make sure to use the
2280 @option{-n} option to specify a foreign main program:
2281 @smallexample
2282 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2283 @end smallexample
2284
2285 @item
2286 Link the Ada main program, the Ada objects and the foreign language
2287 objects. You need only list the last ALI file here:
2288 @smallexample
2289 gnatlink unit2.ali main.o -o exec_file
2290 @end smallexample
2291
2292 This procedure yields a binary executable called @file{exec_file}.
2293 @end enumerate
2294
2295 @noindent
2296 Depending on the circumstances (for example when your non-Ada main object
2297 does not provide symbol @code{main}), you may also need to instruct the
2298 GNAT linker not to include the standard startup objects by passing the
2299 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2300
2301 @node Calling Conventions
2302 @subsection Calling Conventions
2303 @cindex Foreign Languages
2304 @cindex Calling Conventions
2305 GNAT follows standard calling sequence conventions and will thus interface
2306 to any other language that also follows these conventions. The following
2307 Convention identifiers are recognized by GNAT:
2308
2309 @table @code
2310 @cindex Interfacing to Ada
2311 @cindex Other Ada compilers
2312 @cindex Convention Ada
2313 @item Ada
2314 This indicates that the standard Ada calling sequence will be
2315 used and all Ada data items may be passed without any limitations in the
2316 case where GNAT is used to generate both the caller and callee. It is also
2317 possible to mix GNAT generated code and code generated by another Ada
2318 compiler. In this case, the data types should be restricted to simple
2319 cases, including primitive types. Whether complex data types can be passed
2320 depends on the situation. Probably it is safe to pass simple arrays, such
2321 as arrays of integers or floats. Records may or may not work, depending
2322 on whether both compilers lay them out identically. Complex structures
2323 involving variant records, access parameters, tasks, or protected types,
2324 are unlikely to be able to be passed.
2325
2326 Note that in the case of GNAT running
2327 on a platform that supports HP Ada 83, a higher degree of compatibility
2328 can be guaranteed, and in particular records are laid out in an identical
2329 manner in the two compilers. Note also that if output from two different
2330 compilers is mixed, the program is responsible for dealing with elaboration
2331 issues. Probably the safest approach is to write the main program in the
2332 version of Ada other than GNAT, so that it takes care of its own elaboration
2333 requirements, and then call the GNAT-generated adainit procedure to ensure
2334 elaboration of the GNAT components. Consult the documentation of the other
2335 Ada compiler for further details on elaboration.
2336
2337 However, it is not possible to mix the tasking run time of GNAT and
2338 HP Ada 83, All the tasking operations must either be entirely within
2339 GNAT compiled sections of the program, or entirely within HP Ada 83
2340 compiled sections of the program.
2341
2342 @cindex Interfacing to Assembly
2343 @cindex Convention Assembler
2344 @item Assembler
2345 Specifies assembler as the convention. In practice this has the
2346 same effect as convention Ada (but is not equivalent in the sense of being
2347 considered the same convention).
2348
2349 @cindex Convention Asm
2350 @findex Asm
2351 @item Asm
2352 Equivalent to Assembler.
2353
2354 @cindex Interfacing to COBOL
2355 @cindex Convention COBOL
2356 @findex COBOL
2357 @item COBOL
2358 Data will be passed according to the conventions described
2359 in section B.4 of the Ada Reference Manual.
2360
2361 @findex C
2362 @cindex Interfacing to C
2363 @cindex Convention C
2364 @item C
2365 Data will be passed according to the conventions described
2366 in section B.3 of the Ada Reference Manual.
2367
2368 A note on interfacing to a C ``varargs'' function:
2369 @findex C varargs function
2370 @cindex Interfacing to C varargs function
2371 @cindex varargs function interfaces
2372
2373 @itemize @bullet
2374 @item
2375 In C, @code{varargs} allows a function to take a variable number of
2376 arguments. There is no direct equivalent in this to Ada. One
2377 approach that can be used is to create a C wrapper for each
2378 different profile and then interface to this C wrapper. For
2379 example, to print an @code{int} value using @code{printf},
2380 create a C function @code{printfi} that takes two arguments, a
2381 pointer to a string and an int, and calls @code{printf}.
2382 Then in the Ada program, use pragma @code{Import} to
2383 interface to @code{printfi}.
2384
2385 @item
2386 It may work on some platforms to directly interface to
2387 a @code{varargs} function by providing a specific Ada profile
2388 for a particular call. However, this does not work on
2389 all platforms, since there is no guarantee that the
2390 calling sequence for a two argument normal C function
2391 is the same as for calling a @code{varargs} C function with
2392 the same two arguments.
2393 @end itemize
2394
2395 @cindex Convention Default
2396 @findex Default
2397 @item Default
2398 Equivalent to C.
2399
2400 @cindex Convention External
2401 @findex External
2402 @item External
2403 Equivalent to C.
2404
2405 @ifclear vms
2406 @findex C++
2407 @cindex Interfacing to C++
2408 @cindex Convention C++
2409 @item C_Plus_Plus (or CPP)
2410 This stands for C++. For most purposes this is identical to C.
2411 See the separate description of the specialized GNAT pragmas relating to
2412 C++ interfacing for further details.
2413 @end ifclear
2414
2415 @findex Fortran
2416 @cindex Interfacing to Fortran
2417 @cindex Convention Fortran
2418 @item Fortran
2419 Data will be passed according to the conventions described
2420 in section B.5 of the Ada Reference Manual.
2421
2422 @item Intrinsic
2423 This applies to an intrinsic operation, as defined in the Ada
2424 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2425 this means that the body of the subprogram is provided by the compiler itself,
2426 usually by means of an efficient code sequence, and that the user does not
2427 supply an explicit body for it. In an application program, the pragma may
2428 be applied to the following sets of names:
2429
2430 @itemize @bullet
2431 @item
2432 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2433 Shift_Right_Arithmetic.  The corresponding subprogram declaration must have
2434 two formal parameters. The
2435 first one must be a signed integer type or a modular type with a binary
2436 modulus, and the second parameter must be of type Natural.
2437 The return type must be the same as the type of the first argument. The size
2438 of this type can only be 8, 16, 32, or 64.
2439
2440 @item
2441 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2442 The corresponding operator declaration must have parameters and result type
2443 that have the same root numeric type (for example, all three are long_float
2444 types). This simplifies the definition of operations that use type checking
2445 to perform dimensional checks:
2446
2447 @smallexample @c ada
2448 type Distance is new Long_Float;
2449 type Time     is new Long_Float;
2450 type Velocity is new Long_Float;
2451 function "/" (D : Distance; T : Time)
2452   return Velocity;
2453 pragma Import (Intrinsic, "/");
2454 @end smallexample
2455
2456 @noindent
2457 This common idiom is often programmed with a generic definition and an
2458 explicit body. The pragma makes it simpler to introduce such declarations.
2459 It incurs no overhead in compilation time or code size, because it is
2460 implemented as a single machine instruction.
2461
2462 @item
2463 General subprogram entities, to bind an Ada subprogram declaration to
2464 a compiler builtin by name with back-ends where such interfaces are
2465 available. A typical example is the set of ``__builtin'' functions
2466 exposed by the GCC back-end, as in the following example:
2467
2468 @smallexample @c ada
2469    function builtin_sqrt (F : Float) return Float;
2470    pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2471 @end smallexample
2472
2473 Most of the GCC builtins are accessible this way, and as for other
2474 import conventions (e.g. C), it is the user's responsibility to ensure
2475 that the Ada subprogram profile matches the underlying builtin
2476 expectations.
2477 @end itemize
2478
2479 @noindent
2480
2481 @ifset unw
2482 @findex Stdcall
2483 @cindex Convention Stdcall
2484 @item Stdcall
2485 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2486 and specifies that the @code{Stdcall} calling sequence will be used,
2487 as defined by the NT API. Nevertheless, to ease building
2488 cross-platform bindings this convention will be handled as a @code{C} calling
2489 convention on non-Windows platforms.
2490
2491 @findex DLL
2492 @cindex Convention DLL
2493 @item DLL
2494 This is equivalent to @code{Stdcall}.
2495
2496 @findex Win32
2497 @cindex Convention Win32
2498 @item Win32
2499 This is equivalent to @code{Stdcall}.
2500 @end ifset
2501
2502 @findex Stubbed
2503 @cindex Convention Stubbed
2504 @item Stubbed
2505 This is a special convention that indicates that the compiler
2506 should provide a stub body that raises @code{Program_Error}.
2507 @end table
2508
2509 @noindent
2510 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2511 that can be used to parameterize conventions and allow additional synonyms
2512 to be specified. For example if you have legacy code in which the convention
2513 identifier Fortran77 was used for Fortran, you can use the configuration
2514 pragma:
2515
2516 @smallexample @c ada
2517 pragma Convention_Identifier (Fortran77, Fortran);
2518 @end smallexample
2519
2520 @noindent
2521 And from now on the identifier Fortran77 may be used as a convention
2522 identifier (for example in an @code{Import} pragma) with the same
2523 meaning as Fortran.
2524
2525 @ifclear vms
2526 @node Building Mixed Ada & C++ Programs
2527 @section Building Mixed Ada and C++ Programs
2528
2529 @noindent
2530 A programmer inexperienced with mixed-language development may find that
2531 building an application containing both Ada and C++ code can be a
2532 challenge.  This section gives a few
2533 hints that should make this task easier. The first section addresses
2534 the differences between interfacing with C and interfacing with C++.
2535 The second section
2536 looks into the delicate problem of linking the complete application from
2537 its Ada and C++ parts. The last section gives some hints on how the GNAT
2538 run-time library can be adapted in order to allow inter-language dispatching
2539 with a new C++ compiler.
2540
2541 @menu
2542 * Interfacing to C++::
2543 * Linking a Mixed C++ & Ada Program::
2544 * A Simple Example::
2545 * Interfacing with C++ constructors::
2546 * Interfacing with C++ at the Class Level::
2547 @end menu
2548
2549 @node Interfacing to C++
2550 @subsection Interfacing to C++
2551
2552 @noindent
2553 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2554 generating code that is compatible with the G++ Application Binary
2555 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2556
2557 @noindent
2558 Interfacing can be done at 3 levels: simple data, subprograms, and
2559 classes. In the first two cases, GNAT offers a specific @code{Convention
2560 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2561 Usually, C++ mangles the names of subprograms. To generate proper mangled
2562 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2563 This problem can also be addressed manually in two ways:
2564
2565 @itemize @bullet
2566 @item
2567 by modifying the C++ code in order to force a C convention using
2568 the @code{extern "C"} syntax.
2569
2570 @item
2571 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2572 Link_Name argument of the pragma import.
2573 @end itemize
2574
2575 @noindent
2576 Interfacing at the class level can be achieved by using the GNAT specific
2577 pragmas such as @code{CPP_Constructor}.  @xref{Interfacing to C++,,,
2578 gnat_rm, GNAT Reference Manual}, for additional information.
2579
2580 @node Linking a Mixed C++ & Ada Program
2581 @subsection Linking a Mixed C++ & Ada Program
2582
2583 @noindent
2584 Usually the linker of the C++ development system must be used to link
2585 mixed applications because most C++ systems will resolve elaboration
2586 issues (such as calling constructors on global class instances)
2587 transparently during the link phase. GNAT has been adapted to ease the
2588 use of a foreign linker for the last phase. Three cases can be
2589 considered:
2590 @enumerate
2591
2592 @item
2593 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
2594 The C++ linker can simply be called by using the C++ specific driver
2595 called @code{g++}.
2596
2597 Note that if the C++ code uses inline functions, you will need to
2598 compile your C++ code with the @code{-fkeep-inline-functions} switch in
2599 order to provide an existing function implementation that the Ada code can
2600 link with.
2601
2602 @smallexample
2603 $ g++ -c -fkeep-inline-functions file1.C
2604 $ g++ -c -fkeep-inline-functions file2.C
2605 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
2606 @end smallexample
2607
2608 @item
2609 Using GNAT and G++ from two different GCC installations: If both
2610 compilers are on the @env{PATH}, the previous method may be used. It is
2611 important to note that environment variables such as
2612 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
2613 @env{GCC_ROOT} will affect both compilers
2614 at the same time and may make one of the two compilers operate
2615 improperly if set during invocation of the wrong compiler.  It is also
2616 very important that the linker uses the proper @file{libgcc.a} GCC
2617 library -- that is, the one from the C++ compiler installation. The
2618 implicit link command as suggested in the @command{gnatmake} command
2619 from the former example can be replaced by an explicit link command with
2620 the full-verbosity option in order to verify which library is used:
2621 @smallexample
2622 $ gnatbind ada_unit
2623 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2624 @end smallexample
2625 If there is a problem due to interfering environment variables, it can
2626 be worked around by using an intermediate script. The following example
2627 shows the proper script to use when GNAT has not been installed at its
2628 default location and g++ has been installed at its default location:
2629
2630 @smallexample
2631 $ cat ./my_script
2632 #!/bin/sh
2633 unset BINUTILS_ROOT
2634 unset GCC_ROOT
2635 c++ $*
2636 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2637 @end smallexample
2638
2639 @item
2640 Using a non-GNU C++ compiler: The commands previously described can be
2641 used to insure that the C++ linker is used. Nonetheless, you need to add
2642 a few more parameters to the link command line, depending on the exception
2643 mechanism used.
2644
2645 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
2646 to the libgcc libraries are required:
2647
2648 @smallexample
2649 $ cat ./my_script
2650 #!/bin/sh
2651 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
2652 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2653 @end smallexample
2654
2655 Where CC is the name of the non-GNU C++ compiler.
2656
2657 If the @code{zero cost} exception mechanism is used, and the platform
2658 supports automatic registration of exception tables (e.g.@: Solaris),
2659 paths to more objects are required:
2660
2661 @smallexample
2662 $ cat ./my_script
2663 #!/bin/sh
2664 CC `gcc -print-file-name=crtbegin.o` $* \
2665 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
2666 `gcc -print-file-name=crtend.o`
2667 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2668 @end smallexample
2669
2670 If the @code{zero cost} exception mechanism is used, and the platform
2671 doesn't support automatic registration of exception tables (e.g.@: HP-UX
2672 or AIX), the simple approach described above will not work and
2673 a pre-linking phase using GNAT will be necessary.
2674
2675 @end enumerate
2676
2677 Another alternative is to use the @command{gprbuild} multi-language builder
2678 which has a large knowledge base and knows how to link Ada and C++ code
2679 together automatically in most cases.
2680
2681 @node A Simple Example
2682 @subsection  A Simple Example
2683 @noindent
2684 The following example, provided as part of the GNAT examples, shows how
2685 to achieve procedural interfacing between Ada and C++ in both
2686 directions. The C++ class A has two methods. The first method is exported
2687 to Ada by the means of an extern C wrapper function. The second method
2688 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
2689 a limited record with a layout comparable to the C++ class. The Ada
2690 subprogram, in turn, calls the C++ method. So, starting from the C++
2691 main program, the process passes back and forth between the two
2692 languages.
2693
2694 @noindent
2695 Here are the compilation commands:
2696 @smallexample
2697 $ gnatmake -c simple_cpp_interface
2698 $ g++ -c cpp_main.C
2699 $ g++ -c ex7.C
2700 $ gnatbind -n simple_cpp_interface
2701 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
2702       -lstdc++ ex7.o cpp_main.o
2703 @end smallexample
2704
2705 @noindent
2706 Here are the corresponding sources:
2707 @smallexample
2708
2709 //cpp_main.C
2710
2711 #include "ex7.h"
2712
2713 extern "C" @{
2714   void adainit (void);
2715   void adafinal (void);
2716   void method1 (A *t);
2717 @}
2718
2719 void method1 (A *t)
2720 @{
2721   t->method1 ();
2722 @}
2723
2724 int main ()
2725 @{
2726   A obj;
2727   adainit ();
2728   obj.method2 (3030);
2729   adafinal ();
2730 @}
2731
2732 //ex7.h
2733
2734 class Origin @{
2735  public:
2736   int o_value;
2737 @};
2738 class A : public Origin @{
2739  public:
2740   void method1 (void);
2741   void method2 (int v);
2742   A();
2743   int   a_value;
2744 @};
2745
2746 //ex7.C
2747
2748 #include "ex7.h"
2749 #include <stdio.h>
2750
2751 extern "C" @{ void ada_method2 (A *t, int v);@}
2752
2753 void A::method1 (void)
2754 @{
2755   a_value = 2020;
2756   printf ("in A::method1, a_value = %d \n",a_value);
2757
2758 @}
2759
2760 void A::method2 (int v)
2761 @{
2762    ada_method2 (this, v);
2763    printf ("in A::method2, a_value = %d \n",a_value);
2764
2765 @}
2766
2767 A::A(void)
2768 @{
2769    a_value = 1010;
2770   printf ("in A::A, a_value = %d \n",a_value);
2771 @}
2772 @end smallexample
2773
2774 @smallexample @c ada
2775 -- Ada sources
2776 package body Simple_Cpp_Interface is
2777
2778    procedure Ada_Method2 (This : in out A; V : Integer) is
2779    begin
2780       Method1 (This);
2781       This.A_Value := V;
2782    end Ada_Method2;
2783
2784 end Simple_Cpp_Interface;
2785
2786 with System;
2787 package Simple_Cpp_Interface is
2788    type A is limited
2789       record
2790          Vptr    : System.Address;
2791          O_Value : Integer;
2792          A_Value : Integer;
2793       end record;
2794    pragma Convention (C, A);
2795
2796    procedure Method1 (This : in out A);
2797    pragma Import (C, Method1);
2798
2799    procedure Ada_Method2 (This : in out A; V : Integer);
2800    pragma Export (C, Ada_Method2);
2801
2802 end Simple_Cpp_Interface;
2803 @end smallexample
2804
2805 @node Interfacing with C++ constructors
2806 @subsection Interfacing with C++ constructors
2807 @noindent
2808
2809 In order to interface with C++ constructors GNAT provides the
2810 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
2811 gnat_rm, GNAT Reference Manual}, for additional information).
2812 In this section we present some common uses of C++ constructors
2813 in mixed-languages programs in GNAT.
2814
2815 Let us assume that we need to interface with the following
2816 C++ class:
2817
2818 @smallexample
2819 @b{class} Root @{
2820 @b{public}:
2821   int  a_value;
2822   int  b_value;
2823   @b{virtual} int Get_Value ();
2824   Root();              // Default constructor
2825   Root(int v);         // 1st non-default constructor
2826   Root(int v, int w);  // 2nd non-default constructor
2827 @};
2828 @end smallexample
2829
2830 For this purpose we can write the following package spec (further
2831 information on how to build this spec is available in
2832 @ref{Interfacing with C++ at the Class Level} and
2833 @ref{Generating Ada Bindings for C and C++ headers}).
2834
2835 @smallexample @c ada
2836 with Interfaces.C; use Interfaces.C;
2837 package Pkg_Root is
2838   type Root is tagged limited record
2839      A_Value : int;
2840      B_Value : int;
2841   end record;
2842   pragma Import (CPP, Root);
2843
2844   function Get_Value (Obj : Root) return int;
2845   pragma Import (CPP, Get_Value);
2846
2847   function Constructor return Root;
2848   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
2849
2850   function Constructor (v : Integer) return Root;
2851   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
2852
2853   function Constructor (v, w : Integer) return Root;
2854   pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
2855 end Pkg_Root;
2856 @end smallexample
2857
2858 On the Ada side the constructor is represented by a function (whose
2859 name is arbitrary) that returns the classwide type corresponding to
2860 the imported C++ class. Although the constructor is described as a
2861 function, it is typically a procedure with an extra implicit argument
2862 (the object being initialized) at the implementation level. GNAT
2863 issues the appropriate call, whatever it is, to get the object
2864 properly initialized.
2865
2866 Constructors can only appear in the following contexts:
2867
2868 @itemize @bullet
2869 @item
2870 On the right side of an initialization of an object of type @var{T}.
2871 @item
2872 On the right side of an initialization of a record component of type @var{T}.
2873 @item
2874 In an Ada 2005 limited aggregate.
2875 @item
2876 In an Ada 2005 nested limited aggregate.
2877 @item
2878 In an Ada 2005 limited aggregate that initializes an object built in
2879 place by an extended return statement.
2880 @end itemize
2881
2882 @noindent
2883 In a declaration of an object whose type is a class imported from C++,
2884 either the default C++ constructor is implicitly called by GNAT, or
2885 else the required C++ constructor must be explicitly called in the
2886 expression that initializes the object. For example:
2887
2888 @smallexample @c ada
2889   Obj1 : Root;
2890   Obj2 : Root := Constructor;
2891   Obj3 : Root := Constructor (v => 10);
2892   Obj4 : Root := Constructor (30, 40);
2893 @end smallexample
2894
2895 The first two declarations are equivalent: in both cases the default C++
2896 constructor is invoked (in the former case the call to the constructor is
2897 implicit, and in the latter case the call is explicit in the object
2898 declaration). @code{Obj3} is initialized by the C++ non-default constructor
2899 that takes an integer argument, and @code{Obj4} is initialized by the
2900 non-default C++ constructor that takes two integers.
2901
2902 Let us derive the imported C++ class in the Ada side. For example:
2903
2904 @smallexample @c ada
2905   type DT is new Root with record
2906      C_Value : Natural := 2009;
2907   end record;
2908 @end smallexample
2909
2910 In this case the components DT inherited from the C++ side must be
2911 initialized by a C++ constructor, and the additional Ada components
2912 of type DT are initialized by GNAT. The initialization of such an
2913 object is done either by default, or by means of a function returning
2914 an aggregate of type DT, or by means of an extension aggregate.
2915
2916 @smallexample @c ada
2917   Obj5 : DT;
2918   Obj6 : DT := Function_Returning_DT (50);
2919   Obj7 : DT := (Constructor (30,40) with C_Value => 50);
2920 @end smallexample
2921
2922 The declaration of @code{Obj5} invokes the default constructors: the
2923 C++ default constructor of the parent type takes care of the initialization
2924 of the components inherited from Root, and GNAT takes care of the default
2925 initialization of the additional Ada components of type DT (that is,
2926 @code{C_Value} is initialized to value 2009). The order of invocation of
2927 the constructors is consistent with the order of elaboration required by
2928 Ada and C++. That is, the constructor of the parent type is always called
2929 before the constructor of the derived type.
2930
2931 Let us now consider a record that has components whose type is imported
2932 from C++. For example:
2933
2934 @smallexample @c ada
2935   type Rec1 is limited record
2936      Data1 : Root := Constructor (10);
2937      Value : Natural := 1000;
2938   end record;
2939
2940   type Rec2 (D : Integer := 20) is limited record
2941      Rec   : Rec1;
2942      Data2 : Root := Constructor (D, 30);
2943   end record;
2944 @end smallexample
2945
2946 The initialization of an object of type @code{Rec2} will call the
2947 non-default C++ constructors specified for the imported components.
2948 For example:
2949
2950 @smallexample @c ada
2951   Obj8 : Rec2 (40);
2952 @end smallexample
2953
2954 Using Ada 2005 we can use limited aggregates to initialize an object
2955 invoking C++ constructors that differ from those specified in the type
2956 declarations. For example:
2957
2958 @smallexample @c ada
2959   Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
2960                           others => <>),
2961                   others => <>);
2962 @end smallexample
2963
2964 The above declaration uses an Ada 2005 limited aggregate to
2965 initialize @code{Obj9}, and the C++ constructor that has two integer
2966 arguments is invoked to initialize the @code{Data1} component instead
2967 of the constructor specified in the declaration of type @code{Rec1}. In
2968 Ada 2005 the box in the aggregate indicates that unspecified components
2969 are initialized using the expression (if any) available in the component
2970 declaration. That is, in this case discriminant @code{D} is initialized
2971 to value @code{20}, @code{Value} is initialized to value 1000, and the
2972 non-default C++ constructor that handles two integers takes care of
2973 initializing component @code{Data2} with values @code{20,30}.
2974
2975 In Ada 2005 we can use the extended return statement to build the Ada
2976 equivalent to C++ non-default constructors. For example:
2977
2978 @smallexample @c ada
2979   function Constructor (V : Integer) return Rec2 is
2980   begin
2981      return Obj : Rec2 := (Rec => (Data1  => Constructor (V, 20),
2982                                    others => <>),
2983                            others => <>) do
2984         --  Further actions required for construction of
2985         --  objects of type Rec2
2986         ...
2987      end record;
2988   end Constructor;
2989 @end smallexample
2990
2991 In this example the extended return statement construct is used to
2992 build in place the returned object whose components are initialized
2993 by means of a limited aggregate. Any further action associated with
2994 the constructor can be placed inside the construct.
2995
2996 @node Interfacing with C++ at the Class Level
2997 @subsection Interfacing with C++ at the Class Level
2998 @noindent
2999 In this section we demonstrate the GNAT features for interfacing with
3000 C++ by means of an example making use of Ada 2005 abstract interface
3001 types. This example consists of a classification of animals; classes
3002 have been used to model our main classification of animals, and
3003 interfaces provide support for the management of secondary
3004 classifications. We first demonstrate a case in which the types and
3005 constructors are defined on the C++ side and imported from the Ada
3006 side, and latter the reverse case.
3007
3008 The root of our derivation will be the @code{Animal} class, with a
3009 single private attribute (the @code{Age} of the animal) and two public
3010 primitives to set and get the value of this attribute.
3011
3012 @smallexample
3013 @b{class} Animal @{
3014  @b{public}:
3015    @b{virtual} void Set_Age (int New_Age);
3016    @b{virtual} int Age ();
3017  @b{private}:
3018    int Age_Count;
3019 @};
3020 @end smallexample
3021
3022 Abstract interface types are defined in C++ by means of classes with pure
3023 virtual functions and no data members. In our example we will use two
3024 interfaces that provide support for the common management of @code{Carnivore}
3025 and @code{Domestic} animals:
3026
3027 @smallexample
3028 @b{class} Carnivore @{
3029 @b{public}:
3030    @b{virtual} int Number_Of_Teeth () = 0;
3031 @};
3032
3033 @b{class} Domestic @{
3034 @b{public}:
3035    @b{virtual void} Set_Owner (char* Name) = 0;
3036 @};
3037 @end smallexample
3038
3039 Using these declarations, we can now say that a @code{Dog} is an animal that is
3040 both Carnivore and Domestic, that is:
3041
3042 @smallexample
3043 @b{class} Dog : Animal, Carnivore, Domestic @{
3044  @b{public}:
3045    @b{virtual} int  Number_Of_Teeth ();
3046    @b{virtual} void Set_Owner (char* Name);
3047
3048    Dog(); // Constructor
3049  @b{private}:
3050    int  Tooth_Count;
3051    char *Owner;
3052 @};
3053 @end smallexample
3054
3055 In the following examples we will assume that the previous declarations are
3056 located in a file named @code{animals.h}. The following package demonstrates
3057 how to import these C++ declarations from the Ada side:
3058
3059 @smallexample @c ada
3060 with Interfaces.C.Strings; use Interfaces.C.Strings;
3061 package Animals is
3062   type Carnivore is interface;
3063   pragma Convention (C_Plus_Plus, Carnivore);
3064   function Number_Of_Teeth (X : Carnivore)
3065      return Natural is abstract;
3066
3067   type Domestic is interface;
3068   pragma Convention (C_Plus_Plus, Set_Owner);
3069   procedure Set_Owner
3070     (X    : in out Domestic;
3071      Name : Chars_Ptr) is abstract;
3072
3073   type Animal is tagged record
3074     Age : Natural := 0;
3075   end record;
3076   pragma Import (C_Plus_Plus, Animal);
3077
3078   procedure Set_Age (X : in out Animal; Age : Integer);
3079   pragma Import (C_Plus_Plus, Set_Age);
3080
3081   function Age (X : Animal) return Integer;
3082   pragma Import (C_Plus_Plus, Age);
3083
3084   type Dog is new Animal and Carnivore and Domestic with record
3085     Tooth_Count : Natural;
3086     Owner       : String (1 .. 30);
3087   end record;
3088   pragma Import (C_Plus_Plus, Dog);
3089
3090   function Number_Of_Teeth (A : Dog) return Integer;
3091   pragma Import (C_Plus_Plus, Number_Of_Teeth);
3092
3093   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3094   pragma Import (C_Plus_Plus, Set_Owner);
3095
3096   function New_Dog return Dog;
3097   pragma CPP_Constructor (New_Dog);
3098   pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3099 end Animals;
3100 @end smallexample
3101
3102 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3103 interfacing with these C++ classes is easy. The only requirement is that all
3104 the primitives and components must be declared exactly in the same order in
3105 the two languages.
3106
3107 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3108 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3109 the arguments to the called primitives will be the same as for C++. For the
3110 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3111 to indicate that they have been defined on the C++ side; this is required
3112 because the dispatch table associated with these tagged types will be built
3113 in the C++ side and therefore will not contain the predefined Ada primitives
3114 which Ada would otherwise expect.
3115
3116 As the reader can see there is no need to indicate the C++ mangled names
3117 associated with each subprogram because it is assumed that all the calls to
3118 these primitives will be dispatching calls. The only exception is the
3119 constructor, which must be registered with the compiler by means of
3120 @code{pragma CPP_Constructor} and needs to provide its associated C++
3121 mangled name because the Ada compiler generates direct calls to it.
3122
3123 With the above packages we can now declare objects of type Dog on the Ada side
3124 and dispatch calls to the corresponding subprograms on the C++ side. We can
3125 also extend the tagged type Dog with further fields and primitives, and
3126 override some of its C++ primitives on the Ada side. For example, here we have
3127 a type derivation defined on the Ada side that inherits all the dispatching
3128 primitives of the ancestor from the C++ side.
3129
3130 @smallexample
3131 @b{with} Animals; @b{use} Animals;
3132 @b{package} Vaccinated_Animals @b{is}
3133   @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3134   @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3135 @b{end} Vaccinated_Animals;
3136 @end smallexample
3137
3138 It is important to note that, because of the ABI compatibility, the programmer
3139 does not need to add any further information to indicate either the object
3140 layout or the dispatch table entry associated with each dispatching operation.
3141
3142 Now let us define all the types and constructors on the Ada side and export
3143 them to C++, using the same hierarchy of our previous example:
3144
3145 @smallexample @c ada
3146 with Interfaces.C.Strings;
3147 use Interfaces.C.Strings;
3148 package Animals is
3149   type Carnivore is interface;
3150   pragma Convention (C_Plus_Plus, Carnivore);
3151   function Number_Of_Teeth (X : Carnivore)
3152      return Natural is abstract;
3153
3154   type Domestic is interface;
3155   pragma Convention (C_Plus_Plus, Set_Owner);
3156   procedure Set_Owner
3157     (X    : in out Domestic;
3158      Name : Chars_Ptr) is abstract;
3159
3160   type Animal is tagged record
3161     Age : Natural := 0;
3162   end record;
3163   pragma Convention (C_Plus_Plus, Animal);
3164
3165   procedure Set_Age (X : in out Animal; Age : Integer);
3166   pragma Export (C_Plus_Plus, Set_Age);
3167
3168   function Age (X : Animal) return Integer;
3169   pragma Export (C_Plus_Plus, Age);
3170
3171   type Dog is new Animal and Carnivore and Domestic with record
3172     Tooth_Count : Natural;
3173     Owner       : String (1 .. 30);
3174   end record;
3175   pragma Convention (C_Plus_Plus, Dog);
3176
3177   function Number_Of_Teeth (A : Dog) return Integer;
3178   pragma Export (C_Plus_Plus, Number_Of_Teeth);
3179
3180   procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3181   pragma Export (C_Plus_Plus, Set_Owner);
3182
3183   function New_Dog return Dog'Class;
3184   pragma Export (C_Plus_Plus, New_Dog);
3185 end Animals;
3186 @end smallexample
3187
3188 Compared with our previous example the only difference is the use of
3189 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3190 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3191 nothing else to be done; as explained above, the only requirement is that all
3192 the primitives and components are declared in exactly the same order.
3193
3194 For completeness, let us see a brief C++ main program that uses the
3195 declarations available in @code{animals.h} (presented in our first example) to
3196 import and use the declarations from the Ada side, properly initializing and
3197 finalizing the Ada run-time system along the way:
3198
3199 @smallexample
3200 @b{#include} "animals.h"
3201 @b{#include} <iostream>
3202 @b{using namespace} std;
3203
3204 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3205 void Check_Domestic (Domestic *obj)   @{@dots{}@}
3206 void Check_Animal (Animal *obj)       @{@dots{}@}
3207 void Check_Dog (Dog *obj)             @{@dots{}@}
3208
3209 @b{extern} "C" @{
3210   void adainit (void);
3211   void adafinal (void);
3212   Dog* new_dog ();
3213 @}
3214
3215 void test ()
3216 @{
3217   Dog *obj = new_dog();  // Ada constructor
3218   Check_Carnivore (obj); // Check secondary DT
3219   Check_Domestic (obj);  // Check secondary DT
3220   Check_Animal (obj);    // Check primary DT
3221   Check_Dog (obj);       // Check primary DT
3222 @}
3223
3224 int main ()
3225 @{
3226   adainit ();  test();  adafinal ();
3227   return 0;
3228 @}
3229 @end smallexample
3230
3231 @node Comparison between GNAT and C/C++ Compilation Models
3232 @section Comparison between GNAT and C/C++ Compilation Models
3233
3234 @noindent
3235 The GNAT model of compilation is close to the C and C++ models. You can
3236 think of Ada specs as corresponding to header files in C. As in C, you
3237 don't need to compile specs; they are compiled when they are used. The
3238 Ada @code{with} is similar in effect to the @code{#include} of a C
3239 header.
3240
3241 One notable difference is that, in Ada, you may compile specs separately
3242 to check them for semantic and syntactic accuracy. This is not always
3243 possible with C headers because they are fragments of programs that have
3244 less specific syntactic or semantic rules.
3245
3246 The other major difference is the requirement for running the binder,
3247 which performs two important functions. First, it checks for
3248 consistency. In C or C++, the only defense against assembling
3249 inconsistent programs lies outside the compiler, in a makefile, for
3250 example. The binder satisfies the Ada requirement that it be impossible
3251 to construct an inconsistent program when the compiler is used in normal
3252 mode.
3253
3254 @cindex Elaboration order control
3255 The other important function of the binder is to deal with elaboration
3256 issues. There are also elaboration issues in C++ that are handled
3257 automatically. This automatic handling has the advantage of being
3258 simpler to use, but the C++ programmer has no control over elaboration.
3259 Where @code{gnatbind} might complain there was no valid order of
3260 elaboration, a C++ compiler would simply construct a program that
3261 malfunctioned at run time.
3262 @end ifclear
3263
3264 @node Comparison between GNAT and Conventional Ada Library Models
3265 @section Comparison between GNAT and Conventional Ada Library Models
3266
3267 @noindent
3268 This section is intended for Ada programmers who have
3269 used an Ada compiler implementing the traditional Ada library
3270 model, as described in the Ada Reference Manual.
3271
3272 @cindex GNAT library
3273 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3274 source files themselves acts as the library. Compiling Ada programs does
3275 not generate any centralized information, but rather an object file and
3276 a ALI file, which are of interest only to the binder and linker.
3277 In a traditional system, the compiler reads information not only from
3278 the source file being compiled, but also from the centralized library.
3279 This means that the effect of a compilation depends on what has been
3280 previously compiled. In particular:
3281
3282 @itemize @bullet
3283 @item
3284 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3285 to the version of the unit most recently compiled into the library.
3286
3287 @item
3288 Inlining is effective only if the necessary body has already been
3289 compiled into the library.
3290
3291 @item
3292 Compiling a unit may obsolete other units in the library.
3293 @end itemize
3294
3295 @noindent
3296 In GNAT, compiling one unit never affects the compilation of any other
3297 units because the compiler reads only source files. Only changes to source
3298 files can affect the results of a compilation. In particular:
3299
3300 @itemize @bullet
3301 @item
3302 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3303 to the source version of the unit that is currently accessible to the
3304 compiler.
3305
3306 @item
3307 @cindex Inlining
3308 Inlining requires the appropriate source files for the package or
3309 subprogram bodies to be available to the compiler. Inlining is always
3310 effective, independent of the order in which units are complied.
3311
3312 @item
3313 Compiling a unit never affects any other compilations. The editing of
3314 sources may cause previous compilations to be out of date if they
3315 depended on the source file being modified.
3316 @end itemize
3317
3318 @noindent
3319 The most important result of these differences is that order of compilation
3320 is never significant in GNAT. There is no situation in which one is
3321 required to do one compilation before another. What shows up as order of
3322 compilation requirements in the traditional Ada library becomes, in
3323 GNAT, simple source dependencies; in other words, there is only a set
3324 of rules saying what source files must be present when a file is
3325 compiled.
3326
3327 @ifset vms
3328 @node Placement of temporary files
3329 @section Placement of temporary files
3330 @cindex Temporary files (user control over placement)
3331
3332 @noindent
3333 GNAT creates temporary files in the directory designated by the environment
3334 variable @env{TMPDIR}.
3335 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3336 for detailed information on how environment variables are resolved.
3337 For most users the easiest way to make use of this feature is to simply
3338 define @env{TMPDIR} as a job level logical name).
3339 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3340 for compiler temporary files, then you can include something like the
3341 following command in your @file{LOGIN.COM} file:
3342
3343 @smallexample
3344 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3345 @end smallexample
3346
3347 @noindent
3348 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3349 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3350 designated by @env{TEMP}.
3351 If none of these environment variables are defined then GNAT uses the
3352 directory designated by the logical name @code{SYS$SCRATCH:}
3353 (by default the user's home directory). If all else fails
3354 GNAT uses the current directory for temporary files.
3355 @end ifset
3356
3357 @c *************************
3358 @node Compiling with gcc
3359 @chapter Compiling with @command{gcc}
3360
3361 @noindent
3362 This chapter discusses how to compile Ada programs using the @command{gcc}
3363 command. It also describes the set of switches
3364 that can be used to control the behavior of the compiler.
3365 @menu
3366 * Compiling Programs::
3367 * Switches for gcc::
3368 * Search Paths and the Run-Time Library (RTL)::
3369 * Order of Compilation Issues::
3370 * Examples::
3371 @end menu
3372
3373 @node Compiling Programs
3374 @section Compiling Programs
3375
3376 @noindent
3377 The first step in creating an executable program is to compile the units
3378 of the program using the @command{gcc} command. You must compile the
3379 following files:
3380
3381 @itemize @bullet
3382 @item
3383 the body file (@file{.adb}) for a library level subprogram or generic
3384 subprogram
3385
3386 @item
3387 the spec file (@file{.ads}) for a library level package or generic
3388 package that has no body
3389
3390 @item
3391 the body file (@file{.adb}) for a library level package
3392 or generic package that has a body
3393
3394 @end itemize
3395
3396 @noindent
3397 You need @emph{not} compile the following files
3398
3399 @itemize @bullet
3400
3401 @item
3402 the spec of a library unit which has a body
3403
3404 @item
3405 subunits
3406 @end itemize
3407
3408 @noindent
3409 because they are compiled as part of compiling related units. GNAT
3410 package specs
3411 when the corresponding body is compiled, and subunits when the parent is
3412 compiled.
3413
3414 @cindex cannot generate code
3415 If you attempt to compile any of these files, you will get one of the
3416 following error messages (where @var{fff} is the name of the file you
3417 compiled):
3418
3419 @smallexample
3420 cannot generate code for file @var{fff} (package spec)
3421 to check package spec, use -gnatc
3422
3423 cannot generate code for file @var{fff} (missing subunits)
3424 to check parent unit, use -gnatc
3425
3426 cannot generate code for file @var{fff} (subprogram spec)
3427 to check subprogram spec, use -gnatc
3428
3429 cannot generate code for file @var{fff} (subunit)
3430 to check subunit, use -gnatc
3431 @end smallexample
3432
3433 @noindent
3434 As indicated by the above error messages, if you want to submit
3435 one of these files to the compiler to check for correct semantics
3436 without generating code, then use the @option{-gnatc} switch.
3437
3438 The basic command for compiling a file containing an Ada unit is
3439
3440 @smallexample
3441 @c $ gcc -c @ovar{switches} @file{file name}
3442 @c Expanding @ovar macro inline (explanation in macro def comments)
3443 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3444 @end smallexample
3445
3446 @noindent
3447 where @var{file name} is the name of the Ada file (usually
3448 having an extension
3449 @file{.ads} for a spec or @file{.adb} for a body).
3450 @ifclear vms
3451 You specify the
3452 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3453 @end ifclear
3454 The result of a successful compilation is an object file, which has the
3455 same name as the source file but an extension of @file{.o} and an Ada
3456 Library Information (ALI) file, which also has the same name as the
3457 source file, but with @file{.ali} as the extension. GNAT creates these
3458 two output files in the current directory, but you may specify a source
3459 file in any directory using an absolute or relative path specification
3460 containing the directory information.
3461
3462 @findex gnat1
3463 @command{gcc} is actually a driver program that looks at the extensions of
3464 the file arguments and loads the appropriate compiler. For example, the
3465 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3466 These programs are in directories known to the driver program (in some
3467 configurations via environment variables you set), but need not be in
3468 your path. The @command{gcc} driver also calls the assembler and any other
3469 utilities needed to complete the generation of the required object
3470 files.
3471
3472 It is possible to supply several file names on the same @command{gcc}
3473 command. This causes @command{gcc} to call the appropriate compiler for
3474 each file. For example, the following command lists two separate
3475 files to be compiled:
3476
3477 @smallexample
3478 $ gcc -c x.adb y.adb
3479 @end smallexample
3480
3481 @noindent
3482 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3483 @file{y.adb}.
3484 The compiler generates two object files @file{x.o} and @file{y.o}
3485 and the two ALI files @file{x.ali} and @file{y.ali}.
3486 Any switches apply to all the files ^listed,^listed.^
3487
3488 @node Switches for gcc
3489 @section Switches for @command{gcc}
3490
3491 @noindent
3492 The @command{gcc} command accepts switches that control the
3493 compilation process. These switches are fully described in this section.
3494 First we briefly list all the switches, in alphabetical order, then we
3495 describe the switches in more detail in functionally grouped sections.
3496
3497 More switches exist for GCC than those documented here, especially
3498 for specific targets. However, their use is not recommended as
3499 they may change code generation in ways that are incompatible with
3500 the Ada run-time library, or can cause inconsistencies between
3501 compilation units.
3502
3503 @menu
3504 * Output and Error Message Control::
3505 * Warning Message Control::
3506 * Debugging and Assertion Control::
3507 * Validity Checking::
3508 * Style Checking::
3509 * Run-Time Checks::
3510 * Using gcc for Syntax Checking::
3511 * Using gcc for Semantic Checking::
3512 * Compiling Different Versions of Ada::
3513 * Character Set Control::
3514 * File Naming Control::
3515 * Subprogram Inlining Control::
3516 * Auxiliary Output Control::
3517 * Debugging Control::
3518 * Exception Handling Control::
3519 * Units to Sources Mapping Files::
3520 * Integrated Preprocessing::
3521 * Code Generation Control::
3522 @ifset vms
3523 * Return Codes::
3524 @end ifset
3525 @end menu
3526
3527 @table @option
3528 @c !sort!
3529 @ifclear vms
3530 @cindex @option{-b} (@command{gcc})
3531 @item -b @var{target}
3532 Compile your program to run on @var{target}, which is the name of a
3533 system configuration. You must have a GNAT cross-compiler built if
3534 @var{target} is not the same as your host system.
3535
3536 @item -B@var{dir}
3537 @cindex @option{-B} (@command{gcc})
3538 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3539 from @var{dir} instead of the default location. Only use this switch
3540 when multiple versions of the GNAT compiler are available.
3541 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3542 GNU Compiler Collection (GCC)}, for further details. You would normally
3543 use the @option{-b} or @option{-V} switch instead.
3544
3545 @item -c
3546 @cindex @option{-c} (@command{gcc})
3547 Compile. Always use this switch when compiling Ada programs.
3548
3549 Note: for some other languages when using @command{gcc}, notably in
3550 the case of C and C++, it is possible to use
3551 use @command{gcc} without a @option{-c} switch to
3552 compile and link in one step. In the case of GNAT, you
3553 cannot use this approach, because the binder must be run
3554 and @command{gcc} cannot be used to run the GNAT binder.
3555 @end ifclear
3556
3557 @item -fcallgraph-info@r{[}=su,da@r{]}
3558 @cindex @option{-fcallgraph-info} (@command{gcc})
3559 Makes the compiler output callgraph information for the program, on a
3560 per-file basis. The information is generated in the VCG format.  It can
3561 be decorated with additional, per-node and/or per-edge information, if a
3562 list of comma-separated markers is additionally specified. When the
3563 @var{su} marker is specified, the callgraph is decorated with stack usage information; it is equivalent to @option{-fstack-usage}. When the @var{da}
3564 marker is specified, the callgraph is decorated with information about
3565 dynamically allocated objects.
3566
3567 @item -fdump-scos
3568 @cindex @option{-fdump-scos} (@command{gcc})
3569 Generates SCO (Source Coverage Obligation) information in the ALI file.
3570 This information is used by advanced coverage tools. See unit @file{SCOs}
3571 in the compiler sources for details in files @file{scos.ads} and
3572 @file{scos.adb}.
3573
3574 @item -flto@r{[}=n@r{]}
3575 @cindex @option{-flto} (@command{gcc})
3576 Enables Link Time Optimization. This switch must be used in conjunction
3577 with the traditional @option{-Ox} switches and instructs the compiler to
3578 defer most optimizations until the link stage. The advantage of this
3579 approach is that the compiler can do a whole-program analysis and choose
3580 the best interprocedural optimization strategy based on a complete view
3581 of the program, instead of a fragmentary view with the usual approach.
3582 This can also speed up the compilation of huge programs and reduce the
3583 size of the final executable, compared with a per-unit compilation with
3584 full inlining across modules enabled with the @option{-gnatn2} switch.
3585 The drawback of this approach is that it may require much more memory.
3586 The switch, as well as the accompanying @option{-Ox} switches, must be
3587 specified both for the compilation and the link phases.
3588 If the @var{n} parameter is specified, the optimization and final code
3589 generation at link time are executed using @var{n} parallel jobs by
3590 means of an installed @command{make} program.
3591
3592 @item -fno-inline
3593 @cindex @option{-fno-inline} (@command{gcc})
3594 Suppresses all inlining, even if other optimization or inlining
3595 switches are set.  This includes suppression of inlining that
3596 results from the use of the pragma @code{Inline_Always}.
3597 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3598 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3599 effects if this switch is present.  Note that inlining can also
3600 be suppressed on a finer-grained basis with pragma @code{No_Inline}.
3601
3602 @item -fno-inline-functions
3603 @cindex @option{-fno-inline-functions} (@command{gcc})
3604 Suppresses automatic inlining of subprograms, which is enabled
3605 if @option{-O3} is used.
3606
3607 @item -fno-inline-small-functions
3608 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3609 Suppresses automatic inlining of small subprograms, which is enabled
3610 if @option{-O2} is used.
3611
3612 @item -fno-inline-functions-called-once
3613 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3614 Suppresses inlining of subprograms local to the unit and called once
3615 from within it, which is enabled if @option{-O1} is used.
3616
3617 @item -fno-ivopts
3618 @cindex @option{-fno-ivopts} (@command{gcc})
3619 Suppresses high-level loop induction variable optimizations, which are
3620 enabled if @option{-O1} is used. These optimizations are generally
3621 profitable but, for some specific cases of loops with numerous uses
3622 of the iteration variable that follow a common pattern, they may end
3623 up destroying the regularity that could be exploited at a lower level
3624 and thus producing inferior code.
3625
3626 @item -fno-strict-aliasing
3627 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3628 Causes the compiler to avoid assumptions regarding non-aliasing
3629 of objects of different types. See
3630 @ref{Optimization and Strict Aliasing} for details.
3631
3632 @item -fstack-check
3633 @cindex @option{-fstack-check} (@command{gcc})
3634 Activates stack checking.
3635 See @ref{Stack Overflow Checking} for details.
3636
3637 @item -fstack-usage
3638 @cindex @option{-fstack-usage} (@command{gcc})
3639 Makes the compiler output stack usage information for the program, on a
3640 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
3641
3642 @item ^-g^/DEBUG^
3643 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3644 Generate debugging information. This information is stored in the object
3645 file and copied from there to the final executable file by the linker,
3646 where it can be read by the debugger. You must use the
3647 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3648
3649 @item -gnat83
3650 @cindex @option{-gnat83} (@command{gcc})
3651 Enforce Ada 83 restrictions.
3652
3653 @item -gnat95
3654 @cindex @option{-gnat95} (@command{gcc})
3655 Enforce Ada 95 restrictions.
3656
3657 @item -gnat05
3658 @cindex @option{-gnat05} (@command{gcc})
3659 Allow full Ada 2005 features.
3660
3661 @item -gnat2005
3662 @cindex @option{-gnat2005} (@command{gcc})
3663 Allow full Ada 2005 features (same as @option{-gnat05})
3664
3665 @item -gnat12
3666 @cindex @option{-gnat12} (@command{gcc})
3667
3668 @item -gnat2012
3669 @cindex @option{-gnat2012} (@command{gcc})
3670 Allow full Ada 2012 features (same as @option{-gnat12})
3671
3672 @item -gnata
3673 @cindex @option{-gnata} (@command{gcc})
3674 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3675 activated. Note that these pragmas can also be controlled using the
3676 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3677 It also activates pragmas @code{Check}, @code{Precondition}, and
3678 @code{Postcondition}. Note that these pragmas can also be controlled
3679 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
3680 also activates all assertions defined in the RM as aspects: preconditions,
3681 postconditions, type invariants and (sub)type predicates. In all Ada modes,
3682 corresponding pragmas for type invariants and (sub)type predicates are
3683 also activated.
3684
3685 @item -gnatA
3686 @cindex @option{-gnatA} (@command{gcc})
3687 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
3688 it will be ignored.
3689
3690 @item -gnatb
3691 @cindex @option{-gnatb} (@command{gcc})
3692 Generate brief messages to @file{stderr} even if verbose mode set.
3693
3694 @item -gnatB
3695 @cindex @option{-gnatB} (@command{gcc})
3696 Assume no invalid (bad) values except for 'Valid attribute use
3697 (@pxref{Validity Checking}).
3698
3699 @item -gnatc
3700 @cindex @option{-gnatc} (@command{gcc})
3701 Check syntax and semantics only (no code generation attempted). When the
3702 compiler is invoked by @command{gnatmake}, if the switch @option{-gnatc} is
3703 only given to the compiler (after @option{-cargs} or in package Compiler of
3704 the project file, @command{gnatmake} will fail because it will not find the
3705 object file after compilation. If @command{gnatmake} is called with
3706 @option{-gnatc} as a builder switch (before @option{-cargs} or in package
3707 Builder of the project file) then @command{gnatmake} will not fail because
3708 it will not look for the object files after compilation, and it will not try
3709 to build and link. This switch may not be given if a previous @code{-gnatR}
3710 switch has been given, since @code{-gnatR} requires that the code generator
3711 be called to complete determination of representation information.
3712
3713 @item -gnatC
3714 @cindex @option{-gnatC} (@command{gcc})
3715 Generate CodePeer information (no code generation attempted).
3716 This switch will generate an intermediate representation suitable for
3717 use by CodePeer (@file{.scil} files). This switch is not compatible with
3718 code generation (it will, among other things, disable some switches such
3719 as -gnatn, and enable others such as -gnata).
3720
3721 @item -gnatd
3722 @cindex @option{-gnatd} (@command{gcc})
3723 Specify debug options for the compiler. The string of characters after
3724 the @option{-gnatd} specify the specific debug options. The possible
3725 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3726 compiler source file @file{debug.adb} for details of the implemented
3727 debug options. Certain debug options are relevant to applications
3728 programmers, and these are documented at appropriate points in this
3729 users guide.
3730
3731 @ifclear vms
3732 @item -gnatD
3733 @cindex @option{-gnatD[nn]} (@command{gcc})
3734 @end ifclear
3735 @ifset vms
3736 @item /XDEBUG /LXDEBUG=nnn
3737 @end ifset
3738 Create expanded source files for source level debugging. This switch
3739 also suppress generation of cross-reference information
3740 (see @option{-gnatx}). Note that this switch is not allowed if a previous
3741 -gnatR switch has been given, since these two switches are not compatible.
3742
3743 @item ^-gnateA^/ALIASING_CHECK^
3744 @cindex @option{-gnateA} (@command{gcc})
3745 Check that there is no aliasing between two parameters of the same subprogram.
3746
3747 @item -gnatec=@var{path}
3748 @cindex @option{-gnatec} (@command{gcc})
3749 Specify a configuration pragma file
3750 @ifclear vms
3751 (the equal sign is optional)
3752 @end ifclear
3753 (@pxref{The Configuration Pragmas Files}).
3754
3755 @item ^-gnated^/DISABLE_ATOMIC_SYNCHRONIZATION^
3756 @cindex @option{-gnated} (@command{gcc})
3757 Disable atomic synchronization
3758
3759 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
3760 @cindex @option{-gnateD} (@command{gcc})
3761 Defines a symbol, associated with @var{value}, for preprocessing.
3762 (@pxref{Integrated Preprocessing}).
3763
3764 @item -gnateE
3765 @cindex @option{-gnateE} (@command{gcc})
3766 Generate extra information in exception messages. In particular, display
3767 extra column information and the value and range associated with index and
3768 range check failures, and extra column information for access checks.
3769 In cases where the compiler is able to determine at compile time that
3770 a check will fail, it gives a warning, and the extra information is not
3771 produced at run time.
3772
3773 @item -gnatef
3774 @cindex @option{-gnatef} (@command{gcc})
3775 Display full source path name in brief error messages.
3776
3777 @item -gnateF
3778 @cindex @option{-gnateF} (@command{gcc})
3779 Check for overflow on all floating-point operations, including those
3780 for unconstrained predefined types. See description of pragma
3781 @code{Check_Float_Overflow} in GNAT RM.
3782
3783 @item -gnateG
3784 @cindex @option{-gnateG} (@command{gcc})
3785 Save result of preprocessing in a text file.
3786
3787 @item -gnatei@var{nnn}
3788 @cindex @option{-gnatei} (@command{gcc})
3789 Set maximum number of instantiations during compilation of a single unit to
3790 @var{nnn}. This may be useful in increasing the default maximum of 8000 for
3791 the rare case when a single unit legitimately exceeds this limit.
3792
3793 @item -gnateI@var{nnn}
3794 @cindex @option{-gnateI} (@command{gcc})
3795 Indicates that the source is a multi-unit source and that the index of the
3796 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
3797 to be a valid index in the multi-unit source.
3798
3799 @item -gnatem=@var{path}
3800 @cindex @option{-gnatem} (@command{gcc})
3801 Specify a mapping file
3802 @ifclear vms
3803 (the equal sign is optional)
3804 @end ifclear
3805 (@pxref{Units to Sources Mapping Files}).
3806
3807 @item -gnatep=@var{file}
3808 @cindex @option{-gnatep} (@command{gcc})
3809 Specify a preprocessing data file
3810 @ifclear vms
3811 (the equal sign is optional)
3812 @end ifclear
3813 (@pxref{Integrated Preprocessing}).
3814
3815 @item -gnateP
3816 @cindex @option{-gnateP} (@command{gcc})
3817 Turn categorization dependency errors into warnings.
3818 Ada requires that units that WITH one another have compatible categories, for
3819 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
3820 these errors become warnings (which can be ignored, or suppressed in the usual
3821 manner). This can be useful in some specialized circumstances such as the
3822 temporary use of special test software.
3823
3824 @item -gnateS
3825 @cindex @option{-gnateS} (@command{gcc})
3826 Synonym of @option{-fdump-scos}, kept for backards compatibility.
3827
3828 @item -gnatet=@var{path}
3829 @cindex @option{-gnatet=file} (@command{gcc})
3830 Generate target dependent information. The format of the output file is
3831 described in the section about switch @option{-gnateT}.
3832
3833 @item -gnateT=@var{path}
3834 @cindex @option{-gnateT} (@command{gcc})
3835 Read target dependent information, such as endianness or sizes and alignments
3836 of base type. If this switch is passed, the default target dependent
3837 information of the compiler is replaced by the one read from the input file.
3838 This is used by tools other than the compiler, e.g. to do
3839 semantic analysis of programs that will run on some other target than
3840 the machine on which the tool is run.
3841
3842 The following target dependent values should be defined,
3843 where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
3844 positive integer value, and fields marked with a question mark are
3845 boolean fields, where a value of 0 is False, and a value of 1 is True:
3846
3847 @smallexample
3848 Bits_BE                    : Nat; -- Bits stored big-endian?
3849 Bits_Per_Unit              : Pos; -- Bits in a storage unit
3850 Bits_Per_Word              : Pos; -- Bits in a word
3851 Bytes_BE                   : Nat; -- Bytes stored big-endian?
3852 Char_Size                  : Pos; -- Standard.Character'Size
3853 Double_Float_Alignment     : Nat; -- Alignment of double float
3854 Double_Scalar_Alignment    : Nat; -- Alignment of double length scalar
3855 Double_Size                : Pos; -- Standard.Long_Float'Size
3856 Float_Size                 : Pos; -- Standard.Float'Size
3857 Float_Words_BE             : Nat; -- Float words stored big-endian?
3858 Int_Size                   : Pos; -- Standard.Integer'Size
3859 Long_Double_Size           : Pos; -- Standard.Long_Long_Float'Size
3860 Long_Long_Size             : Pos; -- Standard.Long_Long_Integer'Size
3861 Long_Size                  : Pos; -- Standard.Long_Integer'Size
3862 Maximum_Alignment          : Pos; -- Maximum permitted alignment
3863 Max_Unaligned_Field        : Pos; -- Maximum size for unaligned bit field
3864 Pointer_Size               : Pos; -- System.Address'Size
3865 Short_Size                 : Pos; -- Standard.Short_Integer'Size
3866 Strict_Alignment           : Nat; -- Strict alignment?
3867 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
3868 Wchar_T_Size               : Pos; -- Interfaces.C.wchar_t'Size
3869 Words_BE                   : Nat; -- Words stored big-endian?
3870 @end smallexample
3871
3872 The format of the input file is as follows. First come the values of
3873 the variables defined above, with one line per value:
3874
3875 @smallexample
3876 name  value
3877 @end smallexample
3878
3879 where @code{name} is the name of the parameter, spelled out in full,
3880 and cased as in the above list, and @code{value} is an unsigned decimal
3881 integer. Two or more blanks separates the name from the value.
3882
3883 All the variables must be present, in alphabetical order (i.e. the
3884 same order as the list above).
3885
3886 Then there is a blank line to separate the two parts of the file. Then
3887 come the lines showing the floating-point types to be registered, with
3888 one line per registered mode:
3889
3890 @smallexample
3891 name  digs float_rep size alignment
3892 @end smallexample
3893
3894 where @code{name} is the string name of the type (which can have
3895 single spaces embedded in the name (e.g. long double), @code{digs} is
3896 the number of digits for the floating-point type, @code{float_rep} is
3897 the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
3898 AAMP), @code{size} is the size in bits, @code{alignment} is the
3899 alignment in bits. The name is followed by at least two blanks, fields
3900 are separated by at least one blank, and a LF character immediately
3901 follows the alignment field.
3902
3903 Here is an example of target parametrization file:
3904
3905 @smallexample
3906 Bits_BE                       0
3907 Bits_Per_Unit                 8
3908 Bits_Per_Word                64
3909 Bytes_BE                      0
3910 Char_Size                     8
3911 Double_Float_Alignment        0
3912 Double_Scalar_Alignment       0
3913 Double_Size                  64
3914 Float_Size                   32
3915 Float_Words_BE                0
3916 Int_Size                     64
3917 Long_Double_Size            128
3918 Long_Long_Size               64
3919 Long_Size                    64
3920 Maximum_Alignment            16
3921 Max_Unaligned_Field          64
3922 Pointer_Size                 64
3923 Short_Size                   16
3924 Strict_Alignment              0
3925 System_Allocator_Alignment   16
3926 Wchar_T_Size                 32
3927 Words_BE                      0
3928
3929 float         15  I  64  64
3930 double        15  I  64  64
3931 long double   18  I  80 128
3932 TF            33  I 128 128
3933 @end smallexample
3934
3935 @item -gnateu
3936 @cindex @option{-gnateu} (@command{gcc})
3937 Ignore unrecognized validity, warning, and style switches that
3938 apppear after this switch is given. This may be useful when
3939 compiling sources developed on a later version of the compiler
3940 with an earlier version. Of course the earlier version must
3941 support this switch.
3942
3943 @item ^-gnateV^/PARAMETER_VALIDITY_CHECK^
3944 @cindex @option{-gnateV} (@command{gcc})
3945 Check validity of subprogram parameters.
3946
3947 @item ^-gnateY^/IGNORE_SUPPRESS_SYLE_CHECK_PRAGMAS^
3948 @cindex @option{-gnateY} (@command{gcc})
3949 Ignore all STYLE_CHECKS pragmas. Full legality checks
3950 are still carried out, but the pragmas have no effect
3951 on what style checks are active. This allows all style
3952 checking options to be controlled from the command line.
3953
3954 @item -gnatE
3955 @cindex @option{-gnatE} (@command{gcc})
3956 Full dynamic elaboration checks.
3957
3958 @item -gnatf
3959 @cindex @option{-gnatf} (@command{gcc})
3960 Full errors. Multiple errors per line, all undefined references, do not
3961 attempt to suppress cascaded errors.
3962
3963 @item -gnatF
3964 @cindex @option{-gnatF} (@command{gcc})
3965 Externals names are folded to all uppercase.
3966
3967 @item ^-gnatg^/GNAT_INTERNAL^
3968 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
3969 Internal GNAT implementation mode. This should not be used for
3970 applications programs, it is intended only for use by the compiler
3971 and its run-time library. For documentation, see the GNAT sources.
3972 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
3973 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
3974 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
3975 so that all standard warnings and all standard style options are turned on.
3976 All warnings and style messages are treated as errors.
3977
3978 @ifclear vms
3979 @item -gnatG=nn
3980 @cindex @option{-gnatG[nn]} (@command{gcc})
3981 @end ifclear
3982 @ifset vms
3983 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
3984 @end ifset
3985 List generated expanded code in source form.
3986
3987 @item ^-gnath^/HELP^
3988 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3989 Output usage information. The output is written to @file{stdout}.
3990
3991 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3992 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3993 Identifier character set
3994 @ifclear vms
3995 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3996 @end ifclear
3997 For details of the possible selections for @var{c},
3998 see @ref{Character Set Control}.
3999
4000 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4001 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4002 Ignore representation clauses. When this switch is used,
4003 representation clauses are treated as comments. This is useful
4004 when initially porting code where you want to ignore rep clause
4005 problems, and also for compiling foreign code (particularly
4006 for use with ASIS). The representation clauses that are ignored
4007 are: enumeration_representation_clause, record_representation_clause,
4008 and attribute_definition_clause for the following attributes:
4009 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4010 Object_Size, Size, Small, Stream_Size, and Value_Size.
4011 Note that this option should be used only for compiling -- the
4012 code is likely to malfunction at run time.
4013
4014 @item -gnatjnn
4015 @cindex @option{-gnatjnn} (@command{gcc})
4016 Reformat error messages to fit on nn character lines
4017
4018 @item -gnatk=@var{n}
4019 @cindex @option{-gnatk} (@command{gcc})
4020 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4021
4022 @item -gnatl
4023 @cindex @option{-gnatl} (@command{gcc})
4024 Output full source listing with embedded error messages.
4025
4026 @item -gnatL
4027 @cindex @option{-gnatL} (@command{gcc})
4028 Used in conjunction with -gnatG or -gnatD to intersperse original
4029 source lines (as comment lines with line numbers) in the expanded
4030 source output.
4031
4032 @item -gnatm=@var{n}
4033 @cindex @option{-gnatm} (@command{gcc})
4034 Limit number of detected error or warning messages to @var{n}
4035 where @var{n} is in the range 1..999999. The default setting if
4036 no switch is given is 9999. If the number of warnings reaches this
4037 limit, then a message is output and further warnings are suppressed,
4038 but the compilation is continued. If the number of error messages
4039 reaches this limit, then a message is output and the compilation
4040 is abandoned. The equal sign here is optional. A value of zero
4041 means that no limit applies.
4042
4043 @item -gnatn[12]
4044 @cindex @option{-gnatn} (@command{gcc})
4045 Activate inlining for subprograms for which pragma @code{Inline} is
4046 specified. This inlining is performed by the GCC back-end. An optional
4047 digit sets the inlining level: 1 for moderate inlining across modules
4048 or 2 for full inlining across modules. If no inlining level is specified,
4049 the compiler will pick it based on the optimization level.
4050
4051 @item -gnatN
4052 @cindex @option{-gnatN} (@command{gcc})
4053 Activate front end inlining for subprograms for which
4054 pragma @code{Inline} is specified. This inlining is performed
4055 by the front end and will be visible in the
4056 @option{-gnatG} output.
4057
4058 When using a gcc-based back end (in practice this means using any version
4059 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4060 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4061 Historically front end inlining was more extensive than the gcc back end
4062 inlining, but that is no longer the case.
4063
4064 @item -gnato??
4065 @cindex @option{-gnato??} (@command{gcc})
4066 Set default mode for handling generation of code to avoid intermediate
4067 arithmetic overflow. Here `@code{??}' is two digits, a
4068 single digit, or nothing. Each digit is one of the digits `@code{1}'
4069 through `@code{3}':
4070
4071 @itemize @bullet
4072 @item   @code{1}:
4073 all intermediate overflows checked against base type (@code{STRICT})
4074 @item   @code{2}:
4075 minimize intermediate overflows (@code{MINIMIZED})
4076 @item   @code{3}:
4077 eliminate intermediate overflows (@code{ELIMINATED})
4078 @end itemize
4079
4080 If only one digit appears then it applies to all
4081 cases; if two digits are given, then the first applies outside
4082 assertions, and the second within assertions.
4083
4084 If no digits follow the @option{-gnato}, then it is equivalent to
4085 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
4086 causing all intermediate overflows to be handled in strict mode.
4087
4088 This switch also causes arithmetic overflow checking to be performed
4089 (as though pragma @code{Unsuppress (Overflow_Mode)} has been specified.
4090
4091 The default if no option @option{-gnato} is given is that overflow handling
4092 is in @code{STRICT} mode (computations done using the base type), and that
4093 overflow checking is suppressed.
4094
4095 Note that division by zero is a separate check that is not
4096 controlled by this switch (division by zero checking is on by default).
4097
4098 See also @ref{Specifying the Desired Mode}.
4099
4100 @item -gnatp
4101 @cindex @option{-gnatp} (@command{gcc})
4102 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4103 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4104
4105 @item -gnat-p
4106 @cindex @option{-gnat-p} (@command{gcc})
4107 Cancel effect of previous @option{-gnatp} switch.
4108
4109 @item -gnatP
4110 @cindex @option{-gnatP} (@command{gcc})
4111 Enable polling. This is required on some systems (notably Windows NT) to
4112 obtain asynchronous abort and asynchronous transfer of control capability.
4113 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4114 details.
4115
4116 @item -gnatq
4117 @cindex @option{-gnatq} (@command{gcc})
4118 Don't quit. Try semantics, even if parse errors.
4119
4120 @item -gnatQ
4121 @cindex @option{-gnatQ} (@command{gcc})
4122 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4123
4124 @item -gnatr
4125 @cindex @option{-gnatr} (@command{gcc})
4126 Treat pragma Restrictions as Restriction_Warnings.
4127
4128 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4129 @cindex @option{-gnatR} (@command{gcc})
4130 Output representation information for declared types and objects.
4131 Note that this switch is not allowed if a previous @code{-gnatD} switch has
4132 been given, since these two switches are not compatible. It is also not allowed
4133 if a previous @code{-gnatc} switch has been given, since we must be generating
4134 code to be able to determine representation information.
4135
4136 @item ^-gnatRm[s]^/REPRESENTATION_INFO^
4137 Output convention and parameter passing mechanisms for all subprograms.
4138 This form is also incompatible with the use of @code{-gnatc}.
4139
4140 @item -gnats
4141 @cindex @option{-gnats} (@command{gcc})
4142 Syntax check only.
4143
4144 @item -gnatS
4145 @cindex @option{-gnatS} (@command{gcc})
4146 Print package Standard.
4147
4148 @item -gnatt
4149 @cindex @option{-gnatt} (@command{gcc})
4150 Generate tree output file.
4151
4152 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4153 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4154 All compiler tables start at @var{nnn} times usual starting size.
4155
4156 @item -gnatu
4157 @cindex @option{-gnatu} (@command{gcc})
4158 List units for this compilation.
4159
4160 @item -gnatU
4161 @cindex @option{-gnatU} (@command{gcc})
4162 Tag all error messages with the unique string ``error:''
4163
4164 @item -gnatv
4165 @cindex @option{-gnatv} (@command{gcc})
4166 Verbose mode. Full error output with source lines to @file{stdout}.
4167
4168 @item -gnatV
4169 @cindex @option{-gnatV} (@command{gcc})
4170 Control level of validity checking (@pxref{Validity Checking}).
4171
4172 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4173 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4174 Warning mode where
4175 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4176 the exact warnings that
4177 are enabled or disabled (@pxref{Warning Message Control}).
4178
4179 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4180 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4181 Wide character encoding method
4182 @ifclear vms
4183 (@var{e}=n/h/u/s/e/8).
4184 @end ifclear
4185 @ifset vms
4186 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4187 @end ifset
4188
4189 @item -gnatx
4190 @cindex @option{-gnatx} (@command{gcc})
4191 Suppress generation of cross-reference information.
4192
4193 @item -gnatX
4194 @cindex @option{-gnatX} (@command{gcc})
4195 Enable GNAT implementation extensions and latest Ada version.
4196
4197 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4198 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4199 Enable built-in style checks (@pxref{Style Checking}).
4200
4201 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4202 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4203 Distribution stub generation and compilation
4204 @ifclear vms
4205 (@var{m}=r/c for receiver/caller stubs).
4206 @end ifclear
4207 @ifset vms
4208 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4209 to be generated and compiled).
4210 @end ifset
4211
4212 @item ^-I^/SEARCH=^@var{dir}
4213 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4214 @cindex RTL
4215 Direct GNAT to search the @var{dir} directory for source files needed by
4216 the current compilation
4217 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4218
4219 @item ^-I-^/NOCURRENT_DIRECTORY^
4220 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4221 @cindex RTL
4222 Except for the source file named in the command line, do not look for source
4223 files in the directory containing the source file named in the command line
4224 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4225
4226 @ifclear vms
4227 @item -mbig-switch
4228 @cindex @option{-mbig-switch} (@command{gcc})
4229 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4230 This standard gcc switch causes the compiler to use larger offsets in its
4231 jump table representation for @code{case} statements.
4232 This may result in less efficient code, but is sometimes necessary
4233 (for example on HP-UX targets)
4234 @cindex HP-UX and @option{-mbig-switch} option
4235 in order to compile large and/or nested @code{case} statements.
4236
4237 @item -o @var{file}
4238 @cindex @option{-o} (@command{gcc})
4239 This switch is used in @command{gcc} to redirect the generated object file
4240 and its associated ALI file. Beware of this switch with GNAT, because it may
4241 cause the object file and ALI file to have different names which in turn
4242 may confuse the binder and the linker.
4243 @end ifclear
4244
4245 @item -nostdinc
4246 @cindex @option{-nostdinc} (@command{gcc})
4247 Inhibit the search of the default location for the GNAT Run Time
4248 Library (RTL) source files.
4249
4250 @item -nostdlib
4251 @cindex @option{-nostdlib} (@command{gcc})
4252 Inhibit the search of the default location for the GNAT Run Time
4253 Library (RTL) ALI files.
4254
4255 @ifclear vms
4256 @c @item -O@ovar{n}
4257 @c Expanding @ovar macro inline (explanation in macro def comments)
4258 @item -O@r{[}@var{n}@r{]}
4259 @cindex @option{-O} (@command{gcc})
4260 @var{n} controls the optimization level.
4261
4262 @table @asis
4263 @item n = 0
4264 No optimization, the default setting if no @option{-O} appears
4265
4266 @item n = 1
4267 Normal optimization, the default if you specify @option{-O} without
4268 an operand. A good compromise between code quality and compilation
4269 time.
4270
4271 @item n = 2
4272 Extensive optimization, may improve execution time, possibly at the cost of
4273 substantially increased compilation time.
4274
4275 @item n = 3
4276 Same as @option{-O2}, and also includes inline expansion for small subprograms
4277 in the same unit.
4278
4279 @item n = s
4280 Optimize space usage
4281 @end table
4282
4283 @noindent
4284 See also @ref{Optimization Levels}.
4285 @end ifclear
4286
4287 @ifset vms
4288 @item  /NOOPTIMIZE
4289 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4290 Equivalent to @option{/OPTIMIZE=NONE}.
4291 This is the default behavior in the absence of an @option{/OPTIMIZE}
4292 qualifier.
4293
4294 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4295 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4296 Selects the level of optimization for your program. The supported
4297 keywords are as follows:
4298 @table @code
4299 @item   ALL
4300 Perform most optimizations, including those that
4301 are expensive.
4302 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4303 without keyword options.
4304
4305 @item   NONE
4306 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4307
4308 @item SOME
4309 Perform some optimizations, but omit ones that are costly.
4310
4311 @item   DEVELOPMENT
4312 Same as @code{SOME}.
4313
4314 @item INLINING
4315 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4316 automatic inlining of small subprograms within a unit
4317
4318 @item   UNROLL_LOOPS
4319 Try to unroll loops. This keyword may be specified together with
4320 any keyword above other than @code{NONE}. Loop unrolling
4321 usually, but not always, improves the performance of programs.
4322
4323 @item SPACE
4324 Optimize space usage
4325 @end table
4326
4327 @noindent
4328 See also @ref{Optimization Levels}.
4329 @end ifset
4330
4331 @ifclear vms
4332 @item -pass-exit-codes
4333 @cindex @option{-pass-exit-codes} (@command{gcc})
4334 Catch exit codes from the compiler and use the most meaningful as
4335 exit status.
4336 @end ifclear
4337
4338 @item --RTS=@var{rts-path}
4339 @cindex @option{--RTS} (@command{gcc})
4340 Specifies the default location of the runtime library. Same meaning as the
4341 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4342
4343 @item ^-S^/ASM^
4344 @cindex @option{^-S^/ASM^} (@command{gcc})
4345 ^Used in place of @option{-c} to^Used to^
4346 cause the assembler source file to be
4347 generated, using @file{^.s^.S^} as the extension,
4348 instead of the object file.
4349 This may be useful if you need to examine the generated assembly code.
4350
4351 @item ^-fverbose-asm^/VERBOSE_ASM^
4352 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4353 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4354 to cause the generated assembly code file to be annotated with variable
4355 names, making it significantly easier to follow.
4356
4357 @item ^-v^/VERBOSE^
4358 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4359 Show commands generated by the @command{gcc} driver. Normally used only for
4360 debugging purposes or if you need to be sure what version of the
4361 compiler you are executing.
4362
4363 @ifclear vms
4364 @item -V @var{ver}
4365 @cindex @option{-V} (@command{gcc})
4366 Execute @var{ver} version of the compiler. This is the @command{gcc}
4367 version, not the GNAT version.
4368 @end ifclear
4369
4370 @item ^-w^/NO_BACK_END_WARNINGS^
4371 @cindex @option{-w} (@command{gcc})
4372 Turn off warnings generated by the back end of the compiler. Use of
4373 this switch also causes the default for front end warnings to be set
4374 to suppress (as though @option{-gnatws} had appeared at the start of
4375 the options).
4376
4377 @end table
4378
4379 @ifclear vms
4380 @c Combining qualifiers does not work on VMS
4381 You may combine a sequence of GNAT switches into a single switch. For
4382 example, the combined switch
4383
4384 @cindex Combining GNAT switches
4385 @smallexample
4386 -gnatofi3
4387 @end smallexample
4388
4389 @noindent
4390 is equivalent to specifying the following sequence of switches:
4391
4392 @smallexample
4393 -gnato -gnatf -gnati3
4394 @end smallexample
4395 @end ifclear
4396
4397 @noindent
4398 The following restrictions apply to the combination of switches
4399 in this manner:
4400
4401 @itemize @bullet
4402 @item
4403 The switch @option{-gnatc} if combined with other switches must come
4404 first in the string.
4405
4406 @item
4407 The switch @option{-gnats} if combined with other switches must come
4408 first in the string.
4409
4410 @item
4411 The switches
4412 ^^@option{/DISTRIBUTION_STUBS=},^
4413 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4414 switches, and only one of them may appear in the command line.
4415
4416 @item
4417 The switch @option{-gnat-p} may not be combined with any other switch.
4418
4419 @ifclear vms
4420 @item
4421 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4422 switch), then all further characters in the switch are interpreted
4423 as style modifiers (see description of @option{-gnaty}).
4424
4425 @item
4426 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4427 switch), then all further characters in the switch are interpreted
4428 as debug flags (see description of @option{-gnatd}).
4429
4430 @item
4431 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4432 switch), then all further characters in the switch are interpreted
4433 as warning mode modifiers (see description of @option{-gnatw}).
4434
4435 @item
4436 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4437 switch), then all further characters in the switch are interpreted
4438 as validity checking options (@pxref{Validity Checking}).
4439
4440 @item
4441 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4442 a combined list of options.
4443 @end ifclear
4444 @end itemize
4445
4446 @node Output and Error Message Control
4447 @subsection Output and Error Message Control
4448 @findex stderr
4449
4450 @noindent
4451 The standard default format for error messages is called ``brief format''.
4452 Brief format messages are written to @file{stderr} (the standard error
4453 file) and have the following form:
4454
4455 @smallexample
4456 e.adb:3:04: Incorrect spelling of keyword "function"
4457 e.adb:4:20: ";" should be "is"
4458 @end smallexample
4459
4460 @noindent
4461 The first integer after the file name is the line number in the file,
4462 and the second integer is the column number within the line.
4463 @ifclear vms
4464 @code{GPS} can parse the error messages
4465 and point to the referenced character.
4466 @end ifclear
4467 The following switches provide control over the error message
4468 format:
4469
4470 @table @option
4471 @c !sort!
4472 @item -gnatv
4473 @cindex @option{-gnatv} (@command{gcc})
4474 @findex stdout
4475 @ifclear vms
4476 The v stands for verbose.
4477 @end ifclear
4478 The effect of this setting is to write long-format error
4479 messages to @file{stdout} (the standard output file.
4480 The same program compiled with the
4481 @option{-gnatv} switch would generate:
4482
4483 @smallexample
4484 @cartouche
4485 3. funcion X (Q : Integer)
4486    |
4487 >>> Incorrect spelling of keyword "function"
4488 4. return Integer;
4489                  |
4490 >>> ";" should be "is"
4491 @end cartouche
4492 @end smallexample
4493
4494 @noindent
4495 The vertical bar indicates the location of the error, and the @samp{>>>}
4496 prefix can be used to search for error messages. When this switch is
4497 used the only source lines output are those with errors.
4498
4499 @item -gnatl
4500 @cindex @option{-gnatl} (@command{gcc})
4501 @ifclear vms
4502 The @code{l} stands for list.
4503 @end ifclear
4504 This switch causes a full listing of
4505 the file to be generated. In the case where a body is
4506 compiled, the corresponding spec is also listed, along
4507 with any subunits. Typical output from compiling a package
4508 body @file{p.adb} might look like:
4509
4510 @smallexample @c ada
4511 @cartouche
4512  Compiling: p.adb
4513
4514      1. package body p is
4515      2.    procedure a;
4516      3.    procedure a is separate;
4517      4. begin
4518      5.    null
4519                |
4520         >>> missing ";"
4521
4522      6. end;
4523
4524 Compiling: p.ads
4525
4526      1. package p is
4527      2.    pragma Elaborate_Body
4528                                 |
4529         >>> missing ";"
4530
4531      3. end p;
4532
4533 Compiling: p-a.adb
4534
4535      1. separate p
4536                 |
4537         >>> missing "("
4538
4539      2. procedure a is
4540      3. begin
4541      4.    null
4542                |
4543         >>> missing ";"
4544
4545      5. end;
4546 @end cartouche
4547 @end smallexample
4548
4549 @noindent
4550 @findex stderr
4551 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4552 standard output is redirected, a brief summary is written to
4553 @file{stderr} (standard error) giving the number of error messages and
4554 warning messages generated.
4555
4556 @item ^-gnatl^/OUTPUT_FILE^=file
4557 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4558 This has the same effect as @option{-gnatl} except that the output is
4559 written to a file instead of to standard output. If the given name
4560 @file{fname} does not start with a period, then it is the full name
4561 of the file to be written. If @file{fname} is an extension, it is
4562 appended to the name of the file being compiled. For example, if
4563 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4564 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4565
4566 @item -gnatU
4567 @cindex @option{-gnatU} (@command{gcc})
4568 This switch forces all error messages to be preceded by the unique
4569 string ``error:''. This means that error messages take a few more
4570 characters in space, but allows easy searching for and identification
4571 of error messages.
4572
4573 @item -gnatb
4574 @cindex @option{-gnatb} (@command{gcc})
4575 @ifclear vms
4576 The @code{b} stands for brief.
4577 @end ifclear
4578 This switch causes GNAT to generate the
4579 brief format error messages to @file{stderr} (the standard error
4580 file) as well as the verbose
4581 format message or full listing (which as usual is written to
4582 @file{stdout} (the standard output file).
4583
4584 @item -gnatm=@var{n}
4585 @cindex @option{-gnatm} (@command{gcc})
4586 @ifclear vms
4587 The @code{m} stands for maximum.
4588 @end ifclear
4589 @var{n} is a decimal integer in the
4590 range of 1 to 999999 and limits the number of error or warning
4591 messages to be generated. For example, using
4592 @option{-gnatm2} might yield
4593
4594 @smallexample
4595 e.adb:3:04: Incorrect spelling of keyword "function"
4596 e.adb:5:35: missing ".."
4597 fatal error: maximum number of errors detected
4598 compilation abandoned
4599 @end smallexample
4600
4601 @noindent
4602 The default setting if
4603 no switch is given is 9999. If the number of warnings reaches this
4604 limit, then a message is output and further warnings are suppressed,
4605 but the compilation is continued. If the number of error messages
4606 reaches this limit, then a message is output and the compilation
4607 is abandoned. A value of zero means that no limit applies.
4608
4609 @noindent
4610 Note that the equal sign is optional, so the switches
4611 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4612
4613 @item -gnatf
4614 @cindex @option{-gnatf} (@command{gcc})
4615 @cindex Error messages, suppressing
4616 @ifclear vms
4617 The @code{f} stands for full.
4618 @end ifclear
4619 Normally, the compiler suppresses error messages that are likely to be
4620 redundant. This switch causes all error
4621 messages to be generated. In particular, in the case of
4622 references to undefined variables. If a given variable is referenced
4623 several times, the normal format of messages is
4624 @smallexample
4625 e.adb:7:07: "V" is undefined (more references follow)
4626 @end smallexample
4627
4628 @noindent
4629 where the parenthetical comment warns that there are additional
4630 references to the variable @code{V}. Compiling the same program with the
4631 @option{-gnatf} switch yields
4632
4633 @smallexample
4634 e.adb:7:07: "V" is undefined
4635 e.adb:8:07: "V" is undefined
4636 e.adb:8:12: "V" is undefined
4637 e.adb:8:16: "V" is undefined
4638 e.adb:9:07: "V" is undefined
4639 e.adb:9:12: "V" is undefined
4640 @end smallexample
4641
4642 @noindent
4643 The @option{-gnatf} switch also generates additional information for
4644 some error messages.  Some examples are:
4645
4646 @itemize @bullet
4647 @item
4648 Details on possibly non-portable unchecked conversion
4649 @item
4650 List possible interpretations for ambiguous calls
4651 @item
4652 Additional details on incorrect parameters
4653 @end itemize
4654
4655 @item -gnatjnn
4656 @cindex @option{-gnatjnn} (@command{gcc})
4657 In normal operation mode (or if @option{-gnatj0} is used), then error messages
4658 with continuation lines are treated as though the continuation lines were
4659 separate messages (and so a warning with two continuation lines counts as
4660 three warnings, and is listed as three separate messages).
4661
4662 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4663 messages are output in a different manner. A message and all its continuation
4664 lines are treated as a unit, and count as only one warning or message in the
4665 statistics totals. Furthermore, the message is reformatted so that no line
4666 is longer than nn characters.
4667
4668 @item -gnatq
4669 @cindex @option{-gnatq} (@command{gcc})
4670 @ifclear vms
4671 The @code{q} stands for quit (really ``don't quit'').
4672 @end ifclear
4673 In normal operation mode, the compiler first parses the program and
4674 determines if there are any syntax errors. If there are, appropriate
4675 error messages are generated and compilation is immediately terminated.
4676 This switch tells
4677 GNAT to continue with semantic analysis even if syntax errors have been
4678 found. This may enable the detection of more errors in a single run. On
4679 the other hand, the semantic analyzer is more likely to encounter some
4680 internal fatal error when given a syntactically invalid tree.
4681
4682 @item -gnatQ
4683 @cindex @option{-gnatQ} (@command{gcc})
4684 In normal operation mode, the @file{ALI} file is not generated if any
4685 illegalities are detected in the program. The use of @option{-gnatQ} forces
4686 generation of the @file{ALI} file. This file is marked as being in
4687 error, so it cannot be used for binding purposes, but it does contain
4688 reasonably complete cross-reference information, and thus may be useful
4689 for use by tools (e.g., semantic browsing tools or integrated development
4690 environments) that are driven from the @file{ALI} file. This switch
4691 implies @option{-gnatq}, since the semantic phase must be run to get a
4692 meaningful ALI file.
4693
4694 In addition, if @option{-gnatt} is also specified, then the tree file is
4695 generated even if there are illegalities. It may be useful in this case
4696 to also specify @option{-gnatq} to ensure that full semantic processing
4697 occurs. The resulting tree file can be processed by ASIS, for the purpose
4698 of providing partial information about illegal units, but if the error
4699 causes the tree to be badly malformed, then ASIS may crash during the
4700 analysis.
4701
4702 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4703 being in error, @command{gnatmake} will attempt to recompile the source when it
4704 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4705
4706 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4707 since ALI files are never generated if @option{-gnats} is set.
4708
4709 @end table
4710
4711 @node Warning Message Control
4712 @subsection Warning Message Control
4713 @cindex Warning messages
4714 @noindent
4715 In addition to error messages, which correspond to illegalities as defined
4716 in the Ada Reference Manual, the compiler detects two kinds of warning
4717 situations.
4718
4719 First, the compiler considers some constructs suspicious and generates a
4720 warning message to alert you to a possible error. Second, if the
4721 compiler detects a situation that is sure to raise an exception at
4722 run time, it generates a warning message. The following shows an example
4723 of warning messages:
4724 @smallexample
4725 e.adb:4:24: warning: creation of object may raise Storage_Error
4726 e.adb:10:17: warning: static value out of range
4727 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4728 @end smallexample
4729
4730 @noindent
4731 GNAT considers a large number of situations as appropriate
4732 for the generation of warning messages. As always, warnings are not
4733 definite indications of errors. For example, if you do an out-of-range
4734 assignment with the deliberate intention of raising a
4735 @code{Constraint_Error} exception, then the warning that may be
4736 issued does not indicate an error. Some of the situations for which GNAT
4737 issues warnings (at least some of the time) are given in the following
4738 list. This list is not complete, and new warnings are often added to
4739 subsequent versions of GNAT. The list is intended to give a general idea
4740 of the kinds of warnings that are generated.
4741
4742 @itemize @bullet
4743 @item
4744 Possible infinitely recursive calls
4745
4746 @item
4747 Out-of-range values being assigned
4748
4749 @item
4750 Possible order of elaboration problems
4751
4752 @item
4753 Assertions (pragma Assert) that are sure to fail
4754
4755 @item
4756 Unreachable code
4757
4758 @item
4759 Address clauses with possibly unaligned values, or where an attempt is
4760 made to overlay a smaller variable with a larger one.
4761
4762 @item
4763 Fixed-point type declarations with a null range
4764
4765 @item
4766 Direct_IO or Sequential_IO instantiated with a type that has access values
4767
4768 @item
4769 Variables that are never assigned a value
4770
4771 @item
4772 Variables that are referenced before being initialized
4773
4774 @item
4775 Task entries with no corresponding @code{accept} statement
4776
4777 @item
4778 Duplicate accepts for the same task entry in a @code{select}
4779
4780 @item
4781 Objects that take too much storage
4782
4783 @item
4784 Unchecked conversion between types of differing sizes
4785
4786 @item
4787 Missing @code{return} statement along some execution path in a function
4788
4789 @item
4790 Incorrect (unrecognized) pragmas
4791
4792 @item
4793 Incorrect external names
4794
4795 @item
4796 Allocation from empty storage pool
4797
4798 @item
4799 Potentially blocking operation in protected type
4800
4801 @item
4802 Suspicious parenthesization of expressions
4803
4804 @item
4805 Mismatching bounds in an aggregate
4806
4807 @item
4808 Attempt to return local value by reference
4809
4810 @item
4811 Premature instantiation of a generic body
4812
4813 @item
4814 Attempt to pack aliased components
4815
4816 @item
4817 Out of bounds array subscripts
4818
4819 @item
4820 Wrong length on string assignment
4821
4822 @item
4823 Violations of style rules if style checking is enabled
4824
4825 @item
4826 Unused @code{with} clauses
4827
4828 @item
4829 @code{Bit_Order} usage that does not have any effect
4830
4831 @item
4832 @code{Standard.Duration} used to resolve universal fixed expression
4833
4834 @item
4835 Dereference of possibly null value
4836
4837 @item
4838 Declaration that is likely to cause storage error
4839
4840 @item
4841 Internal GNAT unit @code{with}'ed by application unit
4842
4843 @item
4844 Values known to be out of range at compile time
4845
4846 @item
4847 Unreferenced labels and variables
4848
4849 @item
4850 Address overlays that could clobber memory
4851
4852 @item
4853 Unexpected initialization when address clause present
4854
4855 @item
4856 Bad alignment for address clause
4857
4858 @item
4859 Useless type conversions
4860
4861 @item
4862 Redundant assignment statements and other redundant constructs
4863
4864 @item
4865 Useless exception handlers
4866
4867 @item
4868 Accidental hiding of name by child unit
4869
4870 @item
4871 Access before elaboration detected at compile time
4872
4873 @item
4874 A range in a @code{for} loop that is known to be null or might be null
4875
4876 @end itemize
4877
4878 @noindent
4879 The following section lists compiler switches that are available
4880 to control the handling of warning messages. It is also possible
4881 to exercise much finer control over what warnings are issued and
4882 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
4883 gnat_rm, GNAT Reference manual}.
4884
4885 @table @option
4886 @c !sort!
4887 @item -gnatwa
4888 @emph{Activate most optional warnings.}
4889 @cindex @option{-gnatwa} (@command{gcc})
4890 This switch activates most optional warning messages.  See the remaining list
4891 in this section for details on optional warning messages that can be
4892 individually controlled.  The warnings that are not turned on by this
4893 switch are
4894 @option{-gnatwd} (implicit dereferencing),
4895 @option{-gnatwh} (hiding),
4896 @option{-gnatw.d} (tag warnings with -gnatw switch)
4897 @option{-gnatw.h} (holes (gaps) in record layouts)
4898 @option{-gnatw.i} (overlapping actuals),
4899 @option{-gnatw.k} (redefinition of names in standard),
4900 @option{-gnatwl} (elaboration warnings),
4901 @option{-gnatw.l} (inherited aspects),
4902 @option{-gnatw.o} (warn on values set by out parameters ignored),
4903 @option{-gnatwt} (tracking of deleted conditional code)
4904 and @option{-gnatw.u} (unordered enumeration),
4905 All other optional warnings are turned on.
4906
4907 @item -gnatwA
4908 @emph{Suppress all optional errors.}
4909 @cindex @option{-gnatwA} (@command{gcc})
4910 This switch suppresses all optional warning messages, see remaining list
4911 in this section for details on optional warning messages that can be
4912 individually controlled. Note that unlike switch @option{-gnatws}, the
4913 use of switch @option{-gnatwA} does not suppress warnings that are
4914 normally given unconditionally and cannot be individually controlled
4915 (for example, the warning about a missing exit path in a function).
4916 Also, again unlike switch @option{-gnatws}, warnings suppressed by
4917 the use of switch @option{-gnatwA} can be individually turned back
4918 on. For example the use of switch @option{-gnatwA} followed by
4919 switch @option{-gnatwd} will suppress all optional warnings except
4920 the warnings for implicit dereferencing.
4921
4922 @item -gnatw.a
4923 @emph{Activate warnings on failing assertions.}
4924 @cindex @option{-gnatw.a} (@command{gcc})
4925 @cindex Assert failures
4926 This switch activates warnings for assertions where the compiler can tell at
4927 compile time that the assertion will fail. Note that this warning is given
4928 even if assertions are disabled. The default is that such warnings are
4929 generated.
4930
4931 @item -gnatw.A
4932 @emph{Suppress warnings on failing assertions.}
4933 @cindex @option{-gnatw.A} (@command{gcc})
4934 @cindex Assert failures
4935 This switch suppresses warnings for assertions where the compiler can tell at
4936 compile time that the assertion will fail.
4937
4938 @item -gnatwb
4939 @emph{Activate warnings on bad fixed values.}
4940 @cindex @option{-gnatwb} (@command{gcc})
4941 @cindex Bad fixed values
4942 @cindex Fixed-point Small value
4943 @cindex Small value
4944 This switch activates warnings for static fixed-point expressions whose
4945 value is not an exact multiple of Small. Such values are implementation
4946 dependent, since an implementation is free to choose either of the multiples
4947 that surround the value. GNAT always chooses the closer one, but this is not
4948 required behavior, and it is better to specify a value that is an exact
4949 multiple, ensuring predictable execution. The default is that such warnings
4950 are not generated.
4951
4952 @item -gnatwB
4953 @emph{Suppress warnings on bad fixed values.}
4954 @cindex @option{-gnatwB} (@command{gcc})
4955 This switch suppresses warnings for static fixed-point expressions whose
4956 value is not an exact multiple of Small.
4957
4958 @item -gnatw.b
4959 @emph{Activate warnings on biased representation.}
4960 @cindex @option{-gnatw.b} (@command{gcc})
4961 @cindex Biased representation
4962 This switch activates warnings when a size clause, value size clause, component
4963 clause, or component size clause forces the use of biased representation for an
4964 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
4965 to represent 10/11). The default is that such warnings are generated.
4966
4967 @item -gnatw.B
4968 @emph{Suppress warnings on biased representation.}
4969 @cindex @option{-gnatwB} (@command{gcc})
4970 This switch suppresses warnings for representation clauses that force the use
4971 of biased representation.
4972
4973 @item -gnatwc
4974 @emph{Activate warnings on conditionals.}
4975 @cindex @option{-gnatwc} (@command{gcc})
4976 @cindex Conditionals, constant
4977 This switch activates warnings for conditional expressions used in
4978 tests that are known to be True or False at compile time. The default
4979 is that such warnings are not generated.
4980 Note that this warning does
4981 not get issued for the use of boolean variables or constants whose
4982 values are known at compile time, since this is a standard technique
4983 for conditional compilation in Ada, and this would generate too many
4984 false positive warnings.
4985
4986 This warning option also activates a special test for comparisons using
4987 the operators ``>='' and`` <=''.
4988 If the compiler can tell that only the equality condition is possible,
4989 then it will warn that the ``>'' or ``<'' part of the test
4990 is useless and that the operator could be replaced by ``=''.
4991 An example would be comparing a @code{Natural} variable <= 0.
4992
4993 This warning option also generates warnings if
4994 one or both tests is optimized away in a membership test for integer
4995 values if the result can be determined at compile time. Range tests on
4996 enumeration types are not included, since it is common for such tests
4997 to include an end point.
4998
4999 This warning can also be turned on using @option{-gnatwa}.
5000
5001 @item -gnatwC
5002 @emph{Suppress warnings on conditionals.}
5003 @cindex @option{-gnatwC} (@command{gcc})
5004 This switch suppresses warnings for conditional expressions used in
5005 tests that are known to be True or False at compile time.
5006
5007 @item -gnatw.c
5008 @emph{Activate warnings on missing component clauses.}
5009 @cindex @option{-gnatw.c} (@command{gcc})
5010 @cindex Component clause, missing
5011 This switch activates warnings for record components where a record
5012 representation clause is present and has component clauses for the
5013 majority, but not all, of the components. A warning is given for each
5014 component for which no component clause is present.
5015
5016 This warning can also be turned on using @option{-gnatwa}.
5017
5018 @item -gnatw.C
5019 @emph{Suppress warnings on missing component clauses.}
5020 @cindex @option{-gnatwC} (@command{gcc})
5021 This switch suppresses warnings for record components that are
5022 missing a component clause in the situation described above.
5023
5024 @item -gnatwd
5025 @emph{Activate warnings on implicit dereferencing.}
5026 @cindex @option{-gnatwd} (@command{gcc})
5027 If this switch is set, then the use of a prefix of an access type
5028 in an indexed component, slice, or selected component without an
5029 explicit @code{.all} will generate a warning. With this warning
5030 enabled, access checks occur only at points where an explicit
5031 @code{.all} appears in the source code (assuming no warnings are
5032 generated as a result of this switch). The default is that such
5033 warnings are not generated.
5034 Note that @option{-gnatwa} does not affect the setting of
5035 this warning option.
5036
5037 @item -gnatwD
5038 @emph{Suppress warnings on implicit dereferencing.}
5039 @cindex @option{-gnatwD} (@command{gcc})
5040 @cindex Implicit dereferencing
5041 @cindex Dereferencing, implicit
5042 This switch suppresses warnings for implicit dereferences in
5043 indexed components, slices, and selected components.
5044
5045 @item -gnatw.d
5046 @emph{Activate tagging of warning messages.}
5047 @cindex @option{-gnatw.d} (@command{gcc})
5048 If this switch is set, then warning messages are tagged, either with
5049 the string ``@option{-gnatw?}'' showing which switch controls the warning,
5050 or with ``[enabled by default]'' if the warning is not under control of a
5051 specific @option{-gnatw?} switch. This mode is off by default, and is not
5052 affected by the use of @code{-gnatwa}.
5053
5054 @item -gnatw.D
5055 @emph{Deactivate tagging of warning messages.}
5056 @cindex @option{-gnatw.d} (@command{gcc})
5057 If this switch is set, then warning messages return to the default
5058 mode in which warnings are not tagged as described above for
5059 @code{-gnatw.d}.
5060
5061 @item -gnatwe
5062 @emph{Treat warnings and style checks as errors.}
5063 @cindex @option{-gnatwe} (@command{gcc})
5064 @cindex Warnings, treat as error
5065 This switch causes warning messages and style check messages to be
5066 treated as errors.
5067 The warning string still appears, but the warning messages are counted
5068 as errors, and prevent the generation of an object file. Note that this
5069 is the only -gnatw switch that affects the handling of style check messages.
5070
5071 @item -gnatw.e
5072 @emph{Activate every optional warning}
5073 @cindex @option{-gnatw.e} (@command{gcc})
5074 @cindex Warnings, activate every optional warning
5075 This switch activates all optional warnings, including those which
5076 are not activated by @code{-gnatwa}. The use of this switch is not
5077 recommended for normal use. If you turn this switch on, it is almost
5078 certain that you will get large numbers of useless warnings. The
5079 warnings that are excluded from @code{-gnatwa} are typically highly
5080 specialized warnings that are suitable for use only in code that has
5081 been specifically designed according to specialized coding rules.
5082
5083 @item -gnatwf
5084 @emph{Activate warnings on unreferenced formals.}
5085 @cindex @option{-gnatwf} (@command{gcc})
5086 @cindex Formals, unreferenced
5087 This switch causes a warning to be generated if a formal parameter
5088 is not referenced in the body of the subprogram. This warning can
5089 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5090 default is that these warnings are not generated.
5091
5092 @item -gnatwF
5093 @emph{Suppress warnings on unreferenced formals.}
5094 @cindex @option{-gnatwF} (@command{gcc})
5095 This switch suppresses warnings for unreferenced formal
5096 parameters. Note that the
5097 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5098 effect of warning on unreferenced entities other than subprogram
5099 formals.
5100
5101 @item -gnatwg
5102 @emph{Activate warnings on unrecognized pragmas.}
5103 @cindex @option{-gnatwg} (@command{gcc})
5104 @cindex Pragmas, unrecognized
5105 This switch causes a warning to be generated if an unrecognized
5106 pragma is encountered. Apart from issuing this warning, the
5107 pragma is ignored and has no effect. This warning can
5108 also be turned on using @option{-gnatwa}. The default
5109 is that such warnings are issued (satisfying the Ada Reference
5110 Manual requirement that such warnings appear).
5111
5112 @item -gnatwG
5113 @emph{Suppress warnings on unrecognized pragmas.}
5114 @cindex @option{-gnatwG} (@command{gcc})
5115 This switch suppresses warnings for unrecognized pragmas.
5116
5117 @item -gnatwh
5118 @emph{Activate warnings on hiding.}
5119 @cindex @option{-gnatwh} (@command{gcc})
5120 @cindex Hiding of Declarations
5121 This switch activates warnings on hiding declarations.
5122 A declaration is considered hiding
5123 if it is for a non-overloadable entity, and it declares an entity with the
5124 same name as some other entity that is directly or use-visible. The default
5125 is that such warnings are not generated.
5126 Note that @option{-gnatwa} does not affect the setting of this warning option.
5127
5128 @item -gnatwH
5129 @emph{Suppress warnings on hiding.}
5130 @cindex @option{-gnatwH} (@command{gcc})
5131 This switch suppresses warnings on hiding declarations.
5132
5133 @item -gnatw.h
5134 @emph{Activate warnings on holes/gaps in records.}
5135 @cindex @option{-gnatw.h} (@command{gcc})
5136 @cindex Record Representation (gaps)
5137 This switch activates warnings on component clauses in record
5138 representation clauses that leave holes (gaps) in the record layout.
5139 If this warning option is active, then record representation clauses
5140 should specify a contiguous layout, adding unused fill fields if needed.
5141 Note that @option{-gnatwa} does not affect the setting of this warning option.
5142
5143 @item -gnatw.H
5144 @emph{Suppress warnings on holes/gaps in records.}
5145 @cindex @option{-gnatw.H} (@command{gcc})
5146 This switch suppresses warnings on component clauses in record
5147 representation clauses that leave holes (haps) in the record layout.
5148
5149 @item -gnatwi
5150 @emph{Activate warnings on implementation units.}
5151 @cindex @option{-gnatwi} (@command{gcc})
5152 This switch activates warnings for a @code{with} of an internal GNAT
5153 implementation unit, defined as any unit from the @code{Ada},
5154 @code{Interfaces}, @code{GNAT},
5155 ^^@code{DEC},^ or @code{System}
5156 hierarchies that is not
5157 documented in either the Ada Reference Manual or the GNAT
5158 Programmer's Reference Manual. Such units are intended only
5159 for internal implementation purposes and should not be @code{with}'ed
5160 by user programs. The default is that such warnings are generated
5161 This warning can also be turned on using @option{-gnatwa}.
5162
5163 @item -gnatwI
5164 @emph{Disable warnings on implementation units.}
5165 @cindex @option{-gnatwI} (@command{gcc})
5166 This switch disables warnings for a @code{with} of an internal GNAT
5167 implementation unit.
5168
5169 @item -gnatw.i
5170 @emph{Activate warnings on overlapping actuals.}
5171 @cindex @option{-gnatw.i} (@command{gcc})
5172 This switch enables a warning on statically detectable overlapping actuals in
5173 a subprogram call, when one of the actuals is an in-out parameter, and the
5174 types of the actuals are not by-copy types. The warning is off by default,
5175 and is not included under -gnatwa.
5176
5177 @item -gnatw.I
5178 @emph{Disable warnings on overlapping actuals.}
5179 @cindex @option{-gnatw.I} (@command{gcc})
5180 This switch disables warnings on overlapping actuals in a call..
5181
5182 @item -gnatwj
5183 @emph{Activate warnings on obsolescent features (Annex J).}
5184 @cindex @option{-gnatwj} (@command{gcc})
5185 @cindex Features, obsolescent
5186 @cindex Obsolescent features
5187 If this warning option is activated, then warnings are generated for
5188 calls to subprograms marked with @code{pragma Obsolescent} and
5189 for use of features in Annex J of the Ada Reference Manual. In the
5190 case of Annex J, not all features are flagged. In particular use
5191 of the renamed packages (like @code{Text_IO}) and use of package
5192 @code{ASCII} are not flagged, since these are very common and
5193 would generate many annoying positive warnings. The default is that
5194 such warnings are not generated. This warning is also turned on by
5195 the use of @option{-gnatwa}.
5196
5197 In addition to the above cases, warnings are also generated for
5198 GNAT features that have been provided in past versions but which
5199 have been superseded (typically by features in the new Ada standard).
5200 For example, @code{pragma Ravenscar} will be flagged since its
5201 function is replaced by @code{pragma Profile(Ravenscar)}, and
5202 @code{pragma Interface_Name} will be flagged since its function
5203 is replaced by @code{pragma Import}.
5204
5205 Note that this warning option functions differently from the
5206 restriction @code{No_Obsolescent_Features} in two respects.
5207 First, the restriction applies only to annex J features.
5208 Second, the restriction does flag uses of package @code{ASCII}.
5209
5210 @item -gnatwJ
5211 @emph{Suppress warnings on obsolescent features (Annex J).}
5212 @cindex @option{-gnatwJ} (@command{gcc})
5213 This switch disables warnings on use of obsolescent features.
5214
5215 @item -gnatwk
5216 @emph{Activate warnings on variables that could be constants.}
5217 @cindex @option{-gnatwk} (@command{gcc})
5218 This switch activates warnings for variables that are initialized but
5219 never modified, and then could be declared constants. The default is that
5220 such warnings are not given.
5221 This warning can also be turned on using @option{-gnatwa}.
5222
5223 @item -gnatwK
5224 @emph{Suppress warnings on variables that could be constants.}
5225 @cindex @option{-gnatwK} (@command{gcc})
5226 This switch disables warnings on variables that could be declared constants.
5227
5228 @item -gnatw.k
5229 @emph{Activate warnings on redefinition of names in standard.}
5230 @cindex @option{-gnatw.k} (@command{gcc})
5231 This switch activates warnings for declarations that declare a name that
5232 is defined in package Standard. Such declarations can be confusing,
5233 especially since the names in package Standard continue to be directly
5234 visible, meaning that use visibiliy on such redeclared names does not
5235 work as expected. Names of discriminants and components in records are
5236 not included in this check.
5237 This warning is not part of the warnings activated by @option{-gnatwa}.
5238 It must be explicitly activated.
5239
5240 @item -gnatw.K
5241 @emph{Suppress warnings on variables that could be constants.}
5242 @cindex @option{-gnatwK} (@command{gcc})
5243 This switch activates warnings for declarations that declare a name that
5244 is defined in package Standard.
5245
5246 @item -gnatwl
5247 @emph{Activate warnings for elaboration pragmas.}
5248 @cindex @option{-gnatwl} (@command{gcc})
5249 @cindex Elaboration, warnings
5250 This switch activates warnings on missing
5251 @code{Elaborate_All} and @code{Elaborate} pragmas.
5252 See the section in this guide on elaboration checking for details on
5253 when such pragmas should be used. In dynamic elaboration mode, this switch
5254 generations warnings about the need to add elaboration pragmas. Note however,
5255 that if you blindly follow these warnings, and add @code{Elaborate_All}
5256 warnings wherever they are recommended, you basically end up with the
5257 equivalent of the static elaboration model, which may not be what you want for
5258 legacy code for which the static model does not work.
5259
5260 For the static model, the messages generated are labeled "info:" (for
5261 information messages). They are not warnings to add elaboration pragmas,
5262 merely informational messages showing what implicit elaboration pragmas
5263 have been added, for use in analyzing elaboration circularity problems.
5264
5265 Warnings are also generated if you
5266 are using the static mode of elaboration, and a @code{pragma Elaborate}
5267 is encountered. The default is that such warnings
5268 are not generated.
5269 This warning is not automatically turned on by the use of @option{-gnatwa}.
5270
5271 @item -gnatwL
5272 @emph{Suppress warnings for elaboration pragmas.}
5273 @cindex @option{-gnatwL} (@command{gcc})
5274 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5275 See the section in this guide on elaboration checking for details on
5276 when such pragmas should be used.
5277
5278 @item -gnatw.l
5279 @emph{List inherited aspects.}
5280 @cindex @option{-gnatw.l} (@command{gcc})
5281 This switch causes the compiler to list inherited invariants,
5282 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
5283 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
5284 These messages are not automatically turned on by the use of @option{-gnatwa}.
5285
5286 @item -gnatw.L
5287 @emph{Suppress listing of inherited aspects.}
5288 @cindex @option{-gnatw.L} (@command{gcc})
5289 This switch suppresses listing of inherited aspects.
5290
5291 @item -gnatwm
5292 @emph{Activate warnings on modified but unreferenced variables.}
5293 @cindex @option{-gnatwm} (@command{gcc})
5294 This switch activates warnings for variables that are assigned (using
5295 an initialization value or with one or more assignment statements) but
5296 whose value is never read. The warning is suppressed for volatile
5297 variables and also for variables that are renamings of other variables
5298 or for which an address clause is given.
5299 This warning can also be turned on using @option{-gnatwa}.
5300 The default is that these warnings are not given.
5301
5302 @item -gnatwM
5303 @emph{Disable warnings on modified but unreferenced variables.}
5304 @cindex @option{-gnatwM} (@command{gcc})
5305 This switch disables warnings for variables that are assigned or
5306 initialized, but never read.
5307
5308 @item -gnatw.m
5309 @emph{Activate warnings on suspicious modulus values.}
5310 @cindex @option{-gnatw.m} (@command{gcc})
5311 This switch activates warnings for modulus values that seem suspicious.
5312 The cases caught are where the size is the same as the modulus (e.g.
5313 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5314 with no size clause. The guess in both cases is that 2**x was intended
5315 rather than x. In addition expressions of the form 2*x for small x
5316 generate a warning (the almost certainly accurate guess being that
5317 2**x was intended). The default is that these warnings are given.
5318
5319 @item -gnatw.M
5320 @emph{Disable warnings on suspicious modulus values.}
5321 @cindex @option{-gnatw.M} (@command{gcc})
5322 This switch disables warnings for suspicious modulus values.
5323
5324 @item -gnatwn
5325 @emph{Set normal warnings mode.}
5326 @cindex @option{-gnatwn} (@command{gcc})
5327 This switch sets normal warning mode, in which enabled warnings are
5328 issued and treated as warnings rather than errors. This is the default
5329 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5330 an explicit @option{-gnatws} or
5331 @option{-gnatwe}. It also cancels the effect of the
5332 implicit @option{-gnatwe} that is activated by the
5333 use of @option{-gnatg}.
5334
5335 @item -gnatwo
5336 @emph{Activate warnings on address clause overlays.}
5337 @cindex @option{-gnatwo} (@command{gcc})
5338 @cindex Address Clauses, warnings
5339 This switch activates warnings for possibly unintended initialization
5340 effects of defining address clauses that cause one variable to overlap
5341 another. The default is that such warnings are generated.
5342 This warning can also be turned on using @option{-gnatwa}.
5343
5344 @item -gnatwO
5345 @emph{Suppress warnings on address clause overlays.}
5346 @cindex @option{-gnatwO} (@command{gcc})
5347 This switch suppresses warnings on possibly unintended initialization
5348 effects of defining address clauses that cause one variable to overlap
5349 another.
5350
5351 @item -gnatw.o
5352 @emph{Activate warnings on modified but unreferenced out parameters.}
5353 @cindex @option{-gnatw.o} (@command{gcc})
5354 This switch activates warnings for variables that are modified by using
5355 them as actuals for a call to a procedure with an out mode formal, where
5356 the resulting assigned value is never read. It is applicable in the case
5357 where there is more than one out mode formal. If there is only one out
5358 mode formal, the warning is issued by default (controlled by -gnatwu).
5359 The warning is suppressed for volatile
5360 variables and also for variables that are renamings of other variables
5361 or for which an address clause is given.
5362 The default is that these warnings are not given. Note that this warning
5363 is not included in -gnatwa, it must be activated explicitly.
5364
5365 @item -gnatw.O
5366 @emph{Disable warnings on modified but unreferenced out parameters.}
5367 @cindex @option{-gnatw.O} (@command{gcc})
5368 This switch suppresses warnings for variables that are modified by using
5369 them as actuals for a call to a procedure with an out mode formal, where
5370 the resulting assigned value is never read.
5371
5372 @item -gnatwp
5373 @emph{Activate warnings on ineffective pragma Inlines.}
5374 @cindex @option{-gnatwp} (@command{gcc})
5375 @cindex Inlining, warnings
5376 This switch activates warnings for failure of front end inlining
5377 (activated by @option{-gnatN}) to inline a particular call. There are
5378 many reasons for not being able to inline a call, including most
5379 commonly that the call is too complex to inline. The default is
5380 that such warnings are not given.
5381 This warning can also be turned on using @option{-gnatwa}.
5382 Warnings on ineffective inlining by the gcc back-end can be activated
5383 separately, using the gcc switch -Winline.
5384
5385 @item -gnatwP
5386 @emph{Suppress warnings on ineffective pragma Inlines.}
5387 @cindex @option{-gnatwP} (@command{gcc})
5388 This switch suppresses warnings on ineffective pragma Inlines. If the
5389 inlining mechanism cannot inline a call, it will simply ignore the
5390 request silently.
5391
5392 @item -gnatw.p
5393 @emph{Activate warnings on parameter ordering.}
5394 @cindex @option{-gnatw.p} (@command{gcc})
5395 @cindex Parameter order, warnings
5396 This switch activates warnings for cases of suspicious parameter
5397 ordering when the list of arguments are all simple identifiers that
5398 match the names of the formals, but are in a different order. The
5399 warning is suppressed if any use of named parameter notation is used,
5400 so this is the appropriate way to suppress a false positive (and
5401 serves to emphasize that the "misordering" is deliberate). The
5402 default is
5403 that such warnings are not given.
5404 This warning can also be turned on using @option{-gnatwa}.
5405
5406 @item -gnatw.P
5407 @emph{Suppress warnings on parameter ordering.}
5408 @cindex @option{-gnatw.P} (@command{gcc})
5409 This switch suppresses warnings on cases of suspicious parameter
5410 ordering.
5411
5412 @item -gnatwq
5413 @emph{Activate warnings on questionable missing parentheses.}
5414 @cindex @option{-gnatwq} (@command{gcc})
5415 @cindex Parentheses, warnings
5416 This switch activates warnings for cases where parentheses are not used and
5417 the result is potential ambiguity from a readers point of view. For example
5418 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5419 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5420 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5421 follow the rule of always parenthesizing to make the association clear, and
5422 this warning switch warns if such parentheses are not present. The default
5423 is that these warnings are given.
5424 This warning can also be turned on using @option{-gnatwa}.
5425
5426 @item -gnatwQ
5427 @emph{Suppress warnings on questionable missing parentheses.}
5428 @cindex @option{-gnatwQ} (@command{gcc})
5429 This switch suppresses warnings for cases where the association is not
5430 clear and the use of parentheses is preferred.
5431
5432 @item -gnatwr
5433 @emph{Activate warnings on redundant constructs.}
5434 @cindex @option{-gnatwr} (@command{gcc})
5435 This switch activates warnings for redundant constructs. The following
5436 is the current list of constructs regarded as redundant:
5437
5438 @itemize @bullet
5439 @item
5440 Assignment of an item to itself.
5441 @item
5442 Type conversion that converts an expression to its own type.
5443 @item
5444 Use of the attribute @code{Base} where @code{typ'Base} is the same
5445 as @code{typ}.
5446 @item
5447 Use of pragma @code{Pack} when all components are placed by a record
5448 representation clause.
5449 @item
5450 Exception handler containing only a reraise statement (raise with no
5451 operand) which has no effect.
5452 @item
5453 Use of the operator abs on an operand that is known at compile time
5454 to be non-negative
5455 @item
5456 Comparison of boolean expressions to an explicit True value.
5457 @end itemize
5458
5459 This warning can also be turned on using @option{-gnatwa}.
5460 The default is that warnings for redundant constructs are not given.
5461
5462 @item -gnatwR
5463 @emph{Suppress warnings on redundant constructs.}
5464 @cindex @option{-gnatwR} (@command{gcc})
5465 This switch suppresses warnings for redundant constructs.
5466
5467 @item -gnatw.r
5468 @emph{Activate warnings for object renaming function.}
5469 @cindex @option{-gnatw.r} (@command{gcc})
5470 This switch activates warnings for an object renaming that renames a
5471 function call, which is equivalent to a constant declaration (as
5472 opposed to renaming the function itself).  The default is that these
5473 warnings are given.  This warning can also be turned on using
5474 @option{-gnatwa}.
5475
5476 @item -gnatw.R
5477 @emph{Suppress warnings for object renaming function.}
5478 @cindex @option{-gnatwT} (@command{gcc})
5479 This switch suppresses warnings for object renaming function.
5480
5481 @item -gnatws
5482 @emph{Suppress all warnings.}
5483 @cindex @option{-gnatws} (@command{gcc})
5484 This switch completely suppresses the
5485 output of all warning messages from the GNAT front end, including
5486 both warnings that can be controlled by switches described in this
5487 section, and those that are normally given unconditionally. The
5488 effect of this suppress action can only be cancelled by a subsequent
5489 use of the switch @option{-gnatwn}.
5490
5491 Note that switch @option{-gnatws} does not suppress
5492 warnings from the @command{gcc} back end.
5493 To suppress these back end warnings as well, use the switch @option{-w}
5494 in addition to @option{-gnatws}. Also this switch has no effect on the
5495 handling of style check messages.
5496
5497 @item -gnatw.s
5498 @emph{Activate warnings on overridden size clauses.}
5499 @cindex @option{-gnatw.s} (@command{gcc})
5500 @cindex Record Representation (component sizes)
5501 This switch activates warnings on component clauses in record
5502 representation clauses where the length given overrides that
5503 specified by an explicit size clause for the component type. A
5504 warning is similarly given in the array case if a specified
5505 component size overrides an explicit size clause for the array
5506 component type.
5507 Note that @option{-gnatwa} does not affect the setting of this warning option.
5508
5509 @item -gnatw.S
5510 @emph{Suppress warnings on overridden size clauses.}
5511 @cindex @option{-gnatw.S} (@command{gcc})
5512 This switch suppresses warnings on component clauses in record
5513 representation clauses that override size clauses, and similar
5514 warnings when an array component size overrides a size clause.
5515
5516 @item -gnatwt
5517 @emph{Activate warnings for tracking of deleted conditional code.}
5518 @cindex @option{-gnatwt} (@command{gcc})
5519 @cindex Deactivated code, warnings
5520 @cindex Deleted code, warnings
5521 This switch activates warnings for tracking of code in conditionals (IF and
5522 CASE statements) that is detected to be dead code which cannot be executed, and
5523 which is removed by the front end. This warning is off by default, and is not
5524 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5525 useful for detecting deactivated code in certified applications.
5526
5527 @item -gnatwT
5528 @emph{Suppress warnings for tracking of deleted conditional code.}
5529 @cindex @option{-gnatwT} (@command{gcc})
5530 This switch suppresses warnings for tracking of deleted conditional code.
5531
5532 @item -gnatw.t
5533 @emph{Activate warnings on suspicious contracts.}
5534 @cindex @option{-gnatw.t} (@command{gcc})
5535 This switch activates warnings on suspicious postconditions (whether a
5536 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012)
5537 and suspicious contract cases (pragma @code{Contract_Cases}). A
5538 function postcondition or contract case is suspicious when no postcondition
5539 or contract case for this function mentions the result of the function.
5540 A procedure postcondition or contract case is suspicious when it only
5541 refers to the pre-state of the procedure, because in that case it should
5542 rather be expressed as a precondition. The default is that such warnings
5543 are not generated. This warning can also be turned on using @option{-gnatwa}.
5544
5545 @item -gnatw.T
5546 @emph{Suppress warnings on suspicious contracts.}
5547 @cindex @option{-gnatw.T} (@command{gcc})
5548 This switch suppresses warnings on suspicious postconditions.
5549
5550 @item -gnatwu
5551 @emph{Activate warnings on unused entities.}
5552 @cindex @option{-gnatwu} (@command{gcc})
5553 This switch activates warnings to be generated for entities that
5554 are declared but not referenced, and for units that are @code{with}'ed
5555 and not
5556 referenced. In the case of packages, a warning is also generated if
5557 no entities in the package are referenced. This means that if a with'ed
5558 package is referenced but the only references are in @code{use}
5559 clauses or @code{renames}
5560 declarations, a warning is still generated. A warning is also generated
5561 for a generic package that is @code{with}'ed but never instantiated.
5562 In the case where a package or subprogram body is compiled, and there
5563 is a @code{with} on the corresponding spec
5564 that is only referenced in the body,
5565 a warning is also generated, noting that the
5566 @code{with} can be moved to the body. The default is that
5567 such warnings are not generated.
5568 This switch also activates warnings on unreferenced formals
5569 (it includes the effect of @option{-gnatwf}).
5570 This warning can also be turned on using @option{-gnatwa}.
5571
5572 @item -gnatwU
5573 @emph{Suppress warnings on unused entities.}
5574 @cindex @option{-gnatwU} (@command{gcc})
5575 This switch suppresses warnings for unused entities and packages.
5576 It also turns off warnings on unreferenced formals (and thus includes
5577 the effect of @option{-gnatwF}).
5578
5579 @item -gnatw.u
5580 @emph{Activate warnings on unordered enumeration types.}
5581 @cindex @option{-gnatw.u} (@command{gcc})
5582 This switch causes enumeration types to be considered as conceptually
5583 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5584 The effect is to generate warnings in clients that use explicit comparisons
5585 or subranges, since these constructs both treat objects of the type as
5586 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5587 which the type is declared, or its body or subunits.) Please refer to
5588 the description of pragma @code{Ordered} in the
5589 @cite{@value{EDITION} Reference Manual} for further details.
5590 The default is that such warnings are not generated.
5591 This warning is not automatically turned on by the use of @option{-gnatwa}.
5592
5593 @item -gnatw.U
5594 @emph{Deactivate warnings on unordered enumeration types.}
5595 @cindex @option{-gnatw.U} (@command{gcc})
5596 This switch causes all enumeration types to be considered as ordered, so
5597 that no warnings are given for comparisons or subranges for any type.
5598
5599 @item -gnatwv
5600 @emph{Activate warnings on unassigned variables.}
5601 @cindex @option{-gnatwv} (@command{gcc})
5602 @cindex Unassigned variable warnings
5603 This switch activates warnings for access to variables which
5604 may not be properly initialized. The default is that
5605 such warnings are generated.
5606 This warning can also be turned on using @option{-gnatwa}.
5607
5608 @item -gnatwV
5609 @emph{Suppress warnings on unassigned variables.}
5610 @cindex @option{-gnatwV} (@command{gcc})
5611 This switch suppresses warnings for access to variables which
5612 may not be properly initialized.
5613 For variables of a composite type, the warning can also be suppressed in
5614 Ada 2005 by using a default initialization with a box. For example, if
5615 Table is an array of records whose components are only partially uninitialized,
5616 then the following code:
5617
5618 @smallexample @c ada
5619    Tab : Table := (others => <>);
5620 @end smallexample
5621
5622 will suppress warnings on subsequent statements that access components
5623 of variable Tab.
5624
5625 @item -gnatw.v
5626 @emph{Activate info messages for non-default bit order.}
5627 @cindex @option{-gnatw.v} (@command{gcc})
5628 @cindex bit order warnings
5629 This switch activates messages (labeled "info", they are not warnings,
5630 just informational messages) about the effects of non-default bit-order
5631 on records to which a component clause is applied. The effect of specifying
5632 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
5633 these messages, which are given by default, are useful in understanding the
5634 exact consequences of using this feature. These messages
5635 can also be turned on using @option{-gnatwa}
5636
5637 @item -gnatw.V
5638 @emph{Suppress info messages for non-default bit order.}
5639 @cindex @option{-gnatw.V} (@command{gcc})
5640 This switch suppresses information messages for the effects of specifying
5641 non-default bit order on record components with component clauses.
5642
5643 @item -gnatww
5644 @emph{Activate warnings on wrong low bound assumption.}
5645 @cindex @option{-gnatww} (@command{gcc})
5646 @cindex String indexing warnings
5647 This switch activates warnings for indexing an unconstrained string parameter
5648 with a literal or S'Length. This is a case where the code is assuming that the
5649 low bound is one, which is in general not true (for example when a slice is
5650 passed). The default is that such warnings are generated.
5651 This warning can also be turned on using @option{-gnatwa}.
5652
5653 @item -gnatwW
5654 @emph{Suppress warnings on wrong low bound assumption.}
5655 @cindex @option{-gnatwW} (@command{gcc})
5656 This switch suppresses warnings for indexing an unconstrained string parameter
5657 with a literal or S'Length. Note that this warning can also be suppressed
5658 in a particular case by adding an
5659 assertion that the lower bound is 1,
5660 as shown in the following example.
5661
5662 @smallexample @c ada
5663    procedure K (S : String) is
5664       pragma Assert (S'First = 1);
5665       @dots{}
5666 @end smallexample
5667
5668 @item -gnatw.w
5669 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5670 @cindex @option{-gnatw.w} (@command{gcc})
5671 @cindex Warnings Off control
5672 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5673 where either the pragma is entirely useless (because it suppresses no
5674 warnings), or it could be replaced by @code{pragma Unreferenced} or
5675 @code{pragma Unmodified}. The default is that these warnings are not given.
5676 Note that this warning is not included in -gnatwa, it must be
5677 activated explicitly.
5678
5679 @item -gnatw.W
5680 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5681 @cindex @option{-gnatw.W} (@command{gcc})
5682 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity)}.
5683
5684 @item -gnatwx
5685 @emph{Activate warnings on Export/Import pragmas.}
5686 @cindex @option{-gnatwx} (@command{gcc})
5687 @cindex Export/Import pragma warnings
5688 This switch activates warnings on Export/Import pragmas when
5689 the compiler detects a possible conflict between the Ada and
5690 foreign language calling sequences. For example, the use of
5691 default parameters in a convention C procedure is dubious
5692 because the C compiler cannot supply the proper default, so
5693 a warning is issued. The default is that such warnings are
5694 generated.
5695 This warning can also be turned on using @option{-gnatwa}.
5696
5697 @item -gnatwX
5698 @emph{Suppress warnings on Export/Import pragmas.}
5699 @cindex @option{-gnatwX} (@command{gcc})
5700 This switch suppresses warnings on Export/Import pragmas.
5701 The sense of this is that you are telling the compiler that
5702 you know what you are doing in writing the pragma, and it
5703 should not complain at you.
5704
5705 @item -gnatw.x
5706 @emph{Activate warnings for No_Exception_Propagation mode.}
5707 @cindex @option{-gnatwm} (@command{gcc})
5708 This switch activates warnings for exception usage when pragma Restrictions
5709 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5710 explicit exception raises which are not covered by a local handler, and for
5711 exception handlers which do not cover a local raise. The default is that these
5712 warnings are not given.
5713
5714 @item -gnatw.X
5715 @emph{Disable warnings for No_Exception_Propagation mode.}
5716 This switch disables warnings for exception usage when pragma Restrictions
5717 (No_Exception_Propagation) is in effect.
5718
5719 @item -gnatwy
5720 @emph{Activate warnings for Ada compatibility issues.}
5721 @cindex @option{-gnatwy} (@command{gcc})
5722 @cindex Ada compatibility issues warnings
5723 For the most part, newer versions of Ada are upwards compatible
5724 with older versions. For example, Ada 2005 programs will almost
5725 always work when compiled as Ada 2012.
5726 However there are some exceptions (for example the fact that
5727 @code{some} is now a reserved word in Ada 2012). This
5728 switch activates several warnings to help in identifying
5729 and correcting such incompatibilities. The default is that
5730 these warnings are generated. Note that at one point Ada 2005
5731 was called Ada 0Y, hence the choice of character.
5732 This warning can also be turned on using @option{-gnatwa}.
5733
5734 @item -gnatwY
5735 @emph{Disable warnings for Ada compatibility issues.}
5736 @cindex @option{-gnatwY} (@command{gcc})
5737 @cindex Ada compatibility issues warnings
5738 This switch suppresses the warnings intended to help in identifying
5739 incompatibilities between Ada language versions.
5740
5741 @item -gnatw.y
5742 @emph{Activate information messages for why package spec needs body}
5743 @cindex @option{-gnatw.y} (@command{gcc})
5744 @cindex Package spec needing body
5745 There are a number of cases in which a package spec needs a body.
5746 For example, the use of pragma Elaborate_Body, or the declaration
5747 of a procedure specification requiring a completion. This switch
5748 causes information messages to be output showing why a package
5749 specification requires a body. This can be useful in the case of
5750 a large package specification which is unexpectedly requiring a
5751 body. The default is that such information messages are not output.
5752
5753 @item -gnatw.Y
5754 @emph{Disable information messages for why package spec needs body}
5755 @cindex @option{-gnatw.Y} (@command{gcc})
5756 @cindex No information messages for why package spec needs body
5757 This switch suppresses the output of information messages showing why
5758 a package specification needs a body.
5759
5760 @item -gnatwz
5761 @emph{Activate warnings on unchecked conversions.}
5762 @cindex @option{-gnatwz} (@command{gcc})
5763 @cindex Unchecked_Conversion warnings
5764 This switch activates warnings for unchecked conversions
5765 where the types are known at compile time to have different
5766 sizes. The default
5767 is that such warnings are generated. Warnings are also
5768 generated for subprogram pointers with different conventions,
5769 and, on VMS only, for data pointers with different conventions.
5770 This warning can also be turned on using @option{-gnatwa}.
5771
5772 @item -gnatwZ
5773 @emph{Suppress warnings on unchecked conversions.}
5774 @cindex @option{-gnatwZ} (@command{gcc})
5775 This switch suppresses warnings for unchecked conversions
5776 where the types are known at compile time to have different
5777 sizes or conventions.
5778
5779 @item ^-Wunused^WARNINGS=UNUSED^
5780 @cindex @option{-Wunused}
5781 The warnings controlled by the @option{-gnatw} switch are generated by
5782 the front end of the compiler. The @option{GCC} back end can provide
5783 additional warnings and they are controlled by the @option{-W} switch.
5784 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5785 warnings for entities that are declared but not referenced.
5786
5787 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5788 @cindex @option{-Wuninitialized}
5789 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5790 the back end warning for uninitialized variables. This switch must be
5791 used in conjunction with an optimization level greater than zero.
5792
5793 @item -Wstack-usage=@var{len}
5794 @cindex @option{-Wstack-usage}
5795 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5796 See @ref{Static Stack Usage Analysis} for details.
5797
5798 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5799 @cindex @option{-Wall}
5800 This switch enables most warnings from the @option{GCC} back end.
5801 The code generator detects a number of warning situations that are missed
5802 by the @option{GNAT} front end, and this switch can be used to activate them.
5803 The use of this switch also sets the default front end warning mode to
5804 @option{-gnatwa}, that is, most front end warnings activated as well.
5805
5806 @item ^-w^/NO_BACK_END_WARNINGS^
5807 @cindex @option{-w}
5808 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5809 The use of this switch also sets the default front end warning mode to
5810 @option{-gnatws}, that is, front end warnings suppressed as well.
5811
5812 @end table
5813
5814 @noindent
5815 @ifclear vms
5816 A string of warning parameters can be used in the same parameter. For example:
5817
5818 @smallexample
5819 -gnatwaGe
5820 @end smallexample
5821
5822 @noindent
5823 will turn on all optional warnings except for unrecognized pragma warnings,
5824 and also specify that warnings should be treated as errors.
5825 @end ifclear
5826
5827 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5828
5829 @table @option
5830 @c !sort!
5831 @item -gnatw.a
5832 @item -gnatwB
5833 @item -gnatw.b
5834 @item -gnatwC
5835 @item -gnatw.C
5836 @item -gnatwD
5837 @item -gnatwF
5838 @item -gnatwg
5839 @item -gnatwH
5840 @item -gnatwi
5841 @item -gnatw.I
5842 @item -gnatwJ
5843 @item -gnatwK
5844 @item -gnatwL
5845 @item -gnatw.L
5846 @item -gnatwM
5847 @item -gnatw.m
5848 @item -gnatwn
5849 @item -gnatwo
5850 @item -gnatw.O
5851 @item -gnatwP
5852 @item -gnatw.P
5853 @item -gnatwq
5854 @item -gnatwR
5855 @item -gnatw.R
5856 @item -gnatw.S
5857 @item -gnatwT
5858 @item -gnatw.T
5859 @item -gnatwU
5860 @item -gnatwv
5861 @item -gnatww
5862 @item -gnatw.W
5863 @item -gnatwx
5864 @item -gnatw.X
5865 @item -gnatwy
5866 @item -gnatwz
5867
5868 @end table
5869
5870 @node Debugging and Assertion Control
5871 @subsection Debugging and Assertion Control
5872
5873 @table @option
5874 @item -gnata
5875 @cindex @option{-gnata} (@command{gcc})
5876 @findex Assert
5877 @findex Debug
5878 @cindex Assertions
5879
5880 @noindent
5881 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5882 are ignored. This switch, where @samp{a} stands for assert, causes
5883 @code{Assert} and @code{Debug} pragmas to be activated.
5884
5885 The pragmas have the form:
5886
5887 @smallexample
5888 @cartouche
5889    @b{pragma} Assert (@var{Boolean-expression} @r{[},
5890                       @var{static-string-expression}@r{]})
5891    @b{pragma} Debug (@var{procedure call})
5892 @end cartouche
5893 @end smallexample
5894
5895 @noindent
5896 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5897 If the result is @code{True}, the pragma has no effect (other than
5898 possible side effects from evaluating the expression). If the result is
5899 @code{False}, the exception @code{Assert_Failure} declared in the package
5900 @code{System.Assertions} is
5901 raised (passing @var{static-string-expression}, if present, as the
5902 message associated with the exception). If no string expression is
5903 given the default is a string giving the file name and line number
5904 of the pragma.
5905
5906 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5907 @code{pragma Debug} may appear within a declaration sequence, allowing
5908 debugging procedures to be called between declarations.
5909
5910 @ifset vms
5911 @item /DEBUG@r{[}=debug-level@r{]}
5912 @itemx  /NODEBUG
5913 Specifies how much debugging information is to be included in
5914 the resulting object file where 'debug-level' is one of the following:
5915 @table @code
5916 @item   TRACEBACK
5917 Include both debugger symbol records and traceback
5918 the object file.
5919 This is the default setting.
5920 @item   ALL
5921 Include both debugger symbol records and traceback in
5922 object file.
5923 @item   NONE
5924 Excludes both debugger symbol records and traceback
5925 the object file. Same as /NODEBUG.
5926 @item   SYMBOLS
5927 Includes only debugger symbol records in the object
5928 file. Note that this doesn't include traceback information.
5929 @end table
5930 @end ifset
5931 @end table
5932
5933 @node Validity Checking
5934 @subsection Validity Checking
5935 @findex Validity Checking
5936
5937 @noindent
5938 The Ada Reference Manual defines the concept of invalid values (see
5939 RM 13.9.1). The primary source of invalid values is uninitialized
5940 variables. A scalar variable that is left uninitialized may contain
5941 an invalid value; the concept of invalid does not apply to access or
5942 composite types.
5943
5944 It is an error to read an invalid value, but the RM does not require
5945 run-time checks to detect such errors, except for some minimal
5946 checking to prevent erroneous execution (i.e. unpredictable
5947 behavior). This corresponds to the @option{-gnatVd} switch below,
5948 which is the default. For example, by default, if the expression of a
5949 case statement is invalid, it will raise Constraint_Error rather than
5950 causing a wild jump, and if an array index on the left-hand side of an
5951 assignment is invalid, it will raise Constraint_Error rather than
5952 overwriting an arbitrary memory location.
5953
5954 The @option{-gnatVa} may be used to enable additional validity checks,
5955 which are not required by the RM. These checks are often very
5956 expensive (which is why the RM does not require them). These checks
5957 are useful in tracking down uninitialized variables, but they are
5958 not usually recommended for production builds.
5959
5960 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5961 control; you can enable whichever validity checks you desire. However,
5962 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5963 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5964 sufficient for non-debugging use.
5965
5966 The @option{-gnatB} switch tells the compiler to assume that all
5967 values are valid (that is, within their declared subtype range)
5968 except in the context of a use of the Valid attribute. This means
5969 the compiler can generate more efficient code, since the range
5970 of values is better known at compile time. However, an uninitialized
5971 variable can cause wild jumps and memory corruption in this mode.
5972
5973 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5974 checking mode as described below.
5975 @ifclear vms
5976 The @code{x} argument is a string of letters that
5977 indicate validity checks that are performed or not performed in addition
5978 to the default checks required by Ada as described above.
5979 @end ifclear
5980 @ifset vms
5981 The options allowed for this qualifier
5982 indicate validity checks that are performed or not performed in addition
5983 to the default checks required by Ada as described above.
5984 @end ifset
5985
5986 @table @option
5987 @c !sort!
5988 @item -gnatVa
5989 @emph{All validity checks.}
5990 @cindex @option{-gnatVa} (@command{gcc})
5991 All validity checks are turned on.
5992 @ifclear vms
5993 That is, @option{-gnatVa} is
5994 equivalent to @option{gnatVcdfimorst}.
5995 @end ifclear
5996
5997 @item -gnatVc
5998 @emph{Validity checks for copies.}
5999 @cindex @option{-gnatVc} (@command{gcc})
6000 The right hand side of assignments, and the initializing values of
6001 object declarations are validity checked.
6002
6003 @item -gnatVd
6004 @emph{Default (RM) validity checks.}
6005 @cindex @option{-gnatVd} (@command{gcc})
6006 Some validity checks are done by default following normal Ada semantics
6007 (RM 13.9.1 (9-11)).
6008 A check is done in case statements that the expression is within the range
6009 of the subtype. If it is not, Constraint_Error is raised.
6010 For assignments to array components, a check is done that the expression used
6011 as index is within the range. If it is not, Constraint_Error is raised.
6012 Both these validity checks may be turned off using switch @option{-gnatVD}.
6013 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6014 switch @option{-gnatVd} will leave the checks turned on.
6015 Switch @option{-gnatVD} should be used only if you are sure that all such
6016 expressions have valid values. If you use this switch and invalid values
6017 are present, then the program is erroneous, and wild jumps or memory
6018 overwriting may occur.
6019
6020 @item -gnatVe
6021 @emph{Validity checks for elementary components.}
6022 @cindex @option{-gnatVe} (@command{gcc})
6023 In the absence of this switch, assignments to record or array components are
6024 not validity checked, even if validity checks for assignments generally
6025 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6026 require valid data, but assignment of individual components does. So for
6027 example, there is a difference between copying the elements of an array with a
6028 slice assignment, compared to assigning element by element in a loop. This
6029 switch allows you to turn off validity checking for components, even when they
6030 are assigned component by component.
6031
6032 @item -gnatVf
6033 @emph{Validity checks for floating-point values.}
6034 @cindex @option{-gnatVf} (@command{gcc})
6035 In the absence of this switch, validity checking occurs only for discrete
6036 values. If @option{-gnatVf} is specified, then validity checking also applies
6037 for floating-point values, and NaNs and infinities are considered invalid,
6038 as well as out of range values for constrained types. Note that this means
6039 that standard IEEE infinity mode is not allowed. The exact contexts
6040 in which floating-point values are checked depends on the setting of other
6041 options. For example,
6042 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6043 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6044 (the order does not matter) specifies that floating-point parameters of mode
6045 @code{in} should be validity checked.
6046
6047 @item -gnatVi
6048 @emph{Validity checks for @code{in} mode parameters}
6049 @cindex @option{-gnatVi} (@command{gcc})
6050 Arguments for parameters of mode @code{in} are validity checked in function
6051 and procedure calls at the point of call.
6052
6053 @item -gnatVm
6054 @emph{Validity checks for @code{in out} mode parameters.}
6055 @cindex @option{-gnatVm} (@command{gcc})
6056 Arguments for parameters of mode @code{in out} are validity checked in
6057 procedure calls at the point of call. The @code{'m'} here stands for
6058 modify, since this concerns parameters that can be modified by the call.
6059 Note that there is no specific option to test @code{out} parameters,
6060 but any reference within the subprogram will be tested in the usual
6061 manner, and if an invalid value is copied back, any reference to it
6062 will be subject to validity checking.
6063
6064 @item -gnatVn
6065 @emph{No validity checks.}
6066 @cindex @option{-gnatVn} (@command{gcc})
6067 This switch turns off all validity checking, including the default checking
6068 for case statements and left hand side subscripts. Note that the use of
6069 the switch @option{-gnatp} suppresses all run-time checks, including
6070 validity checks, and thus implies @option{-gnatVn}. When this switch
6071 is used, it cancels any other @option{-gnatV} previously issued.
6072
6073 @item -gnatVo
6074 @emph{Validity checks for operator and attribute operands.}
6075 @cindex @option{-gnatVo} (@command{gcc})
6076 Arguments for predefined operators and attributes are validity checked.
6077 This includes all operators in package @code{Standard},
6078 the shift operators defined as intrinsic in package @code{Interfaces}
6079 and operands for attributes such as @code{Pos}. Checks are also made
6080 on individual component values for composite comparisons, and on the
6081 expressions in type conversions and qualified expressions. Checks are
6082 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6083
6084 @item -gnatVp
6085 @emph{Validity checks for parameters.}
6086 @cindex @option{-gnatVp} (@command{gcc})
6087 This controls the treatment of parameters within a subprogram (as opposed
6088 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6089 of parameters on a call. If either of these call options is used, then
6090 normally an assumption is made within a subprogram that the input arguments
6091 have been validity checking at the point of call, and do not need checking
6092 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6093 is not made, and parameters are not assumed to be valid, so their validity
6094 will be checked (or rechecked) within the subprogram.
6095
6096 @item -gnatVr
6097 @emph{Validity checks for function returns.}
6098 @cindex @option{-gnatVr} (@command{gcc})
6099 The expression in @code{return} statements in functions is validity
6100 checked.
6101
6102 @item -gnatVs
6103 @emph{Validity checks for subscripts.}
6104 @cindex @option{-gnatVs} (@command{gcc})
6105 All subscripts expressions are checked for validity, whether they appear
6106 on the right side or left side (in default mode only left side subscripts
6107 are validity checked).
6108
6109 @item -gnatVt
6110 @emph{Validity checks for tests.}
6111 @cindex @option{-gnatVt} (@command{gcc})
6112 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6113 statements are checked, as well as guard expressions in entry calls.
6114
6115 @end table
6116
6117 @noindent
6118 The @option{-gnatV} switch may be followed by
6119 ^a string of letters^a list of options^
6120 to turn on a series of validity checking options.
6121 For example,
6122 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6123 specifies that in addition to the default validity checking, copies and
6124 function return expressions are to be validity checked.
6125 In order to make it easier
6126 to specify the desired combination of effects,
6127 @ifclear vms
6128 the upper case letters @code{CDFIMORST} may
6129 be used to turn off the corresponding lower case option.
6130 @end ifclear
6131 @ifset vms
6132 the prefix @code{NO} on an option turns off the corresponding validity
6133 checking:
6134 @itemize @bullet
6135 @item @code{NOCOPIES}
6136 @item @code{NODEFAULT}
6137 @item @code{NOFLOATS}
6138 @item @code{NOIN_PARAMS}
6139 @item @code{NOMOD_PARAMS}
6140 @item @code{NOOPERANDS}
6141 @item @code{NORETURNS}
6142 @item @code{NOSUBSCRIPTS}
6143 @item @code{NOTESTS}
6144 @end itemize
6145 @end ifset
6146 Thus
6147 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6148 turns on all validity checking options except for
6149 checking of @code{@b{in out}} procedure arguments.
6150
6151 The specification of additional validity checking generates extra code (and
6152 in the case of @option{-gnatVa} the code expansion can be substantial).
6153 However, these additional checks can be very useful in detecting
6154 uninitialized variables, incorrect use of unchecked conversion, and other
6155 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6156 is useful in conjunction with the extra validity checking, since this
6157 ensures that wherever possible uninitialized variables have invalid values.
6158
6159 See also the pragma @code{Validity_Checks} which allows modification of
6160 the validity checking mode at the program source level, and also allows for
6161 temporary disabling of validity checks.
6162
6163 @node Style Checking
6164 @subsection Style Checking
6165 @findex Style checking
6166
6167 @noindent
6168 The @option{-gnaty^x^(option,option,@dots{})^} switch
6169 @cindex @option{-gnaty} (@command{gcc})
6170 causes the compiler to
6171 enforce specified style rules. A limited set of style rules has been used
6172 in writing the GNAT sources themselves. This switch allows user programs
6173 to activate all or some of these checks. If the source program fails a
6174 specified style check, an appropriate message is given, preceded by
6175 the character sequence ``(style)''. This message does not prevent
6176 successful compilation (unless the @option{-gnatwe} switch is used).
6177
6178 Note that this is by no means intended to be a general facility for
6179 checking arbitrary coding standards. It is simply an embedding of the
6180 style rules we have chosen for the GNAT sources. If you are starting
6181 a project which does not have established style standards, you may
6182 find it useful to adopt the entire set of GNAT coding standards, or
6183 some subset of them. If you already have an established set of coding
6184 standards, then it may be that selected style checking options do
6185 indeed correspond to choices you have made, but for general checking
6186 of an existing set of coding rules, you should look to the gnatcheck
6187 tool, which is designed for that purpose.
6188
6189 @ifset vms
6190 @code{(option,option,@dots{})} is a sequence of keywords
6191 @end ifset
6192 @ifclear vms
6193 The string @var{x} is a sequence of letters or digits
6194 @end ifclear
6195 indicating the particular style
6196 checks to be performed. The following checks are defined:
6197
6198 @table @option
6199 @c !sort!
6200 @item 0-9
6201 @emph{Specify indentation level.}
6202 If a digit from 1-9 appears
6203 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6204 then proper indentation is checked, with the digit indicating the
6205 indentation level required. A value of zero turns off this style check.
6206 The general style of required indentation is as specified by
6207 the examples in the Ada Reference Manual. Full line comments must be
6208 aligned with the @code{--} starting on a column that is a multiple of
6209 the alignment level, or they may be aligned the same way as the following
6210 non-blank line (this is useful when full line comments appear in the middle
6211 of a statement, or they may be aligned with the source line on the previous
6212 non-blank line.
6213
6214 @item ^a^ATTRIBUTE^
6215 @emph{Check attribute casing.}
6216 Attribute names, including the case of keywords such as @code{digits}
6217 used as attributes names, must be written in mixed case, that is, the
6218 initial letter and any letter following an underscore must be uppercase.
6219 All other letters must be lowercase.
6220
6221 @item ^A^ARRAY_INDEXES^
6222 @emph{Use of array index numbers in array attributes.}
6223 When using the array attributes First, Last, Range,
6224 or Length, the index number must be omitted for one-dimensional arrays
6225 and is required for multi-dimensional arrays.
6226
6227 @item ^b^BLANKS^
6228 @emph{Blanks not allowed at statement end.}
6229 Trailing blanks are not allowed at the end of statements. The purpose of this
6230 rule, together with h (no horizontal tabs), is to enforce a canonical format
6231 for the use of blanks to separate source tokens.
6232
6233 @item ^B^BOOLEAN_OPERATORS^
6234 @emph{Check Boolean operators.}
6235 The use of AND/OR operators is not permitted except in the cases of modular
6236 operands, array operands, and simple stand-alone boolean variables or
6237 boolean constants. In all other cases @code{and then}/@code{or else} are
6238 required.
6239
6240 @item ^c^COMMENTS^
6241 @emph{Check comments, double space.}
6242 Comments must meet the following set of rules:
6243
6244 @itemize @bullet
6245
6246 @item
6247 The ``@code{--}'' that starts the column must either start in column one,
6248 or else at least one blank must precede this sequence.
6249
6250 @item
6251 Comments that follow other tokens on a line must have at least one blank
6252 following the ``@code{--}'' at the start of the comment.
6253
6254 @item
6255 Full line comments must have at least two blanks following the
6256 ``@code{--}'' that starts the comment, with the following exceptions.
6257
6258 @item
6259 A line consisting only of the ``@code{--}'' characters, possibly preceded
6260 by blanks is permitted.
6261
6262 @item
6263 A comment starting with ``@code{--x}'' where @code{x} is a special character
6264 is permitted.
6265 This allows proper processing of the output generated by specialized tools
6266 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6267 annotation
6268 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6269 special character is defined as being in one of the ASCII ranges
6270 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6271 Note that this usage is not permitted
6272 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6273
6274 @item
6275 A line consisting entirely of minus signs, possibly preceded by blanks, is
6276 permitted. This allows the construction of box comments where lines of minus
6277 signs are used to form the top and bottom of the box.
6278
6279 @item
6280 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6281 least one blank follows the initial ``@code{--}''. Together with the preceding
6282 rule, this allows the construction of box comments, as shown in the following
6283 example:
6284 @smallexample
6285 ---------------------------
6286 -- This is a box comment --
6287 -- with two text lines.  --
6288 ---------------------------
6289 @end smallexample
6290 @end itemize
6291
6292 @item ^C^COMMENTS1^
6293 @emph{Check comments, single space.}
6294 This is identical to @code{^c^COMMENTS^} except that only one space
6295 is required following the @code{--} of a comment instead of two.
6296
6297 @item ^d^DOS_LINE_ENDINGS^
6298 @emph{Check no DOS line terminators present.}
6299 All lines must be terminated by a single ASCII.LF
6300 character (in particular the DOS line terminator sequence CR/LF is not
6301 allowed).
6302
6303 @item ^e^END^
6304 @emph{Check end/exit labels.}
6305 Optional labels on @code{end} statements ending subprograms and on
6306 @code{exit} statements exiting named loops, are required to be present.
6307
6308 @item ^f^VTABS^
6309 @emph{No form feeds or vertical tabs.}
6310 Neither form feeds nor vertical tab characters are permitted
6311 in the source text.
6312
6313 @item ^g^GNAT^
6314 @emph{GNAT style mode.}
6315 The set of style check switches is set to match that used by the GNAT sources.
6316 This may be useful when developing code that is eventually intended to be
6317 incorporated into GNAT. For further details, see GNAT sources.
6318
6319 @item ^h^HTABS^
6320 @emph{No horizontal tabs.}
6321 Horizontal tab characters are not permitted in the source text.
6322 Together with the b (no blanks at end of line) check, this
6323 enforces a canonical form for the use of blanks to separate
6324 source tokens.
6325
6326 @item ^i^IF_THEN^
6327 @emph{Check if-then layout.}
6328 The keyword @code{then} must appear either on the same
6329 line as corresponding @code{if}, or on a line on its own, lined
6330 up under the @code{if} with at least one non-blank line in between
6331 containing all or part of the condition to be tested.
6332
6333 @item ^I^IN_MODE^
6334 @emph{check mode IN keywords.}
6335 Mode @code{in} (the default mode) is not
6336 allowed to be given explicitly. @code{in out} is fine,
6337 but not @code{in} on its own.
6338
6339 @item ^k^KEYWORD^
6340 @emph{Check keyword casing.}
6341 All keywords must be in lower case (with the exception of keywords
6342 such as @code{digits} used as attribute names to which this check
6343 does not apply).
6344
6345 @item ^l^LAYOUT^
6346 @emph{Check layout.}
6347 Layout of statement and declaration constructs must follow the
6348 recommendations in the Ada Reference Manual, as indicated by the
6349 form of the syntax rules. For example an @code{else} keyword must
6350 be lined up with the corresponding @code{if} keyword.
6351
6352 There are two respects in which the style rule enforced by this check
6353 option are more liberal than those in the Ada Reference Manual. First
6354 in the case of record declarations, it is permissible to put the
6355 @code{record} keyword on the same line as the @code{type} keyword, and
6356 then the @code{end} in @code{end record} must line up under @code{type}.
6357 This is also permitted when the type declaration is split on two lines.
6358 For example, any of the following three layouts is acceptable:
6359
6360 @smallexample @c ada
6361 @cartouche
6362 type q is record
6363    a : integer;
6364    b : integer;
6365 end record;
6366
6367 type q is
6368    record
6369       a : integer;
6370       b : integer;
6371    end record;
6372
6373 type q is
6374    record
6375       a : integer;
6376       b : integer;
6377 end record;
6378
6379 @end cartouche
6380 @end smallexample
6381
6382 @noindent
6383 Second, in the case of a block statement, a permitted alternative
6384 is to put the block label on the same line as the @code{declare} or
6385 @code{begin} keyword, and then line the @code{end} keyword up under
6386 the block label. For example both the following are permitted:
6387
6388 @smallexample @c ada
6389 @cartouche
6390 Block : declare
6391    A : Integer := 3;
6392 begin
6393    Proc (A, A);
6394 end Block;
6395
6396 Block :
6397    declare
6398       A : Integer := 3;
6399    begin
6400       Proc (A, A);
6401    end Block;
6402 @end cartouche
6403 @end smallexample
6404
6405 @noindent
6406 The same alternative format is allowed for loops. For example, both of
6407 the following are permitted:
6408
6409 @smallexample @c ada
6410 @cartouche
6411 Clear : while J < 10 loop
6412    A (J) := 0;
6413 end loop Clear;
6414
6415 Clear :
6416    while J < 10 loop
6417       A (J) := 0;
6418    end loop Clear;
6419 @end cartouche
6420 @end smallexample
6421
6422 @item ^Lnnn^MAX_NESTING=nnn^
6423 @emph{Set maximum nesting level.}
6424 The maximum level of nesting of constructs (including subprograms, loops,
6425 blocks, packages, and conditionals) may not exceed the given value
6426 @option{nnn}. A value of zero disconnects this style check.
6427
6428 @item ^m^LINE_LENGTH^
6429 @emph{Check maximum line length.}
6430 The length of source lines must not exceed 79 characters, including
6431 any trailing blanks. The value of 79 allows convenient display on an
6432 80 character wide device or window, allowing for possible special
6433 treatment of 80 character lines. Note that this count is of
6434 characters in the source text. This means that a tab character counts
6435 as one character in this count and a wide character sequence counts as
6436 a single character (however many bytes are needed in the encoding).
6437
6438 @item ^Mnnn^MAX_LENGTH=nnn^
6439 @emph{Set maximum line length.}
6440 The length of lines must not exceed the
6441 given value @option{nnn}. The maximum value that can be specified is 32767.
6442 If neither style option for setting the line length is used, then the
6443 default is 255. This also controls the maximum length of lexical elements,
6444 where the only restriction is that they must fit on a single line.
6445
6446 @item ^n^STANDARD_CASING^
6447 @emph{Check casing of entities in Standard.}
6448 Any identifier from Standard must be cased
6449 to match the presentation in the Ada Reference Manual (for example,
6450 @code{Integer} and @code{ASCII.NUL}).
6451
6452 @item ^N^NONE^
6453 @emph{Turn off all style checks.}
6454 All style check options are turned off.
6455
6456 @item ^o^ORDERED_SUBPROGRAMS^
6457 @emph{Check order of subprogram bodies.}
6458 All subprogram bodies in a given scope
6459 (e.g.@: a package body) must be in alphabetical order. The ordering
6460 rule uses normal Ada rules for comparing strings, ignoring casing
6461 of letters, except that if there is a trailing numeric suffix, then
6462 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6463 before Junk10).
6464
6465 @item ^O^OVERRIDING_INDICATORS^
6466 @emph{Check that overriding subprograms are explicitly marked as such.}
6467 The declaration of a primitive operation of a type extension that overrides
6468 an inherited operation must carry an overriding indicator.
6469
6470 @item ^p^PRAGMA^
6471 @emph{Check pragma casing.}
6472 Pragma names must be written in mixed case, that is, the
6473 initial letter and any letter following an underscore must be uppercase.
6474 All other letters must be lowercase.
6475
6476 @item ^r^REFERENCES^
6477 @emph{Check references.}
6478 All identifier references must be cased in the same way as the
6479 corresponding declaration. No specific casing style is imposed on
6480 identifiers. The only requirement is for consistency of references
6481 with declarations.
6482
6483 @item ^s^SPECS^
6484 @emph{Check separate specs.}
6485 Separate declarations (``specs'') are required for subprograms (a
6486 body is not allowed to serve as its own declaration). The only
6487 exception is that parameterless library level procedures are
6488 not required to have a separate declaration. This exception covers
6489 the most frequent form of main program procedures.
6490
6491 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6492 @emph{Check no statements after @code{then}/@code{else}.}
6493 No statements are allowed
6494 on the same line as a @code{then} or @code{else} keyword following the
6495 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6496 affected, and a special exception allows a pragma to appear after @code{else}.
6497
6498 @item ^t^TOKEN^
6499 @emph{Check token spacing.}
6500 The following token spacing rules are enforced:
6501
6502 @itemize @bullet
6503
6504 @item
6505 The keywords @code{abs} and @code{not} must be followed by a space.
6506
6507 @item
6508 The token @code{=>} must be surrounded by spaces.
6509
6510 @item
6511 The token @code{<>} must be preceded by a space or a left parenthesis.
6512
6513 @item
6514 Binary operators other than @code{**} must be surrounded by spaces.
6515 There is no restriction on the layout of the @code{**} binary operator.
6516
6517 @item
6518 Colon must be surrounded by spaces.
6519
6520 @item
6521 Colon-equal (assignment, initialization) must be surrounded by spaces.
6522
6523 @item
6524 Comma must be the first non-blank character on the line, or be
6525 immediately preceded by a non-blank character, and must be followed
6526 by a space.
6527
6528 @item
6529 If the token preceding a left parenthesis ends with a letter or digit, then
6530 a space must separate the two tokens.
6531
6532 @item
6533 if the token following a right parenthesis starts with a letter or digit, then
6534 a space must separate the two tokens.
6535
6536 @item
6537 A right parenthesis must either be the first non-blank character on
6538 a line, or it must be preceded by a non-blank character.
6539
6540 @item
6541 A semicolon must not be preceded by a space, and must not be followed by
6542 a non-blank character.
6543
6544 @item
6545 A unary plus or minus may not be followed by a space.
6546
6547 @item
6548 A vertical bar must be surrounded by spaces.
6549 @end itemize
6550
6551 @item
6552 Exactly one blank (and no other white space) must appear between
6553 a @code{not} token and a following @code{in} token.
6554
6555 @item ^u^UNNECESSARY_BLANK_LINES^
6556 @emph{Check unnecessary blank lines.}
6557 Unnecessary blank lines are not allowed. A blank line is considered
6558 unnecessary if it appears at the end of the file, or if more than
6559 one blank line occurs in sequence.
6560
6561 @item ^x^XTRA_PARENS^
6562 @emph{Check extra parentheses.}
6563 Unnecessary extra level of parentheses (C-style) are not allowed
6564 around conditions in @code{if} statements, @code{while} statements and
6565 @code{exit} statements.
6566
6567 @item ^y^ALL_BUILTIN^
6568 @emph{Set all standard style check options}
6569 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6570 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6571 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6572 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6573
6574 @ifclear vms
6575 @item -
6576 @emph{Remove style check options}
6577 This causes any subsequent options in the string to act as canceling the
6578 corresponding style check option. To cancel maximum nesting level control,
6579 use @option{L} parameter witout any integer value after that, because any
6580 digit following @option{-} in the parameter string of the @option{-gnaty}
6581 option will be threated as canceling indentation check. The same is true
6582 for @option{M} parameter. @option{y} and @option{N} parameters are not
6583 allowed after @option{-}.
6584
6585 @item +
6586 This causes any subsequent options in the string to enable the corresponding
6587 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6588 if any.
6589 @end ifclear
6590
6591 @ifset vms
6592 @item NOxxx
6593 @emph{Removing style check options}
6594 If the name of a style check is preceded by @option{NO} then the corresponding
6595 style check is turned off. For example @option{NOCOMMENTS} turns off style
6596 checking for comments.
6597 @end ifset
6598 @end table
6599
6600 @noindent
6601 In the above rules, appearing in column one is always permitted, that is,
6602 counts as meeting either a requirement for a required preceding space,
6603 or as meeting a requirement for no preceding space.
6604
6605 Appearing at the end of a line is also always permitted, that is, counts
6606 as meeting either a requirement for a following space, or as meeting
6607 a requirement for no following space.
6608
6609 @noindent
6610 If any of these style rules is violated, a message is generated giving
6611 details on the violation. The initial characters of such messages are
6612 always ``@code{(style)}''. Note that these messages are treated as warning
6613 messages, so they normally do not prevent the generation of an object
6614 file. The @option{-gnatwe} switch can be used to treat warning messages,
6615 including style messages, as fatal errors.
6616
6617 The switch
6618 @ifclear vms
6619 @option{-gnaty} on its own (that is not
6620 followed by any letters or digits) is equivalent
6621 to the use of @option{-gnatyy} as described above, that is all
6622 built-in standard style check options are enabled.
6623
6624 @end ifclear
6625 @ifset vms
6626 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6627 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6628 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6629 @end ifset
6630
6631 The switch
6632 @ifclear vms
6633 @option{-gnatyN}
6634 @end ifclear
6635 @ifset vms
6636 /STYLE_CHECKS=NONE
6637 @end ifset
6638 clears any previously set style checks.
6639
6640 @node Run-Time Checks
6641 @subsection Run-Time Checks
6642 @cindex Division by zero
6643 @cindex Access before elaboration
6644 @cindex Checks, division by zero
6645 @cindex Checks, access before elaboration
6646 @cindex Checks, stack overflow checking
6647
6648 @noindent
6649 By default, the following checks are suppressed: integer overflow
6650 checks, stack overflow checks, and checks for access before
6651 elaboration on subprogram calls. All other checks, including range
6652 checks and array bounds checks, are turned on by default. The
6653 following @command{gcc} switches refine this default behavior.
6654
6655 @table @option
6656 @c !sort!
6657 @item -gnatp
6658 @cindex @option{-gnatp} (@command{gcc})
6659 @cindex Suppressing checks
6660 @cindex Checks, suppressing
6661 @findex Suppress
6662 This switch causes the unit to be compiled
6663 as though @code{pragma Suppress (All_checks)}
6664 had been present in the source. Validity checks are also eliminated (in
6665 other words @option{-gnatp} also implies @option{-gnatVn}.
6666 Use this switch to improve the performance
6667 of the code at the expense of safety in the presence of invalid data or
6668 program bugs.
6669
6670 Note that when checks are suppressed, the compiler is allowed, but not
6671 required, to omit the checking code. If the run-time cost of the
6672 checking code is zero or near-zero, the compiler will generate it even
6673 if checks are suppressed. In particular, if the compiler can prove
6674 that a certain check will necessarily fail, it will generate code to
6675 do an unconditional ``raise'', even if checks are suppressed. The
6676 compiler warns in this case. Another case in which checks may not be
6677 eliminated is when they are embedded in certain run time routines such
6678 as math library routines.
6679
6680 Of course, run-time checks are omitted whenever the compiler can prove
6681 that they will not fail, whether or not checks are suppressed.
6682
6683 Note that if you suppress a check that would have failed, program
6684 execution is erroneous, which means the behavior is totally
6685 unpredictable. The program might crash, or print wrong answers, or
6686 do anything else. It might even do exactly what you wanted it to do
6687 (and then it might start failing mysteriously next week or next
6688 year). The compiler will generate code based on the assumption that
6689 the condition being checked is true, which can result in disaster if
6690 that assumption is wrong.
6691
6692 The checks subject to suppression include all the checks defined by
6693 the Ada standard, the additional implementation defined checks
6694 @code{Alignment_Check}, @code{Atomic_Synchronization}, and
6695 @code{Validity_Check}, as well as any checks introduced using
6696 @code{pragma Check_Name}.
6697
6698 The @option{-gnatp} switch has no effect if a subsequent
6699 @option{-gnat-p} switch appears.
6700
6701 @item -gnat-p
6702 @cindex @option{-gnat-p} (@command{gcc})
6703 @cindex Suppressing checks
6704 @cindex Checks, suppressing
6705 @findex Suppress
6706 This switch cancels the effect of a previous @option{gnatp} switch.
6707
6708 @item -gnato??
6709 @cindex @option{-gnato??} (@command{gcc})
6710 @cindex Overflow checks
6711 @cindex Overflow mode
6712 @cindex Check, overflow
6713 This switch controls the mode used for computing intermediate
6714 arithmetic integer operations, and also enables overflow checking.
6715 For a full description of overflow mode and checking control, see
6716 the ``Overflow Check Handling in GNAT'' appendix in this
6717 User's Guide.
6718
6719 Overflow checks are always enabled by this switch. The argument
6720 controls the mode, using the codes
6721
6722 @itemize
6723 @item 1 = STRICT
6724 In STRICT mode, intermediate operations are always done using the
6725 base type, and overflow checking ensures that the result is within
6726 the base type range.
6727
6728 @item 2 = MINIMIZED
6729 In MINIMIZED mode, overflows in intermediate operations are avoided
6730 where possible by using a larger integer type for the computation
6731 (typically @code{Long_Long_Integer}). Overflow checking ensures that
6732 the result fits in this larger integer type.
6733
6734 @item 3 = ELIMINATED
6735 In ELIMINATED mode, overflows in intermediate operations are avoided
6736 by using multi-precision arithmetic. In this case, overflow checking
6737 has no effect on intermediate operations (since overflow is impossible).
6738 @end itemize
6739
6740 If two digits are present after @option{-gnato} then the first digit
6741 sets the mode for expressions outside assertions, and the second digit
6742 sets the mode for expressions within assertions. Here assertions is used
6743 in the technical sense (which includes for example precondition and
6744 postcondition expressions).
6745
6746 If one digit is present, the corresponding mode is applicable to both
6747 expressions within and outside assertion expressions.
6748
6749 If no digits are present, the default is to enable overflow checks
6750 and set STRICT mode for both kinds of expressions. This is compatible
6751 with the use of @option{-gnato} in previous versions of GNAT.
6752
6753 @findex Machine_Overflows
6754 Note that the @option{-gnato??} switch does not affect the code generated
6755 for any floating-point operations; it applies only to integer semantics.
6756 For floating-point, @value{EDITION} has the @code{Machine_Overflows}
6757 attribute set to @code{False} and the normal mode of operation is to
6758 generate IEEE NaN and infinite values on overflow or invalid operations
6759 (such as dividing 0.0 by 0.0).
6760
6761 The reason that we distinguish overflow checking from other kinds of
6762 range constraint checking is that a failure of an overflow check, unlike
6763 for example the failure of a range check, can result in an incorrect
6764 value, but cannot cause random memory destruction (like an out of range
6765 subscript), or a wild jump (from an out of range case value). Overflow
6766 checking is also quite expensive in time and space, since in general it
6767 requires the use of double length arithmetic.
6768
6769 Note again that the default is @option{^-gnato00^/OVERFLOW_CHECKS=00^},
6770 so overflow checking is not performed in default mode. This means that out of
6771 the box, with the default settings, @value{EDITION} does not do all the checks
6772 expected from the language description in the Ada Reference Manual.
6773 If you want all constraint checks to be performed, as described in this Manual,
6774 then you must explicitly use the @option{-gnato??}
6775 switch either on the @command{gnatmake} or @command{gcc} command.
6776
6777 @item -gnatE
6778 @cindex @option{-gnatE} (@command{gcc})
6779 @cindex Elaboration checks
6780 @cindex Check, elaboration
6781 Enables dynamic checks for access-before-elaboration
6782 on subprogram calls and generic instantiations.
6783 Note that @option{-gnatE} is not necessary for safety, because in the
6784 default mode, GNAT ensures statically that the checks would not fail.
6785 For full details of the effect and use of this switch,
6786 @xref{Compiling with gcc}.
6787
6788 @item -fstack-check
6789 @cindex @option{-fstack-check} (@command{gcc})
6790 @cindex Stack Overflow Checking
6791 @cindex Checks, stack overflow checking
6792 Activates stack overflow checking. For full details of the effect and use of
6793 this switch see @ref{Stack Overflow Checking}.
6794 @end table
6795
6796 @findex Unsuppress
6797 @noindent
6798 The setting of these switches only controls the default setting of the
6799 checks. You may modify them using either @code{Suppress} (to remove
6800 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6801 the program source.
6802
6803 @node Using gcc for Syntax Checking
6804 @subsection Using @command{gcc} for Syntax Checking
6805 @table @option
6806 @item -gnats
6807 @cindex @option{-gnats} (@command{gcc})
6808 @ifclear vms
6809
6810 @noindent
6811 The @code{s} stands for ``syntax''.
6812 @end ifclear
6813
6814 Run GNAT in syntax checking only mode. For
6815 example, the command
6816
6817 @smallexample
6818 $ gcc -c -gnats x.adb
6819 @end smallexample
6820
6821 @noindent
6822 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6823 series of files in a single command
6824 @ifclear vms
6825 , and can use wild cards to specify such a group of files.
6826 Note that you must specify the @option{-c} (compile
6827 only) flag in addition to the @option{-gnats} flag.
6828 @end ifclear
6829 .
6830 You may use other switches in conjunction with @option{-gnats}. In
6831 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6832 format of any generated error messages.
6833
6834 When the source file is empty or contains only empty lines and/or comments,
6835 the output is a warning:
6836
6837 @smallexample
6838 $ gcc -c -gnats -x ada toto.txt
6839 toto.txt:1:01: warning: empty file, contains no compilation units
6840 $
6841 @end smallexample
6842
6843 Otherwise, the output is simply the error messages, if any. No object file or
6844 ALI file is generated by a syntax-only compilation. Also, no units other
6845 than the one specified are accessed. For example, if a unit @code{X}
6846 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6847 check only mode does not access the source file containing unit
6848 @code{Y}.
6849
6850 @cindex Multiple units, syntax checking
6851 Normally, GNAT allows only a single unit in a source file. However, this
6852 restriction does not apply in syntax-check-only mode, and it is possible
6853 to check a file containing multiple compilation units concatenated
6854 together. This is primarily used by the @code{gnatchop} utility
6855 (@pxref{Renaming Files with gnatchop}).
6856 @end table
6857
6858 @node Using gcc for Semantic Checking
6859 @subsection Using @command{gcc} for Semantic Checking
6860 @table @option
6861 @item -gnatc
6862 @cindex @option{-gnatc} (@command{gcc})
6863
6864 @ifclear vms
6865 @noindent
6866 The @code{c} stands for ``check''.
6867 @end ifclear
6868 Causes the compiler to operate in semantic check mode,
6869 with full checking for all illegalities specified in the
6870 Ada Reference Manual, but without generation of any object code
6871 (no object file is generated).
6872
6873 Because dependent files must be accessed, you must follow the GNAT
6874 semantic restrictions on file structuring to operate in this mode:
6875
6876 @itemize @bullet
6877 @item
6878 The needed source files must be accessible
6879 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6880
6881 @item
6882 Each file must contain only one compilation unit.
6883
6884 @item
6885 The file name and unit name must match (@pxref{File Naming Rules}).
6886 @end itemize
6887
6888 The output consists of error messages as appropriate. No object file is
6889 generated. An @file{ALI} file is generated for use in the context of
6890 cross-reference tools, but this file is marked as not being suitable
6891 for binding (since no object file is generated).
6892 The checking corresponds exactly to the notion of
6893 legality in the Ada Reference Manual.
6894
6895 Any unit can be compiled in semantics-checking-only mode, including
6896 units that would not normally be compiled (subunits,
6897 and specifications where a separate body is present).
6898 @end table
6899
6900 @node Compiling Different Versions of Ada
6901 @subsection Compiling Different Versions of Ada
6902
6903 @noindent
6904 The switches described in this section allow you to explicitly specify
6905 the version of the Ada language that your programs are written in.
6906 The default mode is Ada 2012,
6907 but you can also specify Ada 95, Ada 2005 mode, or
6908 indicate Ada 83 compatibility mode.
6909
6910 @table @option
6911 @cindex Compatibility with Ada 83
6912
6913 @item -gnat83 (Ada 83 Compatibility Mode)
6914 @cindex @option{-gnat83} (@command{gcc})
6915 @cindex ACVC, Ada 83 tests
6916 @cindex Ada 83 mode
6917
6918 @noindent
6919 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6920 specifies that the program is to be compiled in Ada 83 mode. With
6921 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6922 semantics where this can be done easily.
6923 It is not possible to guarantee this switch does a perfect
6924 job; some subtle tests, such as are
6925 found in earlier ACVC tests (and that have been removed from the ACATS suite
6926 for Ada 95), might not compile correctly.
6927 Nevertheless, this switch may be useful in some circumstances, for example
6928 where, due to contractual reasons, existing code needs to be maintained
6929 using only Ada 83 features.
6930
6931 With few exceptions (most notably the need to use @code{<>} on
6932 @cindex Generic formal parameters
6933 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6934 reserved words, and the use of packages
6935 with optional bodies), it is not necessary to specify the
6936 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6937 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6938 a correct Ada 83 program is usually also a correct program
6939 in these later versions of the language standard.
6940 For further information, please refer to @ref{Compatibility and Porting Guide}.
6941
6942 @item -gnat95 (Ada 95 mode)
6943 @cindex @option{-gnat95} (@command{gcc})
6944 @cindex Ada 95 mode
6945
6946 @noindent
6947 This switch directs the compiler to implement the Ada 95 version of the
6948 language.
6949 Since Ada 95 is almost completely upwards
6950 compatible with Ada 83, Ada 83 programs may generally be compiled using
6951 this switch (see the description of the @option{-gnat83} switch for further
6952 information about Ada 83 mode).
6953 If an Ada 2005 program is compiled in Ada 95 mode,
6954 uses of the new Ada 2005 features will cause error
6955 messages or warnings.
6956
6957 This switch also can be used to cancel the effect of a previous
6958 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
6959 switch earlier in the command line.
6960
6961 @item -gnat05 or -gnat2005 (Ada 2005 mode)
6962 @cindex @option{-gnat05} (@command{gcc})
6963 @cindex @option{-gnat2005} (@command{gcc})
6964 @cindex Ada 2005 mode
6965
6966 @noindent
6967 This switch directs the compiler to implement the Ada 2005 version of the
6968 language, as documented in the official Ada standards document.
6969 Since Ada 2005 is almost completely upwards
6970 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6971 may generally be compiled using this switch (see the description of the
6972 @option{-gnat83} and @option{-gnat95} switches for further
6973 information).
6974
6975 @item -gnat12 or -gnat2012 (Ada 2012 mode)
6976 @cindex @option{-gnat12} (@command{gcc})
6977 @cindex @option{-gnat2012} (@command{gcc})
6978 @cindex Ada 2012 mode
6979
6980 @noindent
6981 This switch directs the compiler to implement the Ada 2012 version of the
6982 language (also the default).
6983 Since Ada 2012 is almost completely upwards
6984 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
6985 Ada 83 and Ada 95 programs
6986 may generally be compiled using this switch (see the description of the
6987 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
6988 for further information).
6989
6990 @item -gnatX (Enable GNAT Extensions)
6991 @cindex @option{-gnatX} (@command{gcc})
6992 @cindex Ada language extensions
6993 @cindex GNAT extensions
6994
6995 @noindent
6996 This switch directs the compiler to implement the latest version of the
6997 language (currently Ada 2012) and also to enable certain GNAT implementation
6998 extensions that are not part of any Ada standard. For a full list of these
6999 extensions, see the GNAT reference manual.
7000
7001 @end table
7002
7003 @node Character Set Control
7004 @subsection Character Set Control
7005 @table @option
7006 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7007 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7008
7009 @noindent
7010 Normally GNAT recognizes the Latin-1 character set in source program
7011 identifiers, as described in the Ada Reference Manual.
7012 This switch causes
7013 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7014 single character ^^or word^ indicating the character set, as follows:
7015
7016 @table @code
7017 @item 1
7018 ISO 8859-1 (Latin-1) identifiers
7019
7020 @item 2
7021 ISO 8859-2 (Latin-2) letters allowed in identifiers
7022
7023 @item 3
7024 ISO 8859-3 (Latin-3) letters allowed in identifiers
7025
7026 @item 4
7027 ISO 8859-4 (Latin-4) letters allowed in identifiers
7028
7029 @item 5
7030 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7031
7032 @item 9
7033 ISO 8859-15 (Latin-9) letters allowed in identifiers
7034
7035 @item ^p^PC^
7036 IBM PC letters (code page 437) allowed in identifiers
7037
7038 @item ^8^PC850^
7039 IBM PC letters (code page 850) allowed in identifiers
7040
7041 @item ^f^FULL_UPPER^
7042 Full upper-half codes allowed in identifiers
7043
7044 @item ^n^NO_UPPER^
7045 No upper-half codes allowed in identifiers
7046
7047 @item ^w^WIDE^
7048 Wide-character codes (that is, codes greater than 255)
7049 allowed in identifiers
7050 @end table
7051
7052 @xref{Foreign Language Representation}, for full details on the
7053 implementation of these character sets.
7054
7055 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7056 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7057 Specify the method of encoding for wide characters.
7058 @var{e} is one of the following:
7059
7060 @table @code
7061
7062 @item ^h^HEX^
7063 Hex encoding (brackets coding also recognized)
7064
7065 @item ^u^UPPER^
7066 Upper half encoding (brackets encoding also recognized)
7067
7068 @item ^s^SHIFT_JIS^
7069 Shift/JIS encoding (brackets encoding also recognized)
7070
7071 @item ^e^EUC^
7072 EUC encoding (brackets encoding also recognized)
7073
7074 @item ^8^UTF8^
7075 UTF-8 encoding (brackets encoding also recognized)
7076
7077 @item ^b^BRACKETS^
7078 Brackets encoding only (default value)
7079 @end table
7080 For full details on these encoding
7081 methods see @ref{Wide Character Encodings}.
7082 Note that brackets coding is always accepted, even if one of the other
7083 options is specified, so for example @option{-gnatW8} specifies that both
7084 brackets and UTF-8 encodings will be recognized. The units that are
7085 with'ed directly or indirectly will be scanned using the specified
7086 representation scheme, and so if one of the non-brackets scheme is
7087 used, it must be used consistently throughout the program. However,
7088 since brackets encoding is always recognized, it may be conveniently
7089 used in standard libraries, allowing these libraries to be used with
7090 any of the available coding schemes.
7091
7092 Note that brackets encoding only applies to program text. Within comments,
7093 brackets are considered to be normal graphic characters, and bracket sequences
7094 are never recognized as wide characters.
7095
7096 If no @option{-gnatW?} parameter is present, then the default
7097 representation is normally Brackets encoding only. However, if the
7098 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7099 byte order mark or BOM for UTF-8), then these three characters are
7100 skipped and the default representation for the file is set to UTF-8.
7101
7102 Note that the wide character representation that is specified (explicitly
7103 or by default) for the main program also acts as the default encoding used
7104 for Wide_Text_IO files if not specifically overridden by a WCEM form
7105 parameter.
7106
7107 @end table
7108
7109 When no @option{-gnatW?} is specified, then characters (other than wide
7110 characters represented using brackets notation) are treated as 8-bit
7111 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
7112 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
7113 characters in the range 16#00#..16#1F# are not accepted in program text
7114 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
7115 in program text, but allowed and ignored in comments. Note in particular
7116 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
7117 as an end of line in this default mode. If your source program contains
7118 instances of the NEL character used as a line terminator,
7119 you must use UTF-8 encoding for the whole
7120 source program. In default mode, all lines must be ended by a standard
7121 end of line sequence (CR, CR/LF, or LF).
7122
7123 Note that the convention of simply accepting all upper half characters in
7124 comments means that programs that use standard ASCII for program text, but
7125 UTF-8 encoding for comments are accepted in default mode, providing that the
7126 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
7127 This is a common mode for many programs with foreign language comments.
7128
7129 @node File Naming Control
7130 @subsection File Naming Control
7131
7132 @table @option
7133 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7134 @cindex @option{-gnatk} (@command{gcc})
7135 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7136 1-999, indicates the maximum allowable length of a file name (not
7137 including the @file{.ads} or @file{.adb} extension). The default is not
7138 to enable file name krunching.
7139
7140 For the source file naming rules, @xref{File Naming Rules}.
7141 @end table
7142
7143 @node Subprogram Inlining Control
7144 @subsection Subprogram Inlining Control
7145
7146 @table @option
7147 @c !sort!
7148 @item -gnatn[12]
7149 @cindex @option{-gnatn} (@command{gcc})
7150 @ifclear vms
7151 The @code{n} here is intended to suggest the first syllable of the
7152 word ``inline''.
7153 @end ifclear
7154 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7155 inlining to actually occur, optimization must be enabled and, in order
7156 to enable inlining of subprograms specified by pragma @code{Inline},
7157 you must also specify this switch.
7158 In the absence of this switch, GNAT does not attempt
7159 inlining and does not need to access the bodies of
7160 subprograms for which @code{pragma Inline} is specified if they are not
7161 in the current unit.
7162
7163 You can optionally specify the inlining level: 1 for moderate inlining across
7164 modules, which is a good compromise between compilation times and performances
7165 at run time, or 2 for full inlining across modules, which may bring about
7166 longer compilation times. If no inlining level is specified, the compiler will
7167 pick it based on the optimization level: 1 for @option{-O1}, @option{-O2} or
7168 @option{-Os} and 2 for @option{-O3}.
7169
7170 If you specify this switch the compiler will access these bodies,
7171 creating an extra source dependency for the resulting object file, and
7172 where possible, the call will be inlined.
7173 For further details on when inlining is possible
7174 see @ref{Inlining of Subprograms}.
7175
7176 @item -gnatN
7177 @cindex @option{-gnatN} (@command{gcc})
7178 This switch activates front-end inlining which also
7179 generates additional dependencies.
7180
7181 When using a gcc-based back end (in practice this means using any version
7182 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7183 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7184 Historically front end inlining was more extensive than the gcc back end
7185 inlining, but that is no longer the case.
7186 @end table
7187
7188 @node Auxiliary Output Control
7189 @subsection Auxiliary Output Control
7190
7191 @table @option
7192 @item -gnatt
7193 @cindex @option{-gnatt} (@command{gcc})
7194 @cindex Writing internal trees
7195 @cindex Internal trees, writing to file
7196 Causes GNAT to write the internal tree for a unit to a file (with the
7197 extension @file{.adt}.
7198 This not normally required, but is used by separate analysis tools.
7199 Typically
7200 these tools do the necessary compilations automatically, so you should
7201 not have to specify this switch in normal operation.
7202 Note that the combination of switches @option{-gnatct}
7203 generates a tree in the form required by ASIS applications.
7204
7205 @item -gnatu
7206 @cindex @option{-gnatu} (@command{gcc})
7207 Print a list of units required by this compilation on @file{stdout}.
7208 The listing includes all units on which the unit being compiled depends
7209 either directly or indirectly.
7210
7211 @ifclear vms
7212 @item -pass-exit-codes
7213 @cindex @option{-pass-exit-codes} (@command{gcc})
7214 If this switch is not used, the exit code returned by @command{gcc} when
7215 compiling multiple files indicates whether all source files have
7216 been successfully used to generate object files or not.
7217
7218 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7219 exit status and allows an integrated development environment to better
7220 react to a compilation failure. Those exit status are:
7221
7222 @table @asis
7223 @item 5
7224 There was an error in at least one source file.
7225 @item 3
7226 At least one source file did not generate an object file.
7227 @item 2
7228 The compiler died unexpectedly (internal error for example).
7229 @item 0
7230 An object file has been generated for every source file.
7231 @end table
7232 @end ifclear
7233 @end table
7234
7235 @node Debugging Control
7236 @subsection Debugging Control
7237
7238 @table @option
7239 @c !sort!
7240 @cindex Debugging options
7241 @ifclear vms
7242 @item -gnatd@var{x}
7243 @cindex @option{-gnatd} (@command{gcc})
7244 Activate internal debugging switches. @var{x} is a letter or digit, or
7245 string of letters or digits, which specifies the type of debugging
7246 outputs desired. Normally these are used only for internal development
7247 or system debugging purposes. You can find full documentation for these
7248 switches in the body of the @code{Debug} unit in the compiler source
7249 file @file{debug.adb}.
7250 @end ifclear
7251
7252 @item -gnatG[=nn]
7253 @cindex @option{-gnatG} (@command{gcc})
7254 This switch causes the compiler to generate auxiliary output containing
7255 a pseudo-source listing of the generated expanded code. Like most Ada
7256 compilers, GNAT works by first transforming the high level Ada code into
7257 lower level constructs. For example, tasking operations are transformed
7258 into calls to the tasking run-time routines. A unique capability of GNAT
7259 is to list this expanded code in a form very close to normal Ada source.
7260 This is very useful in understanding the implications of various Ada
7261 usage on the efficiency of the generated code. There are many cases in
7262 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7263 generate a lot of run-time code. By using @option{-gnatG} you can identify
7264 these cases, and consider whether it may be desirable to modify the coding
7265 approach to improve efficiency.
7266
7267 The optional parameter @code{nn} if present after -gnatG specifies an
7268 alternative maximum line length that overrides the normal default of 72.
7269 This value is in the range 40-999999, values less than 40 being silently
7270 reset to 40. The equal sign is optional.
7271
7272 The format of the output is very similar to standard Ada source, and is
7273 easily understood by an Ada programmer. The following special syntactic
7274 additions correspond to low level features used in the generated code that
7275 do not have any exact analogies in pure Ada source form. The following
7276 is a partial list of these special constructions. See the spec
7277 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7278
7279 If the switch @option{-gnatL} is used in conjunction with
7280 @cindex @option{-gnatL} (@command{gcc})
7281 @option{-gnatG}, then the original source lines are interspersed
7282 in the expanded source (as comment lines with the original line number).
7283
7284 @table @code
7285 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7286 Shows the storage pool being used for an allocator.
7287
7288 @item at end @var{procedure-name};
7289 Shows the finalization (cleanup) procedure for a scope.
7290
7291 @item (if @var{expr} then @var{expr} else @var{expr})
7292 Conditional expression equivalent to the @code{x?y:z} construction in C.
7293
7294 @item @var{target}^^^(@var{source})
7295 A conversion with floating-point truncation instead of rounding.
7296
7297 @item @var{target}?(@var{source})
7298 A conversion that bypasses normal Ada semantic checking. In particular
7299 enumeration types and fixed-point types are treated simply as integers.
7300
7301 @item @var{target}?^^^(@var{source})
7302 Combines the above two cases.
7303
7304 @item @var{x} #/ @var{y}
7305 @itemx @var{x} #mod @var{y}
7306 @itemx @var{x} #* @var{y}
7307 @itemx @var{x} #rem @var{y}
7308 A division or multiplication of fixed-point values which are treated as
7309 integers without any kind of scaling.
7310
7311 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7312 Shows the storage pool associated with a @code{free} statement.
7313
7314 @item [subtype or type declaration]
7315 Used to list an equivalent declaration for an internally generated
7316 type that is referenced elsewhere in the listing.
7317
7318 @c @item freeze @var{type-name} @ovar{actions}
7319 @c Expanding @ovar macro inline (explanation in macro def comments)
7320 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7321 Shows the point at which @var{type-name} is frozen, with possible
7322 associated actions to be performed at the freeze point.
7323
7324 @item reference @var{itype}
7325 Reference (and hence definition) to internal type @var{itype}.
7326
7327 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7328 Intrinsic function call.
7329
7330 @item @var{label-name} : label
7331 Declaration of label @var{labelname}.
7332
7333 @item #$ @var{subprogram-name}
7334 An implicit call to a run-time support routine
7335 (to meet the requirement of H.3.1(9) in a
7336 convenient manner).
7337
7338 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7339 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7340 @var{expr}, but handled more efficiently).
7341
7342 @item [constraint_error]
7343 Raise the @code{Constraint_Error} exception.
7344
7345 @item @var{expression}'reference
7346 A pointer to the result of evaluating @var{expression}.
7347
7348 @item @var{target-type}!(@var{source-expression})
7349 An unchecked conversion of @var{source-expression} to @var{target-type}.
7350
7351 @item [@var{numerator}/@var{denominator}]
7352 Used to represent internal real literals (that) have no exact
7353 representation in base 2-16 (for example, the result of compile time
7354 evaluation of the expression 1.0/27.0).
7355 @end table
7356
7357 @item -gnatD[=nn]
7358 @cindex @option{-gnatD} (@command{gcc})
7359 When used in conjunction with @option{-gnatG}, this switch causes
7360 the expanded source, as described above for
7361 @option{-gnatG} to be written to files with names
7362 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7363 instead of to the standard output file. For
7364 example, if the source file name is @file{hello.adb}, then a file
7365 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written.  The debugging
7366 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7367 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7368 you to do source level debugging using the generated code which is
7369 sometimes useful for complex code, for example to find out exactly
7370 which part of a complex construction raised an exception. This switch
7371 also suppress generation of cross-reference information (see
7372 @option{-gnatx}) since otherwise the cross-reference information
7373 would refer to the @file{^.dg^.DG^} file, which would cause
7374 confusion since this is not the original source file.
7375
7376 Note that @option{-gnatD} actually implies @option{-gnatG}
7377 automatically, so it is not necessary to give both options.
7378 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7379
7380 If the switch @option{-gnatL} is used in conjunction with
7381 @cindex @option{-gnatL} (@command{gcc})
7382 @option{-gnatDG}, then the original source lines are interspersed
7383 in the expanded source (as comment lines with the original line number).
7384
7385 The optional parameter @code{nn} if present after -gnatD specifies an
7386 alternative maximum line length that overrides the normal default of 72.
7387 This value is in the range 40-999999, values less than 40 being silently
7388 reset to 40. The equal sign is optional.
7389
7390 @item -gnatr
7391 @cindex @option{-gnatr} (@command{gcc})
7392 @cindex pragma Restrictions
7393 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7394 so that violation of restrictions causes warnings rather than illegalities.
7395 This is useful during the development process when new restrictions are added
7396 or investigated. The switch also causes pragma Profile to be treated as
7397 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7398 restriction warnings rather than restrictions.
7399
7400 @ifclear vms
7401 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7402 @cindex @option{-gnatR} (@command{gcc})
7403 This switch controls output from the compiler of a listing showing
7404 representation information for declared types and objects. For
7405 @option{-gnatR0}, no information is output (equivalent to omitting
7406 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7407 so @option{-gnatR} with no parameter has the same effect), size and alignment
7408 information is listed for declared array and record types. For
7409 @option{-gnatR2}, size and alignment information is listed for all
7410 declared types and objects. Finally @option{-gnatR3} includes symbolic
7411 expressions for values that are computed at run time for
7412 variant records. These symbolic expressions have a mostly obvious
7413 format with #n being used to represent the value of the n'th
7414 discriminant. See source files @file{repinfo.ads/adb} in the
7415 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7416 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7417 the output is to a file with the name @file{^file.rep^file_REP^} where
7418 file is the name of the corresponding source file.
7419
7420 @item -gnatRm[s]
7421 This form of the switch controls output of subprogram conventions
7422 and parameter passing mechanisms for all subprograms. A following
7423 @code{s} means output to a file as described above.
7424 @end ifclear
7425 @ifset vms
7426 @item /REPRESENTATION_INFO
7427 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7428 This qualifier controls output from the compiler of a listing showing
7429 representation information for declared types and objects. For
7430 @option{/REPRESENTATION_INFO=NONE}, no information is output
7431 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7432 @option{/REPRESENTATION_INFO} without option is equivalent to
7433 @option{/REPRESENTATION_INFO=ARRAYS}.
7434 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7435 information is listed for declared array and record types. For
7436 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7437 is listed for all expression information for values that are computed
7438 at run time for variant records. These symbolic expressions have a mostly
7439 obvious format with #n being used to represent the value of the n'th
7440 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7441 @code{GNAT} sources for full details on the format of
7442 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7443 If _FILE is added at the end of an option
7444 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7445 then the output is to a file with the name @file{file_REP} where
7446 file is the name of the corresponding source file.
7447
7448 @item /REPRESENTATION_INFO=MECHANISMS
7449 This qualifier form controls output of subprogram conventions
7450 and parameter passing mechanisms for all subprograms. It is
7451 possible to append _FILE as described above to cause information
7452 to be written to a file.
7453 @end ifset
7454
7455 Note that it is possible for record components to have zero size. In
7456 this case, the component clause uses an obvious extension of permitted
7457 Ada syntax, for example @code{at 0 range 0 .. -1}.
7458
7459 Representation information requires that code be generated (since it is the
7460 code generator that lays out complex data structures). If an attempt is made
7461 to output representation information when no code is generated, for example
7462 when a subunit is compiled on its own, then no information can be generated
7463 and the compiler outputs a message to this effect.
7464
7465 @item -gnatS
7466 @cindex @option{-gnatS} (@command{gcc})
7467 The use of the switch @option{-gnatS} for an
7468 Ada compilation will cause the compiler to output a
7469 representation of package Standard in a form very
7470 close to standard Ada. It is not quite possible to
7471 do this entirely in standard Ada (since new
7472 numeric base types cannot be created in standard
7473 Ada), but the output is easily
7474 readable to any Ada programmer, and is useful to
7475 determine the characteristics of target dependent
7476 types in package Standard.
7477
7478 @item -gnatx
7479 @cindex @option{-gnatx} (@command{gcc})
7480 Normally the compiler generates full cross-referencing information in
7481 the @file{ALI} file. This information is used by a number of tools,
7482 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7483 suppresses this information. This saves some space and may slightly
7484 speed up compilation, but means that these tools cannot be used.
7485 @end table
7486
7487 @node Exception Handling Control
7488 @subsection Exception Handling Control
7489
7490 @noindent
7491 GNAT uses two methods for handling exceptions at run-time. The
7492 @code{setjmp/longjmp} method saves the context when entering
7493 a frame with an exception handler. Then when an exception is
7494 raised, the context can be restored immediately, without the
7495 need for tracing stack frames. This method provides very fast
7496 exception propagation, but introduces significant overhead for
7497 the use of exception handlers, even if no exception is raised.
7498
7499 The other approach is called ``zero cost'' exception handling.
7500 With this method, the compiler builds static tables to describe
7501 the exception ranges. No dynamic code is required when entering
7502 a frame containing an exception handler. When an exception is
7503 raised, the tables are used to control a back trace of the
7504 subprogram invocation stack to locate the required exception
7505 handler. This method has considerably poorer performance for
7506 the propagation of exceptions, but there is no overhead for
7507 exception handlers if no exception is raised. Note that in this
7508 mode and in the context of mixed Ada and C/C++ programming,
7509 to propagate an exception through a C/C++ code, the C/C++ code
7510 must be compiled with the @option{-funwind-tables} GCC's
7511 option.
7512
7513 The following switches may be used to control which of the
7514 two exception handling methods is used.
7515
7516 @table @option
7517 @c !sort!
7518
7519 @item --RTS=sjlj
7520 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7521 This switch causes the setjmp/longjmp run-time (when available) to be used
7522 for exception handling. If the default
7523 mechanism for the target is zero cost exceptions, then
7524 this switch can be used to modify this default, and must be
7525 used for all units in the partition.
7526 This option is rarely used. One case in which it may be
7527 advantageous is if you have an application where exception
7528 raising is common and the overall performance of the
7529 application is improved by favoring exception propagation.
7530
7531 @item --RTS=zcx
7532 @cindex @option{--RTS=zcx} (@command{gnatmake})
7533 @cindex Zero Cost Exceptions
7534 This switch causes the zero cost approach to be used
7535 for exception handling. If this is the default mechanism for the
7536 target (see below), then this switch is unneeded. If the default
7537 mechanism for the target is setjmp/longjmp exceptions, then
7538 this switch can be used to modify this default, and must be
7539 used for all units in the partition.
7540 This option can only be used if the zero cost approach
7541 is available for the target in use, otherwise it will generate an error.
7542 @end table
7543
7544 @noindent
7545 The same option @option{--RTS} must be used both for @command{gcc}
7546 and @command{gnatbind}. Passing this option to @command{gnatmake}
7547 (@pxref{Switches for gnatmake}) will ensure the required consistency
7548 through the compilation and binding steps.
7549
7550 @node Units to Sources Mapping Files
7551 @subsection Units to Sources Mapping Files
7552
7553 @table @option
7554
7555 @item -gnatem=@var{path}
7556 @cindex @option{-gnatem} (@command{gcc})
7557 A mapping file is a way to communicate to the compiler two mappings:
7558 from unit names to file names (without any directory information) and from
7559 file names to path names (with full directory information). These mappings
7560 are used by the compiler to short-circuit the path search.
7561
7562 The use of mapping files is not required for correct operation of the
7563 compiler, but mapping files can improve efficiency, particularly when
7564 sources are read over a slow network connection. In normal operation,
7565 you need not be concerned with the format or use of mapping files,
7566 and the @option{-gnatem} switch is not a switch that you would use
7567 explicitly. It is intended primarily for use by automatic tools such as
7568 @command{gnatmake} running under the project file facility. The
7569 description here of the format of mapping files is provided
7570 for completeness and for possible use by other tools.
7571
7572 A mapping file is a sequence of sets of three lines. In each set, the
7573 first line is the unit name, in lower case, with @code{%s} appended
7574 for specs and @code{%b} appended for bodies; the second line is the
7575 file name; and the third line is the path name.
7576
7577 Example:
7578 @smallexample
7579    main%b
7580    main.2.ada
7581    /gnat/project1/sources/main.2.ada
7582 @end smallexample
7583
7584 When the switch @option{-gnatem} is specified, the compiler will
7585 create in memory the two mappings from the specified file. If there is
7586 any problem (nonexistent file, truncated file or duplicate entries),
7587 no mapping will be created.
7588
7589 Several @option{-gnatem} switches may be specified; however, only the
7590 last one on the command line will be taken into account.
7591
7592 When using a project file, @command{gnatmake} creates a temporary
7593 mapping file and communicates it to the compiler using this switch.
7594
7595 @end table
7596
7597 @node Integrated Preprocessing
7598 @subsection Integrated Preprocessing
7599
7600 @noindent
7601 GNAT sources may be preprocessed immediately before compilation.
7602 In this case, the actual
7603 text of the source is not the text of the source file, but is derived from it
7604 through a process called preprocessing. Integrated preprocessing is specified
7605 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7606 indicates, through a text file, the preprocessing data to be used.
7607 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7608
7609 @noindent
7610 Note that when integrated preprocessing is used, the output from the
7611 preprocessor is not written to any external file. Instead it is passed
7612 internally to the compiler. If you need to preserve the result of
7613 preprocessing in a file, then you should use @command{gnatprep}
7614 to perform the desired preprocessing in stand-alone mode.
7615
7616 @noindent
7617 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7618 used when Integrated Preprocessing is used. The reason is that preprocessing
7619 with another Preprocessing Data file without changing the sources will
7620 not trigger recompilation without this switch.
7621
7622 @noindent
7623 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7624 always trigger recompilation for sources that are preprocessed,
7625 because @command{gnatmake} cannot compute the checksum of the source after
7626 preprocessing.
7627
7628 @noindent
7629 The actual preprocessing function is described in details in section
7630 @ref{Preprocessing with gnatprep}. This section only describes how integrated
7631 preprocessing is triggered and parameterized.
7632
7633 @table @code
7634
7635 @item -gnatep=@var{file}
7636 @cindex @option{-gnatep} (@command{gcc})
7637 This switch indicates to the compiler the file name (without directory
7638 information) of the preprocessor data file to use. The preprocessor data file
7639 should be found in the source directories. Note that when the compiler is
7640 called by a builder such as (@command{gnatmake} with a project
7641 file, if the object directory is not also a source directory, the builder needs
7642 to be called with @option{-x}.
7643
7644 @noindent
7645 A preprocessing data file is a text file with significant lines indicating
7646 how should be preprocessed either a specific source or all sources not
7647 mentioned in other lines. A significant line is a nonempty, non-comment line.
7648 Comments are similar to Ada comments.
7649
7650 @noindent
7651 Each significant line starts with either a literal string or the character '*'.
7652 A literal string is the file name (without directory information) of the source
7653 to preprocess. A character '*' indicates the preprocessing for all the sources
7654 that are not specified explicitly on other lines (order of the lines is not
7655 significant). It is an error to have two lines with the same file name or two
7656 lines starting with the character '*'.
7657
7658 @noindent
7659 After the file name or the character '*', another optional literal string
7660 indicating the file name of the definition file to be used for preprocessing
7661 (@pxref{Form of Definitions File}). The definition files are found by the
7662 compiler in one of the source directories. In some cases, when compiling
7663 a source in a directory other than the current directory, if the definition
7664 file is in the current directory, it may be necessary to add the current
7665 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7666 the compiler would not find the definition file.
7667
7668 @noindent
7669 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7670 be found. Those ^switches^switches^ are:
7671
7672 @table @code
7673
7674 @item -b
7675 Causes both preprocessor lines and the lines deleted by
7676 preprocessing to be replaced by blank lines, preserving the line number.
7677 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7678 it cancels the effect of @option{-c}.
7679
7680 @item -c
7681 Causes both preprocessor lines and the lines deleted
7682 by preprocessing to be retained as comments marked
7683 with the special string ``@code{--! }''.
7684
7685 @item -Dsymbol=value
7686 Define or redefine a symbol, associated with value. A symbol is an Ada
7687 identifier, or an Ada reserved word, with the exception of @code{if},
7688 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7689 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7690 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7691 same name defined in a definition file.
7692
7693 @item -s
7694 Causes a sorted list of symbol names and values to be
7695 listed on the standard output file.
7696
7697 @item -u
7698 Causes undefined symbols to be treated as having the value @code{FALSE}
7699 in the context
7700 of a preprocessor test. In the absence of this option, an undefined symbol in
7701 a @code{#if} or @code{#elsif} test will be treated as an error.
7702
7703 @end table
7704
7705 @noindent
7706 Examples of valid lines in a preprocessor data file:
7707
7708 @smallexample
7709   "toto.adb"  "prep.def" -u
7710   --  preprocess "toto.adb", using definition file "prep.def",
7711   --  undefined symbol are False.
7712
7713   * -c -DVERSION=V101
7714   --  preprocess all other sources without a definition file;
7715   --  suppressed lined are commented; symbol VERSION has the value V101.
7716
7717   "titi.adb" "prep2.def" -s
7718   --  preprocess "titi.adb", using definition file "prep2.def";
7719   --  list all symbols with their values.
7720 @end smallexample
7721
7722 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7723 @cindex @option{-gnateD} (@command{gcc})
7724 Define or redefine a preprocessing symbol, associated with value. If no value
7725 is given on the command line, then the value of the symbol is @code{True}.
7726 A symbol is an identifier, following normal Ada (case-insensitive)
7727 rules for its syntax, and value is either an arbitrary string between double
7728 quotes or any sequence (including an empty sequence) of characters from the
7729 set (letters, digits, period, underline).
7730 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7731 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7732
7733 @ifclear vms
7734 @noindent
7735 Examples:
7736
7737 @smallexample
7738    -gnateDToto=Titi
7739    -gnateDFoo
7740    -gnateDFoo=\"Foo-Bar\"
7741 @end smallexample
7742 @end ifclear
7743
7744 @noindent
7745 A symbol declared with this ^switch^switch^ on the command line replaces a
7746 symbol with the same name either in a definition file or specified with a
7747 ^switch^switch^ -D in the preprocessor data file.
7748
7749 @noindent
7750 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7751
7752 @item -gnateG
7753 When integrated preprocessing is performed and the preprocessor modifies
7754 the source text, write the result of this preprocessing into a file
7755 <source>^.prep^_prep^.
7756
7757 @end table
7758
7759 @node Code Generation Control
7760 @subsection Code Generation Control
7761
7762 @noindent
7763
7764 The GCC technology provides a wide range of target dependent
7765 @option{-m} switches for controlling
7766 details of code generation with respect to different versions of
7767 architectures. This includes variations in instruction sets (e.g.@:
7768 different members of the power pc family), and different requirements
7769 for optimal arrangement of instructions (e.g.@: different members of
7770 the x86 family). The list of available @option{-m} switches may be
7771 found in the GCC documentation.
7772
7773 Use of these @option{-m} switches may in some cases result in improved
7774 code performance.
7775
7776 The @value{EDITION} technology is tested and qualified without any
7777 @option{-m} switches,
7778 so generally the most reliable approach is to avoid the use of these
7779 switches. However, we generally expect most of these switches to work
7780 successfully with @value{EDITION}, and many customers have reported successful
7781 use of these options.
7782
7783 Our general advice is to avoid the use of @option{-m} switches unless
7784 special needs lead to requirements in this area. In particular,
7785 there is no point in using @option{-m} switches to improve performance
7786 unless you actually see a performance improvement.
7787
7788 @ifset vms
7789 @node Return Codes
7790 @subsection Return Codes
7791 @cindex Return Codes
7792 @cindex @option{/RETURN_CODES=VMS}
7793
7794 @noindent
7795 On VMS, GNAT compiled programs return POSIX-style codes by default,
7796 e.g.@: @option{/RETURN_CODES=POSIX}.
7797
7798 To enable VMS style return codes, use GNAT BIND and LINK with the option
7799 @option{/RETURN_CODES=VMS}. For example:
7800
7801 @smallexample
7802 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7803 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7804 @end smallexample
7805
7806 @noindent
7807 Programs built with /RETURN_CODES=VMS are suitable to be called in
7808 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7809 are suitable for spawning with appropriate GNAT RTL routines.
7810
7811 @end ifset
7812
7813 @node Search Paths and the Run-Time Library (RTL)
7814 @section Search Paths and the Run-Time Library (RTL)
7815
7816 @noindent
7817 With the GNAT source-based library system, the compiler must be able to
7818 find source files for units that are needed by the unit being compiled.
7819 Search paths are used to guide this process.
7820
7821 The compiler compiles one source file whose name must be given
7822 explicitly on the command line. In other words, no searching is done
7823 for this file. To find all other source files that are needed (the most
7824 common being the specs of units), the compiler examines the following
7825 directories, in the following order:
7826
7827 @enumerate
7828 @item
7829 The directory containing the source file of the main unit being compiled
7830 (the file name on the command line).
7831
7832 @item
7833 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7834 @command{gcc} command line, in the order given.
7835
7836 @item
7837 @findex ADA_PRJ_INCLUDE_FILE
7838 Each of the directories listed in the text file whose name is given
7839 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7840
7841 @noindent
7842 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7843 driver when project files are used. It should not normally be set
7844 by other means.
7845
7846 @item
7847 @findex ADA_INCLUDE_PATH
7848 Each of the directories listed in the value of the
7849 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7850 @ifclear vms
7851 Construct this value
7852 exactly as the @env{PATH} environment variable: a list of directory
7853 names separated by colons (semicolons when working with the NT version).
7854 @end ifclear
7855 @ifset vms
7856 Normally, define this value as a logical name containing a comma separated
7857 list of directory names.
7858
7859 This variable can also be defined by means of an environment string
7860 (an argument to the HP C exec* set of functions).
7861
7862 Logical Name:
7863 @smallexample
7864 DEFINE ANOTHER_PATH FOO:[BAG]
7865 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7866 @end smallexample
7867
7868 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7869 first, followed by the standard Ada
7870 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7871 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7872 (Text_IO, Sequential_IO, etc)
7873 instead of the standard Ada packages. Thus, in order to get the standard Ada
7874 packages by default, ADA_INCLUDE_PATH must be redefined.
7875 @end ifset
7876
7877 @item
7878 The content of the @file{ada_source_path} file which is part of the GNAT
7879 installation tree and is used to store standard libraries such as the
7880 GNAT Run Time Library (RTL) source files.
7881 @ifclear vms
7882 @ref{Installing a library}
7883 @end ifclear
7884 @end enumerate
7885
7886 @noindent
7887 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7888 inhibits the use of the directory
7889 containing the source file named in the command line. You can still
7890 have this directory on your search path, but in this case it must be
7891 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7892
7893 Specifying the switch @option{-nostdinc}
7894 inhibits the search of the default location for the GNAT Run Time
7895 Library (RTL) source files.
7896
7897 The compiler outputs its object files and ALI files in the current
7898 working directory.
7899 @ifclear vms
7900 Caution: The object file can be redirected with the @option{-o} switch;
7901 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7902 so the @file{ALI} file will not go to the right place. Therefore, you should
7903 avoid using the @option{-o} switch.
7904 @end ifclear
7905
7906 @findex System.IO
7907 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7908 children make up the GNAT RTL, together with the simple @code{System.IO}
7909 package used in the @code{"Hello World"} example. The sources for these units
7910 are needed by the compiler and are kept together in one directory. Not
7911 all of the bodies are needed, but all of the sources are kept together
7912 anyway. In a normal installation, you need not specify these directory
7913 names when compiling or binding. Either the environment variables or
7914 the built-in defaults cause these files to be found.
7915
7916 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7917 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7918 consisting of child units of @code{GNAT}. This is a collection of generally
7919 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7920 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7921
7922 Besides simplifying access to the RTL, a major use of search paths is
7923 in compiling sources from multiple directories. This can make
7924 development environments much more flexible.
7925
7926 @node Order of Compilation Issues
7927 @section Order of Compilation Issues
7928
7929 @noindent
7930 If, in our earlier example, there was a spec for the @code{hello}
7931 procedure, it would be contained in the file @file{hello.ads}; yet this
7932 file would not have to be explicitly compiled. This is the result of the
7933 model we chose to implement library management. Some of the consequences
7934 of this model are as follows:
7935
7936 @itemize @bullet
7937 @item
7938 There is no point in compiling specs (except for package
7939 specs with no bodies) because these are compiled as needed by clients. If
7940 you attempt a useless compilation, you will receive an error message.
7941 It is also useless to compile subunits because they are compiled as needed
7942 by the parent.
7943
7944 @item
7945 There are no order of compilation requirements: performing a
7946 compilation never obsoletes anything. The only way you can obsolete
7947 something and require recompilations is to modify one of the
7948 source files on which it depends.
7949
7950 @item
7951 There is no library as such, apart from the ALI files
7952 (@pxref{The Ada Library Information Files}, for information on the format
7953 of these files). For now we find it convenient to create separate ALI files,
7954 but eventually the information therein may be incorporated into the object
7955 file directly.
7956
7957 @item
7958 When you compile a unit, the source files for the specs of all units
7959 that it @code{with}'s, all its subunits, and the bodies of any generics it
7960 instantiates must be available (reachable by the search-paths mechanism
7961 described above), or you will receive a fatal error message.
7962 @end itemize
7963
7964 @node Examples
7965 @section Examples
7966
7967 @noindent
7968 The following are some typical Ada compilation command line examples:
7969
7970 @table @code
7971 @item $ gcc -c xyz.adb
7972 Compile body in file @file{xyz.adb} with all default options.
7973
7974 @ifclear vms
7975 @item $ gcc -c -O2 -gnata xyz-def.adb
7976 @end ifclear
7977 @ifset vms
7978 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7979 @end ifset
7980
7981 Compile the child unit package in file @file{xyz-def.adb} with extensive
7982 optimizations, and pragma @code{Assert}/@code{Debug} statements
7983 enabled.
7984
7985 @item $ gcc -c -gnatc abc-def.adb
7986 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7987 mode.
7988 @end table
7989
7990 @node Binding with gnatbind
7991 @chapter Binding with @code{gnatbind}
7992 @findex gnatbind
7993
7994 @menu
7995 * Running gnatbind::
7996 * Switches for gnatbind::
7997 * Command-Line Access::
7998 * Search Paths for gnatbind::
7999 * Examples of gnatbind Usage::
8000 @end menu
8001
8002 @noindent
8003 This chapter describes the GNAT binder, @code{gnatbind}, which is used
8004 to bind compiled GNAT objects.
8005
8006 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
8007 driver (see @ref{The GNAT Driver and Project Files}).
8008
8009 The @code{gnatbind} program performs four separate functions:
8010
8011 @enumerate
8012 @item
8013 Checks that a program is consistent, in accordance with the rules in
8014 Chapter 10 of the Ada Reference Manual. In particular, error
8015 messages are generated if a program uses inconsistent versions of a
8016 given unit.
8017
8018 @item
8019 Checks that an acceptable order of elaboration exists for the program
8020 and issues an error message if it cannot find an order of elaboration
8021 that satisfies the rules in Chapter 10 of the Ada Language Manual.
8022
8023 @item
8024 Generates a main program incorporating the given elaboration order.
8025 This program is a small Ada package (body and spec) that
8026 must be subsequently compiled
8027 using the GNAT compiler. The necessary compilation step is usually
8028 performed automatically by @command{gnatlink}. The two most important
8029 functions of this program
8030 are to call the elaboration routines of units in an appropriate order
8031 and to call the main program.
8032
8033 @item
8034 Determines the set of object files required by the given main program.
8035 This information is output in the forms of comments in the generated program,
8036 to be read by the @command{gnatlink} utility used to link the Ada application.
8037 @end enumerate
8038
8039 @node Running gnatbind
8040 @section Running @code{gnatbind}
8041
8042 @noindent
8043 The form of the @code{gnatbind} command is
8044
8045 @smallexample
8046 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8047 @c Expanding @ovar macro inline (explanation in macro def comments)
8048 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8049 @end smallexample
8050
8051 @noindent
8052 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8053 unit body. @code{gnatbind} constructs an Ada
8054 package in two files whose names are
8055 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8056 For example, if given the
8057 parameter @file{hello.ali}, for a main program contained in file
8058 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8059 and @file{b~hello.adb}.
8060
8061 When doing consistency checking, the binder takes into consideration
8062 any source files it can locate. For example, if the binder determines
8063 that the given main program requires the package @code{Pack}, whose
8064 @file{.ALI}
8065 file is @file{pack.ali} and whose corresponding source spec file is
8066 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8067 (using the same search path conventions as previously described for the
8068 @command{gcc} command). If it can locate this source file, it checks that
8069 the time stamps
8070 or source checksums of the source and its references to in @file{ALI} files
8071 match. In other words, any @file{ALI} files that mentions this spec must have
8072 resulted from compiling this version of the source file (or in the case
8073 where the source checksums match, a version close enough that the
8074 difference does not matter).
8075
8076 @cindex Source files, use by binder
8077 The effect of this consistency checking, which includes source files, is
8078 that the binder ensures that the program is consistent with the latest
8079 version of the source files that can be located at bind time. Editing a
8080 source file without compiling files that depend on the source file cause
8081 error messages to be generated by the binder.
8082
8083 For example, suppose you have a main program @file{hello.adb} and a
8084 package @code{P}, from file @file{p.ads} and you perform the following
8085 steps:
8086
8087 @enumerate
8088 @item
8089 Enter @code{gcc -c hello.adb} to compile the main program.
8090
8091 @item
8092 Enter @code{gcc -c p.ads} to compile package @code{P}.
8093
8094 @item
8095 Edit file @file{p.ads}.
8096
8097 @item
8098 Enter @code{gnatbind hello}.
8099 @end enumerate
8100
8101 @noindent
8102 At this point, the file @file{p.ali} contains an out-of-date time stamp
8103 because the file @file{p.ads} has been edited. The attempt at binding
8104 fails, and the binder generates the following error messages:
8105
8106 @smallexample
8107 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8108 error: "p.ads" has been modified and must be recompiled
8109 @end smallexample
8110
8111 @noindent
8112 Now both files must be recompiled as indicated, and then the bind can
8113 succeed, generating a main program. You need not normally be concerned
8114 with the contents of this file, but for reference purposes a sample
8115 binder output file is given in @ref{Example of Binder Output File}.
8116
8117 In most normal usage, the default mode of @command{gnatbind} which is to
8118 generate the main package in Ada, as described in the previous section.
8119 In particular, this means that any Ada programmer can read and understand
8120 the generated main program. It can also be debugged just like any other
8121 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8122 @command{gnatbind} and @command{gnatlink}.
8123
8124 @node Switches for gnatbind
8125 @section Switches for @command{gnatbind}
8126
8127 @noindent
8128 The following switches are available with @code{gnatbind}; details will
8129 be presented in subsequent sections.
8130
8131 @menu
8132 * Consistency-Checking Modes::
8133 * Binder Error Message Control::
8134 * Elaboration Control::
8135 * Output Control::
8136 * Dynamic Allocation Control::
8137 * Binding with Non-Ada Main Programs::
8138 * Binding Programs with No Main Subprogram::
8139 @end menu
8140
8141 @table @option
8142 @c !sort!
8143
8144 @item --version
8145 @cindex @option{--version} @command{gnatbind}
8146 Display Copyright and version, then exit disregarding all other options.
8147
8148 @item --help
8149 @cindex @option{--help} @command{gnatbind}
8150 If @option{--version} was not used, display usage, then exit disregarding
8151 all other options.
8152
8153 @item -a
8154 @cindex @option{-a} @command{gnatbind}
8155 Indicates that, if supported by the platform, the adainit procedure should
8156 be treated as an initialisation routine by the linker (a constructor). This
8157 is intended to be used by the Project Manager to automatically initialize
8158 shared Stand-Alone Libraries.
8159
8160 @item ^-aO^/OBJECT_SEARCH^
8161 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8162 Specify directory to be searched for ALI files.
8163
8164 @item ^-aI^/SOURCE_SEARCH^
8165 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8166 Specify directory to be searched for source file.
8167
8168 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8169 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8170 Output ALI list (to standard output or to the named file).
8171
8172 @item ^-b^/REPORT_ERRORS=BRIEF^
8173 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8174 Generate brief messages to @file{stderr} even if verbose mode set.
8175
8176 @item ^-c^/NOOUTPUT^
8177 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8178 Check only, no generation of binder output file.
8179
8180 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8181 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8182 This switch can be used to change the default task stack size value
8183 to a specified size @var{nn}, which is expressed in bytes by default, or
8184 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8185 with @var{m}.
8186 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8187 in effect, to completing all task specs with
8188 @smallexample @c ada
8189    pragma Storage_Size (nn);
8190 @end smallexample
8191 When they do not already have such a pragma.
8192
8193 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8194 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8195 This switch can be used to change the default secondary stack size value
8196 to a specified size @var{nn}, which is expressed in bytes by default, or
8197 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8198 with @var{m}.
8199
8200 The secondary stack is used to deal with functions that return a variable
8201 sized result, for example a function returning an unconstrained
8202 String. There are two ways in which this secondary stack is allocated.
8203
8204 For most targets, the secondary stack is growing on demand and is allocated
8205 as a chain of blocks in the heap. The -D option is not very
8206 relevant. It only give some control over the size of the allocated
8207 blocks (whose size is the minimum of the default secondary stack size value,
8208 and the actual size needed for the current allocation request).
8209
8210 For certain targets, notably VxWorks 653,
8211 the secondary stack is allocated by carving off a fixed ratio chunk of the
8212 primary task stack. The -D option is used to define the
8213 size of the environment task's secondary stack.
8214
8215 @item ^-e^/ELABORATION_DEPENDENCIES^
8216 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8217 Output complete list of elaboration-order dependencies.
8218
8219 @item ^-E^/STORE_TRACEBACKS^
8220 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8221 Store tracebacks in exception occurrences when the target supports it.
8222 @ignore
8223 @c The following may get moved to an appendix
8224 This option is currently supported on the following targets:
8225 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8226 @end ignore
8227 See also the packages @code{GNAT.Traceback} and
8228 @code{GNAT.Traceback.Symbolic} for more information.
8229 @ifclear vms
8230 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8231 @command{gcc} option.
8232 @end ifclear
8233
8234 @item ^-F^/FORCE_ELABS_FLAGS^
8235 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8236 Force the checks of elaboration flags. @command{gnatbind} does not normally
8237 generate checks of elaboration flags for the main executable, except when
8238 a Stand-Alone Library is used. However, there are cases when this cannot be
8239 detected by gnatbind. An example is importing an interface of a Stand-Alone
8240 Library through a pragma Import and only specifying through a linker switch
8241 this Stand-Alone Library. This switch is used to guarantee that elaboration
8242 flag checks are generated.
8243
8244 @item ^-h^/HELP^
8245 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8246 Output usage (help) information
8247
8248 @item ^-H32^/32_MALLOC^
8249 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8250 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8251 For further details see @ref{Dynamic Allocation Control}.
8252
8253 @item ^-H64^/64_MALLOC^
8254 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8255 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8256 @cindex @code{__gnat_malloc}
8257 For further details see @ref{Dynamic Allocation Control}.
8258
8259 @item ^-I^/SEARCH^
8260 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8261 Specify directory to be searched for source and ALI files.
8262
8263 @item ^-I-^/NOCURRENT_DIRECTORY^
8264 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8265 Do not look for sources in the current directory where @code{gnatbind} was
8266 invoked, and do not look for ALI files in the directory containing the
8267 ALI file named in the @code{gnatbind} command line.
8268
8269 @item ^-l^/ORDER_OF_ELABORATION^
8270 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8271 Output chosen elaboration order.
8272
8273 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8274 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8275 Bind the units for library building. In this case the adainit and
8276 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8277 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8278 ^@var{xxx}final^@var{XXX}FINAL^.
8279 Implies ^-n^/NOCOMPILE^.
8280 @ifclear vms
8281 (@xref{GNAT and Libraries}, for more details.)
8282 @end ifclear
8283 @ifset vms
8284 On OpenVMS, these init and final procedures are exported in uppercase
8285 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8286 the init procedure will be "TOTOINIT" and the exported name of the final
8287 procedure will be "TOTOFINAL".
8288 @end ifset
8289
8290 @item ^-Mxyz^/RENAME_MAIN=xyz^
8291 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8292 Rename generated main program from main to xyz. This option is
8293 supported on cross environments only.
8294
8295 @item ^-m^/ERROR_LIMIT=^@var{n}
8296 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8297 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8298 in the range 1..999999. The default value if no switch is
8299 given is 9999. If the number of warnings reaches this limit, then a
8300 message is output and further warnings are suppressed, the bind
8301 continues in this case. If the number of errors reaches this
8302 limit, then a message is output and the bind is abandoned.
8303 A value of zero means that no limit is enforced. The equal
8304 sign is optional.
8305
8306 @ifset unw
8307 Furthermore, under Windows, the sources pointed to by the libraries path
8308 set in the registry are not searched for.
8309 @end ifset
8310
8311 @item ^-n^/NOMAIN^
8312 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8313 No main program.
8314
8315 @item -nostdinc
8316 @cindex @option{-nostdinc} (@command{gnatbind})
8317 Do not look for sources in the system default directory.
8318
8319 @item -nostdlib
8320 @cindex @option{-nostdlib} (@command{gnatbind})
8321 Do not look for library files in the system default directory.
8322
8323 @item --RTS=@var{rts-path}
8324 @cindex @option{--RTS} (@code{gnatbind})
8325 Specifies the default location of the runtime library. Same meaning as the
8326 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8327
8328 @item ^-o ^/OUTPUT=^@var{file}
8329 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8330 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8331 Note that if this option is used, then linking must be done manually,
8332 gnatlink cannot be used.
8333
8334 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8335 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8336 Output object list (to standard output or to the named file).
8337
8338 @item ^-p^/PESSIMISTIC_ELABORATION^
8339 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8340 Pessimistic (worst-case) elaboration order
8341
8342 @item ^-P^-P^
8343 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8344 Generate binder file suitable for CodePeer.
8345
8346 @item ^-R^-R^
8347 @cindex @option{^-R^-R^} (@command{gnatbind})
8348 Output closure source list.
8349
8350 @item ^-s^/READ_SOURCES=ALL^
8351 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8352 Require all source files to be present.
8353
8354 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8355 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8356 Specifies the value to be used when detecting uninitialized scalar
8357 objects with pragma Initialize_Scalars.
8358 The @var{xxx} ^string specified with the switch^option^ may be either
8359 @itemize @bullet
8360 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8361 @item ``@option{^lo^LOW^}'' for the lowest possible value
8362 @item ``@option{^hi^HIGH^}'' for the highest possible value
8363 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8364 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8365 @end itemize
8366
8367 In addition, you can specify @option{-Sev} to indicate that the value is
8368 to be set at run time. In this case, the program will look for an environment
8369 @cindex GNAT_INIT_SCALARS
8370 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8371 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8372 If no environment variable is found, or if it does not have a valid value,
8373 then the default is @option{in} (invalid values).
8374
8375 @ifclear vms
8376 @item -static
8377 @cindex @option{-static} (@code{gnatbind})
8378 Link against a static GNAT run time.
8379
8380 @item -shared
8381 @cindex @option{-shared} (@code{gnatbind})
8382 Link against a shared GNAT run time when available.
8383 @end ifclear
8384
8385 @item ^-t^/NOTIME_STAMP_CHECK^
8386 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8387 Tolerate time stamp and other consistency errors
8388
8389 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8390 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8391 Set the time slice value to @var{n} milliseconds. If the system supports
8392 the specification of a specific time slice value, then the indicated value
8393 is used. If the system does not support specific time slice values, but
8394 does support some general notion of round-robin scheduling, then any
8395 nonzero value will activate round-robin scheduling.
8396
8397 A value of zero is treated specially. It turns off time
8398 slicing, and in addition, indicates to the tasking run time that the
8399 semantics should match as closely as possible the Annex D
8400 requirements of the Ada RM, and in particular sets the default
8401 scheduling policy to @code{FIFO_Within_Priorities}.
8402
8403 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8404 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8405 Enable dynamic stack usage, with @var{n} results stored and displayed
8406 at program termination. A result is generated when a task
8407 terminates. Results that can't be stored are displayed on the fly, at
8408 task termination. This option is currently not supported on Itanium
8409 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8410
8411 @item ^-v^/REPORT_ERRORS=VERBOSE^
8412 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8413 Verbose mode. Write error messages, header, summary output to
8414 @file{stdout}.
8415
8416 @ifclear vms
8417 @item -w@var{x}
8418 @cindex @option{-w} (@code{gnatbind})
8419 Warning mode (@var{x}=s/e for suppress/treat as error)
8420 @end ifclear
8421
8422 @ifset vms
8423 @item /WARNINGS=NORMAL
8424 @cindex @option{/WARNINGS} (@code{gnatbind})
8425 Normal warnings mode. Warnings are issued but ignored
8426
8427 @item /WARNINGS=SUPPRESS
8428 @cindex @option{/WARNINGS} (@code{gnatbind})
8429 All warning messages are suppressed
8430
8431 @item /WARNINGS=ERROR
8432 @cindex @option{/WARNINGS} (@code{gnatbind})
8433 Warning messages are treated as fatal errors
8434 @end ifset
8435
8436 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8437 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8438 Override default wide character encoding for standard Text_IO files.
8439
8440 @item ^-x^/READ_SOURCES=NONE^
8441 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8442 Exclude source files (check object consistency only).
8443
8444 @ifset vms
8445 @item /READ_SOURCES=AVAILABLE
8446 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8447 Default mode, in which sources are checked for consistency only if
8448 they are available.
8449 @end ifset
8450
8451 @item ^-y^/ENABLE_LEAP_SECONDS^
8452 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8453 Enable leap seconds support in @code{Ada.Calendar} and its children.
8454
8455 @item ^-z^/ZERO_MAIN^
8456 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8457 No main subprogram.
8458 @end table
8459
8460 @ifclear vms
8461 @noindent
8462 You may obtain this listing of switches by running @code{gnatbind} with
8463 no arguments.
8464 @end ifclear
8465
8466 @node Consistency-Checking Modes
8467 @subsection Consistency-Checking Modes
8468
8469 @noindent
8470 As described earlier, by default @code{gnatbind} checks
8471 that object files are consistent with one another and are consistent
8472 with any source files it can locate. The following switches control binder
8473 access to sources.
8474
8475 @table @option
8476 @c !sort!
8477 @item ^-s^/READ_SOURCES=ALL^
8478 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8479 Require source files to be present. In this mode, the binder must be
8480 able to locate all source files that are referenced, in order to check
8481 their consistency. In normal mode, if a source file cannot be located it
8482 is simply ignored. If you specify this switch, a missing source
8483 file is an error.
8484
8485 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8486 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8487 Override default wide character encoding for standard Text_IO files.
8488 Normally the default wide character encoding method used for standard
8489 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8490 the main source input (see description of switch
8491 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8492 use of this switch for the binder (which has the same set of
8493 possible arguments) overrides this default as specified.
8494
8495 @item ^-x^/READ_SOURCES=NONE^
8496 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8497 Exclude source files. In this mode, the binder only checks that ALI
8498 files are consistent with one another. Source files are not accessed.
8499 The binder runs faster in this mode, and there is still a guarantee that
8500 the resulting program is self-consistent.
8501 If a source file has been edited since it was last compiled, and you
8502 specify this switch, the binder will not detect that the object
8503 file is out of date with respect to the source file. Note that this is the
8504 mode that is automatically used by @command{gnatmake} because in this
8505 case the checking against sources has already been performed by
8506 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8507
8508 @ifset vms
8509 @item /READ_SOURCES=AVAILABLE
8510 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8511 This is the default mode in which source files are checked if they are
8512 available, and ignored if they are not available.
8513 @end ifset
8514 @end table
8515
8516 @node Binder Error Message Control
8517 @subsection Binder Error Message Control
8518
8519 @noindent
8520 The following switches provide control over the generation of error
8521 messages from the binder:
8522
8523 @table @option
8524 @c !sort!
8525 @item ^-v^/REPORT_ERRORS=VERBOSE^
8526 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8527 Verbose mode. In the normal mode, brief error messages are generated to
8528 @file{stderr}. If this switch is present, a header is written
8529 to @file{stdout} and any error messages are directed to @file{stdout}.
8530 All that is written to @file{stderr} is a brief summary message.
8531
8532 @item ^-b^/REPORT_ERRORS=BRIEF^
8533 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8534 Generate brief error messages to @file{stderr} even if verbose mode is
8535 specified. This is relevant only when used with the
8536 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8537
8538 @ifclear vms
8539 @item -m@var{n}
8540 @cindex @option{-m} (@code{gnatbind})
8541 Limits the number of error messages to @var{n}, a decimal integer in the
8542 range 1-999. The binder terminates immediately if this limit is reached.
8543
8544 @item -M@var{xxx}
8545 @cindex @option{-M} (@code{gnatbind})
8546 Renames the generated main program from @code{main} to @code{xxx}.
8547 This is useful in the case of some cross-building environments, where
8548 the actual main program is separate from the one generated
8549 by @code{gnatbind}.
8550 @end ifclear
8551
8552 @item ^-ws^/WARNINGS=SUPPRESS^
8553 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8554 @cindex Warnings
8555 Suppress all warning messages.
8556
8557 @item ^-we^/WARNINGS=ERROR^
8558 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8559 Treat any warning messages as fatal errors.
8560
8561 @ifset vms
8562 @item /WARNINGS=NORMAL
8563 Standard mode with warnings generated, but warnings do not get treated
8564 as errors.
8565 @end ifset
8566
8567 @item ^-t^/NOTIME_STAMP_CHECK^
8568 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8569 @cindex Time stamp checks, in binder
8570 @cindex Binder consistency checks
8571 @cindex Consistency checks, in binder
8572 The binder performs a number of consistency checks including:
8573
8574 @itemize @bullet
8575 @item
8576 Check that time stamps of a given source unit are consistent
8577 @item
8578 Check that checksums of a given source unit are consistent
8579 @item
8580 Check that consistent versions of @code{GNAT} were used for compilation
8581 @item
8582 Check consistency of configuration pragmas as required
8583 @end itemize
8584
8585 @noindent
8586 Normally failure of such checks, in accordance with the consistency
8587 requirements of the Ada Reference Manual, causes error messages to be
8588 generated which abort the binder and prevent the output of a binder
8589 file and subsequent link to obtain an executable.
8590
8591 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8592 into warnings, so that
8593 binding and linking can continue to completion even in the presence of such
8594 errors. The result may be a failed link (due to missing symbols), or a
8595 non-functional executable which has undefined semantics.
8596 @emph{This means that
8597 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8598 with extreme care.}
8599 @end table
8600
8601 @node Elaboration Control
8602 @subsection Elaboration Control
8603
8604 @noindent
8605 The following switches provide additional control over the elaboration
8606 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8607
8608 @table @option
8609 @item ^-p^/PESSIMISTIC_ELABORATION^
8610 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8611 Normally the binder attempts to choose an elaboration order that is
8612 likely to minimize the likelihood of an elaboration order error resulting
8613 in raising a @code{Program_Error} exception. This switch reverses the
8614 action of the binder, and requests that it deliberately choose an order
8615 that is likely to maximize the likelihood of an elaboration error.
8616 This is useful in ensuring portability and avoiding dependence on
8617 accidental fortuitous elaboration ordering.
8618
8619 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8620 switch if dynamic
8621 elaboration checking is used (@option{-gnatE} switch used for compilation).
8622 This is because in the default static elaboration mode, all necessary
8623 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8624 These implicit pragmas are still respected by the binder in
8625 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8626 safe elaboration order is assured.
8627
8628 Note that @option{^-p^/PESSIMISTIC_ELABORATION^} is not intended for
8629 production use; it is more for debugging/experimental use.
8630 @end table
8631
8632 @node Output Control
8633 @subsection Output Control
8634
8635 @noindent
8636 The following switches allow additional control over the output
8637 generated by the binder.
8638
8639 @table @option
8640 @c !sort!
8641
8642 @item ^-c^/NOOUTPUT^
8643 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8644 Check only. Do not generate the binder output file. In this mode the
8645 binder performs all error checks but does not generate an output file.
8646
8647 @item ^-e^/ELABORATION_DEPENDENCIES^
8648 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8649 Output complete list of elaboration-order dependencies, showing the
8650 reason for each dependency. This output can be rather extensive but may
8651 be useful in diagnosing problems with elaboration order. The output is
8652 written to @file{stdout}.
8653
8654 @item ^-h^/HELP^
8655 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8656 Output usage information. The output is written to @file{stdout}.
8657
8658 @item ^-K^/LINKER_OPTION_LIST^
8659 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8660 Output linker options to @file{stdout}. Includes library search paths,
8661 contents of pragmas Ident and Linker_Options, and libraries added
8662 by @code{gnatbind}.
8663
8664 @item ^-l^/ORDER_OF_ELABORATION^
8665 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8666 Output chosen elaboration order. The output is written to @file{stdout}.
8667
8668 @item ^-O^/OBJECT_LIST^
8669 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8670 Output full names of all the object files that must be linked to provide
8671 the Ada component of the program. The output is written to @file{stdout}.
8672 This list includes the files explicitly supplied and referenced by the user
8673 as well as implicitly referenced run-time unit files. The latter are
8674 omitted if the corresponding units reside in shared libraries. The
8675 directory names for the run-time units depend on the system configuration.
8676
8677 @item ^-o ^/OUTPUT=^@var{file}
8678 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8679 Set name of output file to @var{file} instead of the normal
8680 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8681 binder generated body filename.
8682 Note that if this option is used, then linking must be done manually.
8683 It is not possible to use gnatlink in this case, since it cannot locate
8684 the binder file.
8685
8686 @item ^-r^/RESTRICTION_LIST^
8687 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8688 Generate list of @code{pragma Restrictions} that could be applied to
8689 the current unit. This is useful for code audit purposes, and also may
8690 be used to improve code generation in some cases.
8691
8692 @end table
8693
8694 @node Dynamic Allocation Control
8695 @subsection Dynamic Allocation Control
8696
8697 @noindent
8698 The heap control switches -- @option{-H32} and @option{-H64} --
8699 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8700 They only affect compiler-generated allocations via @code{__gnat_malloc};
8701 explicit calls to @code{malloc} and related functions from the C
8702 run-time library are unaffected.
8703
8704 @table @option
8705 @item -H32
8706 Allocate memory on 32-bit heap
8707
8708 @item -H64
8709 Allocate memory on 64-bit heap.  This is the default
8710 unless explicitly overridden by a @code{'Size} clause on the access type.
8711 @end table
8712
8713 @ifset vms
8714 @noindent
8715 See also @ref{Access types and 32/64-bit allocation}.
8716 @end ifset
8717 @ifclear vms
8718 @noindent
8719 These switches are only effective on VMS platforms.
8720 @end ifclear
8721
8722
8723 @node Binding with Non-Ada Main Programs
8724 @subsection Binding with Non-Ada Main Programs
8725
8726 @noindent
8727 In our description so far we have assumed that the main
8728 program is in Ada, and that the task of the binder is to generate a
8729 corresponding function @code{main} that invokes this Ada main
8730 program. GNAT also supports the building of executable programs where
8731 the main program is not in Ada, but some of the called routines are
8732 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8733 The following switch is used in this situation:
8734
8735 @table @option
8736 @item ^-n^/NOMAIN^
8737 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8738 No main program. The main program is not in Ada.
8739 @end table
8740
8741 @noindent
8742 In this case, most of the functions of the binder are still required,
8743 but instead of generating a main program, the binder generates a file
8744 containing the following callable routines:
8745
8746 @table @code
8747 @item adainit
8748 @findex adainit
8749 You must call this routine to initialize the Ada part of the program by
8750 calling the necessary elaboration routines. A call to @code{adainit} is
8751 required before the first call to an Ada subprogram.
8752
8753 Note that it is assumed that the basic execution environment must be setup
8754 to be appropriate for Ada execution at the point where the first Ada
8755 subprogram is called. In particular, if the Ada code will do any
8756 floating-point operations, then the FPU must be setup in an appropriate
8757 manner. For the case of the x86, for example, full precision mode is
8758 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8759 that the FPU is in the right state.
8760
8761 @item adafinal
8762 @findex adafinal
8763 You must call this routine to perform any library-level finalization
8764 required by the Ada subprograms. A call to @code{adafinal} is required
8765 after the last call to an Ada subprogram, and before the program
8766 terminates.
8767 @end table
8768
8769 @noindent
8770 If the @option{^-n^/NOMAIN^} switch
8771 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8772 @cindex Binder, multiple input files
8773 is given, more than one ALI file may appear on
8774 the command line for @code{gnatbind}. The normal @dfn{closure}
8775 calculation is performed for each of the specified units. Calculating
8776 the closure means finding out the set of units involved by tracing
8777 @code{with} references. The reason it is necessary to be able to
8778 specify more than one ALI file is that a given program may invoke two or
8779 more quite separate groups of Ada units.
8780
8781 The binder takes the name of its output file from the last specified ALI
8782 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8783 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8784 The output is an Ada unit in source form that can be compiled with GNAT.
8785 This compilation occurs automatically as part of the @command{gnatlink}
8786 processing.
8787
8788 Currently the GNAT run time requires a FPU using 80 bits mode
8789 precision. Under targets where this is not the default it is required to
8790 call GNAT.Float_Control.Reset before using floating point numbers (this
8791 include float computation, float input and output) in the Ada code. A
8792 side effect is that this could be the wrong mode for the foreign code
8793 where floating point computation could be broken after this call.
8794
8795 @node Binding Programs with No Main Subprogram
8796 @subsection Binding Programs with No Main Subprogram
8797
8798 @noindent
8799 It is possible to have an Ada program which does not have a main
8800 subprogram. This program will call the elaboration routines of all the
8801 packages, then the finalization routines.
8802
8803 The following switch is used to bind programs organized in this manner:
8804
8805 @table @option
8806 @item ^-z^/ZERO_MAIN^
8807 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8808 Normally the binder checks that the unit name given on the command line
8809 corresponds to a suitable main subprogram. When this switch is used,
8810 a list of ALI files can be given, and the execution of the program
8811 consists of elaboration of these units in an appropriate order. Note
8812 that the default wide character encoding method for standard Text_IO
8813 files is always set to Brackets if this switch is set (you can use
8814 the binder switch
8815 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8816 @end table
8817
8818 @node Command-Line Access
8819 @section Command-Line Access
8820
8821 @noindent
8822 The package @code{Ada.Command_Line} provides access to the command-line
8823 arguments and program name. In order for this interface to operate
8824 correctly, the two variables
8825
8826 @smallexample
8827 @group
8828 int gnat_argc;
8829 char **gnat_argv;
8830 @end group
8831 @end smallexample
8832
8833 @noindent
8834 @findex gnat_argv
8835 @findex gnat_argc
8836 are declared in one of the GNAT library routines. These variables must
8837 be set from the actual @code{argc} and @code{argv} values passed to the
8838 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8839 generates the C main program to automatically set these variables.
8840 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8841 set these variables. If they are not set, the procedures in
8842 @code{Ada.Command_Line} will not be available, and any attempt to use
8843 them will raise @code{Constraint_Error}. If command line access is
8844 required, your main program must set @code{gnat_argc} and
8845 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8846 it.
8847
8848 @node Search Paths for gnatbind
8849 @section Search Paths for @code{gnatbind}
8850
8851 @noindent
8852 The binder takes the name of an ALI file as its argument and needs to
8853 locate source files as well as other ALI files to verify object consistency.
8854
8855 For source files, it follows exactly the same search rules as @command{gcc}
8856 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8857 directories searched are:
8858
8859 @enumerate
8860 @item
8861 The directory containing the ALI file named in the command line, unless
8862 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8863
8864 @item
8865 All directories specified by @option{^-I^/SEARCH^}
8866 switches on the @code{gnatbind}
8867 command line, in the order given.
8868
8869 @item
8870 @findex ADA_PRJ_OBJECTS_FILE
8871 Each of the directories listed in the text file whose name is given
8872 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8873
8874 @noindent
8875 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8876 driver when project files are used. It should not normally be set
8877 by other means.
8878
8879 @item
8880 @findex ADA_OBJECTS_PATH
8881 Each of the directories listed in the value of the
8882 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8883 @ifset unw
8884 Construct this value
8885 exactly as the @env{PATH} environment variable: a list of directory
8886 names separated by colons (semicolons when working with the NT version
8887 of GNAT).
8888 @end ifset
8889 @ifset vms
8890 Normally, define this value as a logical name containing a comma separated
8891 list of directory names.
8892
8893 This variable can also be defined by means of an environment string
8894 (an argument to the HP C exec* set of functions).
8895
8896 Logical Name:
8897 @smallexample
8898 DEFINE ANOTHER_PATH FOO:[BAG]
8899 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8900 @end smallexample
8901
8902 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8903 first, followed by the standard Ada
8904 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8905 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8906 (Text_IO, Sequential_IO, etc)
8907 instead of the standard Ada packages. Thus, in order to get the standard Ada
8908 packages by default, ADA_OBJECTS_PATH must be redefined.
8909 @end ifset
8910
8911 @item
8912 The content of the @file{ada_object_path} file which is part of the GNAT
8913 installation tree and is used to store standard libraries such as the
8914 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8915 specified.
8916 @ifclear vms
8917 @ref{Installing a library}
8918 @end ifclear
8919 @end enumerate
8920
8921 @noindent
8922 In the binder the switch @option{^-I^/SEARCH^}
8923 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8924 is used to specify both source and
8925 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8926 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8927 instead if you want to specify
8928 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8929 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8930 if you want to specify library paths
8931 only. This means that for the binder
8932 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8933 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8934 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8935 The binder generates the bind file (a C language source file) in the
8936 current working directory.
8937
8938 @findex Ada
8939 @findex System
8940 @findex Interfaces
8941 @findex GNAT
8942 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8943 children make up the GNAT Run-Time Library, together with the package
8944 GNAT and its children, which contain a set of useful additional
8945 library functions provided by GNAT. The sources for these units are
8946 needed by the compiler and are kept together in one directory. The ALI
8947 files and object files generated by compiling the RTL are needed by the
8948 binder and the linker and are kept together in one directory, typically
8949 different from the directory containing the sources. In a normal
8950 installation, you need not specify these directory names when compiling
8951 or binding. Either the environment variables or the built-in defaults
8952 cause these files to be found.
8953
8954 Besides simplifying access to the RTL, a major use of search paths is
8955 in compiling sources from multiple directories. This can make
8956 development environments much more flexible.
8957
8958 @node Examples of gnatbind Usage
8959 @section Examples of @code{gnatbind} Usage
8960
8961 @noindent
8962 This section contains a number of examples of using the GNAT binding
8963 utility @code{gnatbind}.
8964
8965 @table @code
8966 @item gnatbind hello
8967 The main program @code{Hello} (source program in @file{hello.adb}) is
8968 bound using the standard switch settings. The generated main program is
8969 @file{b~hello.adb}. This is the normal, default use of the binder.
8970
8971 @ifclear vms
8972 @item gnatbind hello -o mainprog.adb
8973 @end ifclear
8974 @ifset vms
8975 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8976 @end ifset
8977 The main program @code{Hello} (source program in @file{hello.adb}) is
8978 bound using the standard switch settings. The generated main program is
8979 @file{mainprog.adb} with the associated spec in
8980 @file{mainprog.ads}. Note that you must specify the body here not the
8981 spec. Note that if this option is used, then linking must be done manually,
8982 since gnatlink will not be able to find the generated file.
8983 @end table
8984
8985 @c ------------------------------------
8986 @node Linking with gnatlink
8987 @chapter Linking with @command{gnatlink}
8988 @c ------------------------------------
8989 @findex gnatlink
8990
8991 @noindent
8992 This chapter discusses @command{gnatlink}, a tool that links
8993 an Ada program and builds an executable file. This utility
8994 invokes the system linker ^(via the @command{gcc} command)^^
8995 with a correct list of object files and library references.
8996 @command{gnatlink} automatically determines the list of files and
8997 references for the Ada part of a program. It uses the binder file
8998 generated by the @command{gnatbind} to determine this list.
8999
9000 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
9001 driver (see @ref{The GNAT Driver and Project Files}).
9002
9003 @menu
9004 * Running gnatlink::
9005 * Switches for gnatlink::
9006 @end menu
9007
9008 @node Running gnatlink
9009 @section Running @command{gnatlink}
9010
9011 @noindent
9012 The form of the @command{gnatlink} command is
9013
9014 @smallexample
9015 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
9016 @c            @ovar{non-Ada objects} @ovar{linker options}
9017 @c Expanding @ovar macro inline (explanation in macro def comments)
9018 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
9019            @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
9020
9021 @end smallexample
9022
9023 @noindent
9024 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
9025 non-Ada objects
9026 or linker options) may be in any order, provided that no non-Ada object may
9027 be mistaken for a main @file{ALI} file.
9028 Any file name @file{F} without the @file{.ali}
9029 extension will be taken as the main @file{ALI} file if a file exists
9030 whose name is the concatenation of @file{F} and @file{.ali}.
9031
9032 @noindent
9033 @file{@var{mainprog}.ali} references the ALI file of the main program.
9034 The @file{.ali} extension of this file can be omitted. From this
9035 reference, @command{gnatlink} locates the corresponding binder file
9036 @file{b~@var{mainprog}.adb} and, using the information in this file along
9037 with the list of non-Ada objects and linker options, constructs a
9038 linker command file to create the executable.
9039
9040 The arguments other than the @command{gnatlink} switches and the main
9041 @file{ALI} file are passed to the linker uninterpreted.
9042 They typically include the names of
9043 object files for units written in other languages than Ada and any library
9044 references required to resolve references in any of these foreign language
9045 units, or in @code{Import} pragmas in any Ada units.
9046
9047 @var{linker options} is an optional list of linker specific
9048 switches.
9049 The default linker called by gnatlink is @command{gcc} which in
9050 turn calls the appropriate system linker.
9051
9052 One useful option for the linker is @option{-s}: it reduces the size of the
9053 executable by removing all symbol table and relocation information from the
9054 executable.
9055
9056 Standard options for the linker such as @option{-lmy_lib} or
9057 @option{-Ldir} can be added as is.
9058 For options that are not recognized by
9059 @command{gcc} as linker options, use the @command{gcc} switches
9060 @option{-Xlinker} or @option{-Wl,}.
9061
9062 Refer to the GCC documentation for
9063 details.
9064
9065 Here is an example showing how to generate a linker map:
9066
9067 @smallexample
9068 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9069 @end smallexample
9070
9071 Using @var{linker options} it is possible to set the program stack and
9072 heap size.
9073 @ifset unw
9074 See @ref{Setting Stack Size from gnatlink} and
9075 @ref{Setting Heap Size from gnatlink}.
9076 @end ifset
9077
9078 @command{gnatlink} determines the list of objects required by the Ada
9079 program and prepends them to the list of objects passed to the linker.
9080 @command{gnatlink} also gathers any arguments set by the use of
9081 @code{pragma Linker_Options} and adds them to the list of arguments
9082 presented to the linker.
9083
9084 @ifset vms
9085 @command{gnatlink} accepts the following types of extra files on the command
9086 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9087 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9088 handled according to their extension.
9089 @end ifset
9090
9091 @node Switches for gnatlink
9092 @section Switches for @command{gnatlink}
9093
9094 @noindent
9095 The following switches are available with the @command{gnatlink} utility:
9096
9097 @table @option
9098 @c !sort!
9099
9100 @item --version
9101 @cindex @option{--version} @command{gnatlink}
9102 Display Copyright and version, then exit disregarding all other options.
9103
9104 @item --help
9105 @cindex @option{--help} @command{gnatlink}
9106 If @option{--version} was not used, display usage, then exit disregarding
9107 all other options.
9108
9109 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9110 @cindex Command line length
9111 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9112 On some targets, the command line length is limited, and @command{gnatlink}
9113 will generate a separate file for the linker if the list of object files
9114 is too long.
9115 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9116 to be generated even if
9117 the limit is not exceeded. This is useful in some cases to deal with
9118 special situations where the command line length is exceeded.
9119
9120 @item ^-g^/DEBUG^
9121 @cindex Debugging information, including
9122 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9123 The option to include debugging information causes the Ada bind file (in
9124 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9125 @option{^-g^/DEBUG^}.
9126 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9127 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9128 Without @option{^-g^/DEBUG^}, the binder removes these files by
9129 default. The same procedure apply if a C bind file was generated using
9130 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9131 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9132
9133 @item ^-n^/NOCOMPILE^
9134 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9135 Do not compile the file generated by the binder. This may be used when
9136 a link is rerun with different options, but there is no need to recompile
9137 the binder file.
9138
9139 @item ^-v^/VERBOSE^
9140 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9141 Causes additional information to be output, including a full list of the
9142 included object files. This switch option is most useful when you want
9143 to see what set of object files are being used in the link step.
9144
9145 @item ^-v -v^/VERBOSE/VERBOSE^
9146 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9147 Very verbose mode. Requests that the compiler operate in verbose mode when
9148 it compiles the binder file, and that the system linker run in verbose mode.
9149
9150 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9151 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9152 @var{exec-name} specifies an alternate name for the generated
9153 executable program. If this switch is omitted, the executable has the same
9154 name as the main unit. For example, @code{gnatlink try.ali} creates
9155 an executable called @file{^try^TRY.EXE^}.
9156
9157 @ifclear vms
9158 @item -b @var{target}
9159 @cindex @option{-b} (@command{gnatlink})
9160 Compile your program to run on @var{target}, which is the name of a
9161 system configuration. You must have a GNAT cross-compiler built if
9162 @var{target} is not the same as your host system.
9163
9164 @item -B@var{dir}
9165 @cindex @option{-B} (@command{gnatlink})
9166 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9167 from @var{dir} instead of the default location. Only use this switch
9168 when multiple versions of the GNAT compiler are available.
9169 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9170 for further details. You would normally use the @option{-b} or
9171 @option{-V} switch instead.
9172
9173 @item -M
9174 When linking an executable, create a map file. The name of the map file
9175 has the same name as the executable with extension ".map".
9176
9177 @item -M=mapfile
9178 When linking an executable, create a map file. The name of the map file is
9179 "mapfile".
9180
9181 @item --GCC=@var{compiler_name}
9182 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9183 Program used for compiling the binder file. The default is
9184 @command{gcc}. You need to use quotes around @var{compiler_name} if
9185 @code{compiler_name} contains spaces or other separator characters.
9186 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9187 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9188 inserted after your command name. Thus in the above example the compiler
9189 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9190 A limitation of this syntax is that the name and path name of the executable
9191 itself must not include any embedded spaces. If the compiler executable is
9192 different from the default one (gcc or <prefix>-gcc), then the back-end
9193 switches in the ALI file are not used to compile the binder generated source.
9194 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9195 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9196 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9197 is taken into account. However, all the additional switches are also taken
9198 into account. Thus,
9199 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9200 @option{--GCC="bar -x -y -z -t"}.
9201
9202 @item --LINK=@var{name}
9203 @cindex @option{--LINK=} (@command{gnatlink})
9204 @var{name} is the name of the linker to be invoked. This is especially
9205 useful in mixed language programs since languages such as C++ require
9206 their own linker to be used. When this switch is omitted, the default
9207 name for the linker is @command{gcc}. When this switch is used, the
9208 specified linker is called instead of @command{gcc} with exactly the same
9209 parameters that would have been passed to @command{gcc} so if the desired
9210 linker requires different parameters it is necessary to use a wrapper
9211 script that massages the parameters before invoking the real linker. It
9212 may be useful to control the exact invocation by using the verbose
9213 switch.
9214
9215 @end ifclear
9216
9217 @ifset vms
9218 @item /DEBUG=TRACEBACK
9219 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9220 This qualifier causes sufficient information to be included in the
9221 executable file to allow a traceback, but does not include the full
9222 symbol information needed by the debugger.
9223
9224 @item /IDENTIFICATION="<string>"
9225 @code{"<string>"} specifies the string to be stored in the image file
9226 identification field in the image header.
9227 It overrides any pragma @code{Ident} specified string.
9228
9229 @item /NOINHIBIT-EXEC
9230 Generate the executable file even if there are linker warnings.
9231
9232 @item /NOSTART_FILES
9233 Don't link in the object file containing the ``main'' transfer address.
9234 Used when linking with a foreign language main program compiled with an
9235 HP compiler.
9236
9237 @item /STATIC
9238 Prefer linking with object libraries over sharable images, even without
9239 /DEBUG.
9240 @end ifset
9241
9242 @end table
9243
9244 @node The GNAT Make Program gnatmake
9245 @chapter The GNAT Make Program @command{gnatmake}
9246 @findex gnatmake
9247
9248 @menu
9249 * Running gnatmake::
9250 * Switches for gnatmake::
9251 * Mode Switches for gnatmake::
9252 * Notes on the Command Line::
9253 * How gnatmake Works::
9254 * Examples of gnatmake Usage::
9255 @end menu
9256 @noindent
9257 A typical development cycle when working on an Ada program consists of
9258 the following steps:
9259
9260 @enumerate
9261 @item
9262 Edit some sources to fix bugs.
9263
9264 @item
9265 Add enhancements.
9266
9267 @item
9268 Compile all sources affected.
9269
9270 @item
9271 Rebind and relink.
9272
9273 @item
9274 Test.
9275 @end enumerate
9276
9277 @noindent
9278 The third step can be tricky, because not only do the modified files
9279 @cindex Dependency rules
9280 have to be compiled, but any files depending on these files must also be
9281 recompiled. The dependency rules in Ada can be quite complex, especially
9282 in the presence of overloading, @code{use} clauses, generics and inlined
9283 subprograms.
9284
9285 @command{gnatmake} automatically takes care of the third and fourth steps
9286 of this process. It determines which sources need to be compiled,
9287 compiles them, and binds and links the resulting object files.
9288
9289 Unlike some other Ada make programs, the dependencies are always
9290 accurately recomputed from the new sources. The source based approach of
9291 the GNAT compilation model makes this possible. This means that if
9292 changes to the source program cause corresponding changes in
9293 dependencies, they will always be tracked exactly correctly by
9294 @command{gnatmake}.
9295
9296 @node Running gnatmake
9297 @section Running @command{gnatmake}
9298
9299 @noindent
9300 The usual form of the @command{gnatmake} command is
9301
9302 @smallexample
9303 @c $ gnatmake @ovar{switches} @var{file_name}
9304 @c       @ovar{file_names} @ovar{mode_switches}
9305 @c Expanding @ovar macro inline (explanation in macro def comments)
9306 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9307       @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9308 @end smallexample
9309
9310 @noindent
9311 The only required argument is one @var{file_name}, which specifies
9312 a compilation unit that is a main program. Several @var{file_names} can be
9313 specified: this will result in several executables being built.
9314 If @code{switches} are present, they can be placed before the first
9315 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9316 If @var{mode_switches} are present, they must always be placed after
9317 the last @var{file_name} and all @code{switches}.
9318
9319 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9320 extension may be omitted from the @var{file_name} arguments. However, if
9321 you are using non-standard extensions, then it is required that the
9322 extension be given. A relative or absolute directory path can be
9323 specified in a @var{file_name}, in which case, the input source file will
9324 be searched for in the specified directory only. Otherwise, the input
9325 source file will first be searched in the directory where
9326 @command{gnatmake} was invoked and if it is not found, it will be search on
9327 the source path of the compiler as described in
9328 @ref{Search Paths and the Run-Time Library (RTL)}.
9329
9330 All @command{gnatmake} output (except when you specify
9331 @option{^-M^/DEPENDENCIES_LIST^}) is to
9332 @file{stderr}. The output produced by the
9333 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9334 @file{stdout}.
9335
9336 @node Switches for gnatmake
9337 @section Switches for @command{gnatmake}
9338
9339 @noindent
9340 You may specify any of the following switches to @command{gnatmake}:
9341
9342 @table @option
9343 @c !sort!
9344
9345 @item --version
9346 @cindex @option{--version} @command{gnatmake}
9347 Display Copyright and version, then exit disregarding all other options.
9348
9349 @item --help
9350 @cindex @option{--help} @command{gnatmake}
9351 If @option{--version} was not used, display usage, then exit disregarding
9352 all other options.
9353
9354 @ifclear vms
9355 @item --GCC=@var{compiler_name}
9356 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9357 Program used for compiling. The default is `@command{gcc}'. You need to use
9358 quotes around @var{compiler_name} if @code{compiler_name} contains
9359 spaces or other separator characters. As an example @option{--GCC="foo -x
9360 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9361 compiler. A limitation of this syntax is that the name and path name of
9362 the executable itself must not include any embedded spaces. Note that
9363 switch @option{-c} is always inserted after your command name. Thus in the
9364 above example the compiler command that will be used by @command{gnatmake}
9365 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9366 used, only the last @var{compiler_name} is taken into account. However,
9367 all the additional switches are also taken into account. Thus,
9368 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9369 @option{--GCC="bar -x -y -z -t"}.
9370
9371 @item --GNATBIND=@var{binder_name}
9372 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9373 Program used for binding. The default is `@code{gnatbind}'. You need to
9374 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9375 or other separator characters. As an example @option{--GNATBIND="bar -x
9376 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9377 binder. Binder switches that are normally appended by @command{gnatmake}
9378 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9379 A limitation of this syntax is that the name and path name of the executable
9380 itself must not include any embedded spaces.
9381
9382 @item --GNATLINK=@var{linker_name}
9383 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9384 Program used for linking. The default is `@command{gnatlink}'. You need to
9385 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9386 or other separator characters. As an example @option{--GNATLINK="lan -x
9387 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9388 linker. Linker switches that are normally appended by @command{gnatmake} to
9389 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9390 A limitation of this syntax is that the name and path name of the executable
9391 itself must not include any embedded spaces.
9392
9393 @end ifclear
9394
9395 @item ^--subdirs^/SUBDIRS^=subdir
9396 Actual object directory of each project file is the subdirectory subdir of the
9397 object directory specified or defaulted in the project file.
9398
9399 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9400 Disallow simultaneous compilations in the same object directory when
9401 project files are used.
9402
9403 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9404 By default, shared library projects are not allowed to import static library
9405 projects. When this switch is used on the command line, this restriction is
9406 relaxed.
9407
9408 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9409 Specify a source info file. This switch is active only when project files
9410 are used. If the source info file is specified as a relative path, then it is
9411 relative to the object directory of the main project. If the source info file
9412 does not exist, then after the Project Manager has successfully parsed and
9413 processed the project files and found the sources, it creates the source info
9414 file. If the source info file already exists and can be read successfully,
9415 then the Project Manager will get all the needed information about the sources
9416 from the source info file and will not look for them. This reduces the time
9417 to process the project files, especially when looking for sources that take a
9418 long time. If the source info file exists but cannot be parsed successfully,
9419 the Project Manager will attempt to recreate it. If the Project Manager fails
9420 to create the source info file, a message is issued, but gnatmake does not
9421 fail. @command{gnatmake} "trusts" the source info file. This means that
9422 if the source files have changed (addition, deletion, moving to a different
9423 source directory), then the source info file need to be deleted and recreated.
9424
9425 @ifclear vms
9426 @item --create-map-file
9427 When linking an executable, create a map file. The name of the map file
9428 has the same name as the executable with extension ".map".
9429
9430 @item --create-map-file=mapfile
9431 When linking an executable, create a map file. The name of the map file is
9432 "mapfile".
9433
9434 @end ifclear
9435
9436 @item ^-a^/ALL_FILES^
9437 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9438 Consider all files in the make process, even the GNAT internal system
9439 files (for example, the predefined Ada library files), as well as any
9440 locked files. Locked files are files whose ALI file is write-protected.
9441 By default,
9442 @command{gnatmake} does not check these files,
9443 because the assumption is that the GNAT internal files are properly up
9444 to date, and also that any write protected ALI files have been properly
9445 installed. Note that if there is an installation problem, such that one
9446 of these files is not up to date, it will be properly caught by the
9447 binder.
9448 You may have to specify this switch if you are working on GNAT
9449 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9450 in conjunction with @option{^-f^/FORCE_COMPILE^}
9451 if you need to recompile an entire application,
9452 including run-time files, using special configuration pragmas,
9453 such as a @code{Normalize_Scalars} pragma.
9454
9455 By default
9456 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9457 internal files with
9458 @ifclear vms
9459 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9460 @end ifclear
9461 @ifset vms
9462 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9463 @end ifset
9464
9465 @item ^-b^/ACTIONS=BIND^
9466 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9467 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9468 compilation and binding, but no link.
9469 Can be combined with @option{^-l^/ACTIONS=LINK^}
9470 to do binding and linking. When not combined with
9471 @option{^-c^/ACTIONS=COMPILE^}
9472 all the units in the closure of the main program must have been previously
9473 compiled and must be up to date. The root unit specified by @var{file_name}
9474 may be given without extension, with the source extension or, if no GNAT
9475 Project File is specified, with the ALI file extension.
9476
9477 @item ^-c^/ACTIONS=COMPILE^
9478 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9479 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9480 is also specified. Do not perform linking, except if both
9481 @option{^-b^/ACTIONS=BIND^} and
9482 @option{^-l^/ACTIONS=LINK^} are also specified.
9483 If the root unit specified by @var{file_name} is not a main unit, this is the
9484 default. Otherwise @command{gnatmake} will attempt binding and linking
9485 unless all objects are up to date and the executable is more recent than
9486 the objects.
9487
9488 @item ^-C^/MAPPING^
9489 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9490 Use a temporary mapping file. A mapping file is a way to communicate
9491 to the compiler two mappings: from unit names to file names (without
9492 any directory information) and from file names to path names (with
9493 full directory information). A mapping file can make the compiler's
9494 file searches faster, especially if there are many source directories,
9495 or the sources are read over a slow network connection. If
9496 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9497 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9498 is initially populated based on the project file. If
9499 @option{^-C^/MAPPING^} is used without
9500 @option{^-P^/PROJECT_FILE^},
9501 the mapping file is initially empty. Each invocation of the compiler
9502 will add any newly accessed sources to the mapping file.
9503
9504 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9505 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9506 Use a specific mapping file. The file, specified as a path name (absolute or
9507 relative) by this switch, should already exist, otherwise the switch is
9508 ineffective. The specified mapping file will be communicated to the compiler.
9509 This switch is not compatible with a project file
9510 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9511 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9512
9513 @item ^-d^/DISPLAY_PROGRESS^
9514 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9515 Display progress for each source, up to date or not, as a single line
9516
9517 @smallexample
9518 completed x out of y (zz%)
9519 @end smallexample
9520
9521 If the file needs to be compiled this is displayed after the invocation of
9522 the compiler. These lines are displayed even in quiet output mode.
9523
9524 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9525 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9526 Put all object files and ALI file in directory @var{dir}.
9527 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9528 and ALI files go in the current working directory.
9529
9530 This switch cannot be used when using a project file.
9531
9532 @item -eInnn
9533 @cindex @option{-eI} (@command{gnatmake})
9534 Indicates that the main source is a multi-unit source and the rank of the unit
9535 in the source file is nnn. nnn needs to be a positive number and a valid
9536 index in the source. This switch cannot be used when @command{gnatmake} is
9537 invoked for several mains.
9538
9539 @ifclear vms
9540 @item -eL
9541 @cindex @option{-eL} (@command{gnatmake})
9542 @cindex symbolic links
9543 Follow all symbolic links when processing project files.
9544 This should be used if your project uses symbolic links for files or
9545 directories, but is not needed in other cases.
9546
9547 @cindex naming scheme
9548 This also assumes that no directory matches the naming scheme for files (for
9549 instance that you do not have a directory called "sources.ads" when using the
9550 default GNAT naming scheme).
9551
9552 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9553 save a lot of system calls (several per source file and object file), which
9554 can result in a significant speed up to load and manipulate a project file,
9555 especially when using source files from a remote system.
9556
9557 @end ifclear
9558
9559 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9560 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9561 Output the commands for the compiler, the binder and the linker
9562 on ^standard output^SYS$OUTPUT^,
9563 instead of ^standard error^SYS$ERROR^.
9564
9565 @item ^-f^/FORCE_COMPILE^
9566 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9567 Force recompilations. Recompile all sources, even though some object
9568 files may be up to date, but don't recompile predefined or GNAT internal
9569 files or locked files (files with a write-protected ALI file),
9570 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9571
9572 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9573 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9574 When using project files, if some errors or warnings are detected during
9575 parsing and verbose mode is not in effect (no use of switch
9576 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9577 file, rather than its simple file name.
9578
9579 @item ^-g^/DEBUG^
9580 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9581 Enable debugging. This switch is simply passed to the compiler and to the
9582 linker.
9583
9584 @item ^-i^/IN_PLACE^
9585 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9586 In normal mode, @command{gnatmake} compiles all object files and ALI files
9587 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9588 then instead object files and ALI files that already exist are overwritten
9589 in place. This means that once a large project is organized into separate
9590 directories in the desired manner, then @command{gnatmake} will automatically
9591 maintain and update this organization. If no ALI files are found on the
9592 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9593 the new object and ALI files are created in the
9594 directory containing the source being compiled. If another organization
9595 is desired, where objects and sources are kept in different directories,
9596 a useful technique is to create dummy ALI files in the desired directories.
9597 When detecting such a dummy file, @command{gnatmake} will be forced to
9598 recompile the corresponding source file, and it will be put the resulting
9599 object and ALI files in the directory where it found the dummy file.
9600
9601 @item ^-j^/PROCESSES=^@var{n}
9602 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9603 @cindex Parallel make
9604 Use @var{n} processes to carry out the (re)compilations. On a multiprocessor
9605 machine compilations will occur in parallel. If @var{n} is 0, then the
9606 maximum number of parallel compilations is the number of core processors
9607 on the platform. In the event of compilation errors, messages from various
9608 compilations might get interspersed (but @command{gnatmake} will give you the
9609 full ordered list of failing compiles at the end). If this is problematic,
9610 rerun the make process with n set to 1 to get a clean list of messages.
9611
9612 @item ^-k^/CONTINUE_ON_ERROR^
9613 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9614 Keep going. Continue as much as possible after a compilation error. To
9615 ease the programmer's task in case of compilation errors, the list of
9616 sources for which the compile fails is given when @command{gnatmake}
9617 terminates.
9618
9619 If @command{gnatmake} is invoked with several @file{file_names} and with this
9620 switch, if there are compilation errors when building an executable,
9621 @command{gnatmake} will not attempt to build the following executables.
9622
9623 @item ^-l^/ACTIONS=LINK^
9624 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9625 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9626 and linking. Linking will not be performed if combined with
9627 @option{^-c^/ACTIONS=COMPILE^}
9628 but not with @option{^-b^/ACTIONS=BIND^}.
9629 When not combined with @option{^-b^/ACTIONS=BIND^}
9630 all the units in the closure of the main program must have been previously
9631 compiled and must be up to date, and the main program needs to have been bound.
9632 The root unit specified by @var{file_name}
9633 may be given without extension, with the source extension or, if no GNAT
9634 Project File is specified, with the ALI file extension.
9635
9636 @item ^-m^/MINIMAL_RECOMPILATION^
9637 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9638 Specify that the minimum necessary amount of recompilations
9639 be performed. In this mode @command{gnatmake} ignores time
9640 stamp differences when the only
9641 modifications to a source file consist in adding/removing comments,
9642 empty lines, spaces or tabs. This means that if you have changed the
9643 comments in a source file or have simply reformatted it, using this
9644 switch will tell @command{gnatmake} not to recompile files that depend on it
9645 (provided other sources on which these files depend have undergone no
9646 semantic modifications). Note that the debugging information may be
9647 out of date with respect to the sources if the @option{-m} switch causes
9648 a compilation to be switched, so the use of this switch represents a
9649 trade-off between compilation time and accurate debugging information.
9650
9651 @item ^-M^/DEPENDENCIES_LIST^
9652 @cindex Dependencies, producing list
9653 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9654 Check if all objects are up to date. If they are, output the object
9655 dependences to @file{stdout} in a form that can be directly exploited in
9656 a @file{Makefile}. By default, each source file is prefixed with its
9657 (relative or absolute) directory name. This name is whatever you
9658 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9659 and @option{^-I^/SEARCH^} switches. If you use
9660 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9661 @option{^-q^/QUIET^}
9662 (see below), only the source file names,
9663 without relative paths, are output. If you just specify the
9664 @option{^-M^/DEPENDENCIES_LIST^}
9665 switch, dependencies of the GNAT internal system files are omitted. This
9666 is typically what you want. If you also specify
9667 the @option{^-a^/ALL_FILES^} switch,
9668 dependencies of the GNAT internal files are also listed. Note that
9669 dependencies of the objects in external Ada libraries (see switch
9670 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9671 are never reported.
9672
9673 @item ^-n^/DO_OBJECT_CHECK^
9674 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9675 Don't compile, bind, or link. Checks if all objects are up to date.
9676 If they are not, the full name of the first file that needs to be
9677 recompiled is printed.
9678 Repeated use of this option, followed by compiling the indicated source
9679 file, will eventually result in recompiling all required units.
9680
9681 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9682 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9683 Output executable name. The name of the final executable program will be
9684 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9685 name for the executable will be the name of the input file in appropriate form
9686 for an executable file on the host system.
9687
9688 This switch cannot be used when invoking @command{gnatmake} with several
9689 @file{file_names}.
9690
9691 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9692 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9693 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9694 automatically missing object directories, library directories and exec
9695 directories.
9696
9697 @item ^-P^/PROJECT_FILE=^@var{project}
9698 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9699 Use project file @var{project}. Only one such switch can be used.
9700 @xref{gnatmake and Project Files}.
9701
9702 @item ^-q^/QUIET^
9703 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9704 Quiet. When this flag is not set, the commands carried out by
9705 @command{gnatmake} are displayed.
9706
9707 @item ^-s^/SWITCH_CHECK/^
9708 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9709 Recompile if compiler switches have changed since last compilation.
9710 All compiler switches but -I and -o are taken into account in the
9711 following way:
9712 orders between different ``first letter'' switches are ignored, but
9713 orders between same switches are taken into account. For example,
9714 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9715 is equivalent to @option{-O -g}.
9716
9717 This switch is recommended when Integrated Preprocessing is used.
9718
9719 @item ^-u^/UNIQUE^
9720 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9721 Unique. Recompile at most the main files. It implies -c. Combined with
9722 -f, it is equivalent to calling the compiler directly. Note that using
9723 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9724 (@pxref{Project Files and Main Subprograms}).
9725
9726 @item ^-U^/ALL_PROJECTS^
9727 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9728 When used without a project file or with one or several mains on the command
9729 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9730 on the command line, all sources of all project files are checked and compiled
9731 if not up to date, and libraries are rebuilt, if necessary.
9732
9733 @item ^-v^/REASONS^
9734 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9735 Verbose. Display the reason for all recompilations @command{gnatmake}
9736 decides are necessary, with the highest verbosity level.
9737
9738 @item ^-vl^/LOW_VERBOSITY^
9739 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9740 Verbosity level Low. Display fewer lines than in verbosity Medium.
9741
9742 @item ^-vm^/MEDIUM_VERBOSITY^
9743 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9744 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9745
9746 @item ^-vh^/HIGH_VERBOSITY^
9747 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9748 Verbosity level High. Equivalent to ^-v^/REASONS^.
9749
9750 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9751 Indicate the verbosity of the parsing of GNAT project files.
9752 @xref{Switches Related to Project Files}.
9753
9754 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9755 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9756 Indicate that sources that are not part of any Project File may be compiled.
9757 Normally, when using Project Files, only sources that are part of a Project
9758 File may be compile. When this switch is used, a source outside of all Project
9759 Files may be compiled. The ALI file and the object file will be put in the
9760 object directory of the main Project. The compilation switches used will only
9761 be those specified on the command line. Even when
9762 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9763 command line need to be sources of a project file.
9764
9765 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9766 Indicate that external variable @var{name} has the value @var{value}.
9767 The Project Manager will use this value for occurrences of
9768 @code{external(name)} when parsing the project file.
9769 @xref{Switches Related to Project Files}.
9770
9771 @item ^-z^/NOMAIN^
9772 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9773 No main subprogram. Bind and link the program even if the unit name
9774 given on the command line is a package name. The resulting executable
9775 will execute the elaboration routines of the package and its closure,
9776 then the finalization routines.
9777
9778 @end table
9779
9780 @table @asis
9781 @item @command{gcc} @asis{switches}
9782 @ifclear vms
9783 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9784 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9785 @end ifclear
9786 @ifset vms
9787 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9788 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9789 automatically treated as a compiler switch, and passed on to all
9790 compilations that are carried out.
9791 @end ifset
9792 @end table
9793
9794 @noindent
9795 Source and library search path switches:
9796
9797 @table @option
9798 @c !sort!
9799 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9800 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9801 When looking for source files also look in directory @var{dir}.
9802 The order in which source files search is undertaken is
9803 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9804
9805 @item ^-aL^/SKIP_MISSING=^@var{dir}
9806 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9807 Consider @var{dir} as being an externally provided Ada library.
9808 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9809 files have been located in directory @var{dir}. This allows you to have
9810 missing bodies for the units in @var{dir} and to ignore out of date bodies
9811 for the same units. You still need to specify
9812 the location of the specs for these units by using the switches
9813 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9814 or @option{^-I^/SEARCH=^@var{dir}}.
9815 Note: this switch is provided for compatibility with previous versions
9816 of @command{gnatmake}. The easier method of causing standard libraries
9817 to be excluded from consideration is to write-protect the corresponding
9818 ALI files.
9819
9820 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9821 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9822 When searching for library and object files, look in directory
9823 @var{dir}. The order in which library files are searched is described in
9824 @ref{Search Paths for gnatbind}.
9825
9826 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9827 @cindex Search paths, for @command{gnatmake}
9828 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9829 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9830 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9831
9832 @item ^-I^/SEARCH=^@var{dir}
9833 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9834 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9835 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9836
9837 @item ^-I-^/NOCURRENT_DIRECTORY^
9838 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9839 @cindex Source files, suppressing search
9840 Do not look for source files in the directory containing the source
9841 file named in the command line.
9842 Do not look for ALI or object files in the directory
9843 where @command{gnatmake} was invoked.
9844
9845 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9846 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9847 @cindex Linker libraries
9848 Add directory @var{dir} to the list of directories in which the linker
9849 will search for libraries. This is equivalent to
9850 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9851 @ifclear vms
9852 Furthermore, under Windows, the sources pointed to by the libraries path
9853 set in the registry are not searched for.
9854 @end ifclear
9855
9856 @item -nostdinc
9857 @cindex @option{-nostdinc} (@command{gnatmake})
9858 Do not look for source files in the system default directory.
9859
9860 @item -nostdlib
9861 @cindex @option{-nostdlib} (@command{gnatmake})
9862 Do not look for library files in the system default directory.
9863
9864 @item --RTS=@var{rts-path}
9865 @cindex @option{--RTS} (@command{gnatmake})
9866 Specifies the default location of the runtime library. GNAT looks for the
9867 runtime
9868 in the following directories, and stops as soon as a valid runtime is found
9869 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9870 @file{ada_object_path} present):
9871
9872 @itemize @bullet
9873 @item <current directory>/$rts_path
9874
9875 @item <default-search-dir>/$rts_path
9876
9877 @item <default-search-dir>/rts-$rts_path
9878 @end itemize
9879
9880 @noindent
9881 The selected path is handled like a normal RTS path.
9882
9883 @end table
9884
9885 @node Mode Switches for gnatmake
9886 @section Mode Switches for @command{gnatmake}
9887
9888 @noindent
9889 The mode switches (referred to as @code{mode_switches}) allow the
9890 inclusion of switches that are to be passed to the compiler itself, the
9891 binder or the linker. The effect of a mode switch is to cause all
9892 subsequent switches up to the end of the switch list, or up to the next
9893 mode switch, to be interpreted as switches to be passed on to the
9894 designated component of GNAT.
9895
9896 @table @option
9897 @c !sort!
9898 @item -cargs @var{switches}
9899 @cindex @option{-cargs} (@command{gnatmake})
9900 Compiler switches. Here @var{switches} is a list of switches
9901 that are valid switches for @command{gcc}. They will be passed on to
9902 all compile steps performed by @command{gnatmake}.
9903
9904 @item -bargs @var{switches}
9905 @cindex @option{-bargs} (@command{gnatmake})
9906 Binder switches. Here @var{switches} is a list of switches
9907 that are valid switches for @code{gnatbind}. They will be passed on to
9908 all bind steps performed by @command{gnatmake}.
9909
9910 @item -largs @var{switches}
9911 @cindex @option{-largs} (@command{gnatmake})
9912 Linker switches. Here @var{switches} is a list of switches
9913 that are valid switches for @command{gnatlink}. They will be passed on to
9914 all link steps performed by @command{gnatmake}.
9915
9916 @item -margs @var{switches}
9917 @cindex @option{-margs} (@command{gnatmake})
9918 Make switches. The switches are directly interpreted by @command{gnatmake},
9919 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9920 or @option{-largs}.
9921 @end table
9922
9923 @node Notes on the Command Line
9924 @section Notes on the Command Line
9925
9926 @noindent
9927 This section contains some additional useful notes on the operation
9928 of the @command{gnatmake} command.
9929
9930 @itemize @bullet
9931 @item
9932 @cindex Recompilation, by @command{gnatmake}
9933 If @command{gnatmake} finds no ALI files, it recompiles the main program
9934 and all other units required by the main program.
9935 This means that @command{gnatmake}
9936 can be used for the initial compile, as well as during subsequent steps of
9937 the development cycle.
9938
9939 @item
9940 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9941 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9942 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9943 warning.
9944
9945 @item
9946 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9947 is used to specify both source and
9948 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9949 instead if you just want to specify
9950 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9951 if you want to specify library paths
9952 only.
9953
9954 @item
9955 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9956 This may conveniently be used to exclude standard libraries from
9957 consideration and in particular it means that the use of the
9958 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9959 unless @option{^-a^/ALL_FILES^} is also specified.
9960
9961 @item
9962 @command{gnatmake} has been designed to make the use of Ada libraries
9963 particularly convenient. Assume you have an Ada library organized
9964 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9965 of your Ada compilation units,
9966 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9967 specs of these units, but no bodies. Then to compile a unit
9968 stored in @code{main.adb}, which uses this Ada library you would just type
9969
9970 @smallexample
9971 @ifclear vms
9972 $ gnatmake -aI@var{include-dir}  -aL@var{obj-dir}  main
9973 @end ifclear
9974 @ifset vms
9975 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9976            /SKIP_MISSING=@i{[OBJ_DIR]} main
9977 @end ifset
9978 @end smallexample
9979
9980 @item
9981 Using @command{gnatmake} along with the
9982 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9983 switch provides a mechanism for avoiding unnecessary recompilations. Using
9984 this switch,
9985 you can update the comments/format of your
9986 source files without having to recompile everything. Note, however, that
9987 adding or deleting lines in a source files may render its debugging
9988 info obsolete. If the file in question is a spec, the impact is rather
9989 limited, as that debugging info will only be useful during the
9990 elaboration phase of your program. For bodies the impact can be more
9991 significant. In all events, your debugger will warn you if a source file
9992 is more recent than the corresponding object, and alert you to the fact
9993 that the debugging information may be out of date.
9994 @end itemize
9995
9996 @node How gnatmake Works
9997 @section How @command{gnatmake} Works
9998
9999 @noindent
10000 Generally @command{gnatmake} automatically performs all necessary
10001 recompilations and you don't need to worry about how it works. However,
10002 it may be useful to have some basic understanding of the @command{gnatmake}
10003 approach and in particular to understand how it uses the results of
10004 previous compilations without incorrectly depending on them.
10005
10006 First a definition: an object file is considered @dfn{up to date} if the
10007 corresponding ALI file exists and if all the source files listed in the
10008 dependency section of this ALI file have time stamps matching those in
10009 the ALI file. This means that neither the source file itself nor any
10010 files that it depends on have been modified, and hence there is no need
10011 to recompile this file.
10012
10013 @command{gnatmake} works by first checking if the specified main unit is up
10014 to date. If so, no compilations are required for the main unit. If not,
10015 @command{gnatmake} compiles the main program to build a new ALI file that
10016 reflects the latest sources. Then the ALI file of the main unit is
10017 examined to find all the source files on which the main program depends,
10018 and @command{gnatmake} recursively applies the above procedure on all these
10019 files.
10020
10021 This process ensures that @command{gnatmake} only trusts the dependencies
10022 in an existing ALI file if they are known to be correct. Otherwise it
10023 always recompiles to determine a new, guaranteed accurate set of
10024 dependencies. As a result the program is compiled ``upside down'' from what may
10025 be more familiar as the required order of compilation in some other Ada
10026 systems. In particular, clients are compiled before the units on which
10027 they depend. The ability of GNAT to compile in any order is critical in
10028 allowing an order of compilation to be chosen that guarantees that
10029 @command{gnatmake} will recompute a correct set of new dependencies if
10030 necessary.
10031
10032 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
10033 imported by several of the executables, it will be recompiled at most once.
10034
10035 Note: when using non-standard naming conventions
10036 (@pxref{Using Other File Names}), changing through a configuration pragmas
10037 file the version of a source and invoking @command{gnatmake} to recompile may
10038 have no effect, if the previous version of the source is still accessible
10039 by @command{gnatmake}. It may be necessary to use the switch
10040 ^-f^/FORCE_COMPILE^.
10041
10042 @node Examples of gnatmake Usage
10043 @section Examples of @command{gnatmake} Usage
10044
10045 @table @code
10046 @item gnatmake hello.adb
10047 Compile all files necessary to bind and link the main program
10048 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
10049 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
10050
10051 @item gnatmake main1 main2 main3
10052 Compile all files necessary to bind and link the main programs
10053 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
10054 (containing unit @code{Main2}) and @file{main3.adb}
10055 (containing unit @code{Main3}) and bind and link the resulting object files
10056 to generate three executable files @file{^main1^MAIN1.EXE^},
10057 @file{^main2^MAIN2.EXE^}
10058 and @file{^main3^MAIN3.EXE^}.
10059
10060 @ifclear vms
10061 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10062 @end ifclear
10063
10064 @ifset vms
10065 @item gnatmake Main_Unit /QUIET
10066 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10067 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10068 @end ifset
10069 Compile all files necessary to bind and link the main program unit
10070 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10071 be done with optimization level 2 and the order of elaboration will be
10072 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10073 displaying commands it is executing.
10074 @end table
10075
10076 @c *************************
10077 @node Improving Performance
10078 @chapter Improving Performance
10079 @cindex Improving performance
10080
10081 @noindent
10082 This chapter presents several topics related to program performance.
10083 It first describes some of the tradeoffs that need to be considered
10084 and some of the techniques for making your program run faster.
10085 It then documents the @command{gnatelim} tool and unused subprogram/data
10086 elimination feature, which can reduce the size of program executables.
10087
10088 @ifnottex
10089 @menu
10090 * Performance Considerations::
10091 * Text_IO Suggestions::
10092 * Reducing Size of Ada Executables with gnatelim::
10093 * Reducing Size of Executables with unused subprogram/data elimination::
10094 @end menu
10095 @end ifnottex
10096
10097 @c *****************************
10098 @node Performance Considerations
10099 @section Performance Considerations
10100
10101 @noindent
10102 The GNAT system provides a number of options that allow a trade-off
10103 between
10104
10105 @itemize @bullet
10106 @item
10107 performance of the generated code
10108
10109 @item
10110 speed of compilation
10111
10112 @item
10113 minimization of dependences and recompilation
10114
10115 @item
10116 the degree of run-time checking.
10117 @end itemize
10118
10119 @noindent
10120 The defaults (if no options are selected) aim at improving the speed
10121 of compilation and minimizing dependences, at the expense of performance
10122 of the generated code:
10123
10124 @itemize @bullet
10125 @item
10126 no optimization
10127
10128 @item
10129 no inlining of subprogram calls
10130
10131 @item
10132 all run-time checks enabled except overflow and elaboration checks
10133 @end itemize
10134
10135 @noindent
10136 These options are suitable for most program development purposes. This
10137 chapter describes how you can modify these choices, and also provides
10138 some guidelines on debugging optimized code.
10139
10140 @menu
10141 * Controlling Run-Time Checks::
10142 * Use of Restrictions::
10143 * Optimization Levels::
10144 * Debugging Optimized Code::
10145 * Inlining of Subprograms::
10146 * Vectorization of loops::
10147 * Other Optimization Switches::
10148 * Optimization and Strict Aliasing::
10149 * Aliased Variables and Optimization::
10150
10151 @ifset vms
10152 * Coverage Analysis::
10153 @end ifset
10154 @end menu
10155
10156 @node Controlling Run-Time Checks
10157 @subsection Controlling Run-Time Checks
10158
10159 @noindent
10160 By default, GNAT generates all run-time checks, except integer overflow
10161 checks, stack overflow checks, and checks for access before elaboration on
10162 subprogram calls. The latter are not required in default mode, because all
10163 necessary checking is done at compile time.
10164 @cindex @option{-gnatp} (@command{gcc})
10165 @cindex @option{-gnato} (@command{gcc})
10166 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10167 be modified. @xref{Run-Time Checks}.
10168
10169 Our experience is that the default is suitable for most development
10170 purposes.
10171
10172 We treat integer overflow specially because these
10173 are quite expensive and in our experience are not as important as other
10174 run-time checks in the development process. Note that division by zero
10175 is not considered an overflow check, and divide by zero checks are
10176 generated where required by default.
10177
10178 Elaboration checks are off by default, and also not needed by default, since
10179 GNAT uses a static elaboration analysis approach that avoids the need for
10180 run-time checking. This manual contains a full chapter discussing the issue
10181 of elaboration checks, and if the default is not satisfactory for your use,
10182 you should read this chapter.
10183
10184 For validity checks, the minimal checks required by the Ada Reference
10185 Manual (for case statements and assignments to array elements) are on
10186 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10187 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10188 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10189 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10190 are also suppressed entirely if @option{-gnatp} is used.
10191
10192 @cindex Overflow checks
10193 @cindex Checks, overflow
10194 @findex Suppress
10195 @findex Unsuppress
10196 @cindex pragma Suppress
10197 @cindex pragma Unsuppress
10198 Note that the setting of the switches controls the default setting of
10199 the checks. They may be modified using either @code{pragma Suppress} (to
10200 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10201 checks) in the program source.
10202
10203 @node Use of Restrictions
10204 @subsection Use of Restrictions
10205
10206 @noindent
10207 The use of pragma Restrictions allows you to control which features are
10208 permitted in your program. Apart from the obvious point that if you avoid
10209 relatively expensive features like finalization (enforceable by the use
10210 of pragma Restrictions (No_Finalization), the use of this pragma does not
10211 affect the generated code in most cases.
10212
10213 One notable exception to this rule is that the possibility of task abort
10214 results in some distributed overhead, particularly if finalization or
10215 exception handlers are used. The reason is that certain sections of code
10216 have to be marked as non-abortable.
10217
10218 If you use neither the @code{abort} statement, nor asynchronous transfer
10219 of control (@code{select @dots{} then abort}), then this distributed overhead
10220 is removed, which may have a general positive effect in improving
10221 overall performance.  Especially code involving frequent use of tasking
10222 constructs and controlled types will show much improved performance.
10223 The relevant restrictions pragmas are
10224
10225 @smallexample @c ada
10226    pragma Restrictions (No_Abort_Statements);
10227    pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10228 @end smallexample
10229
10230 @noindent
10231 It is recommended that these restriction pragmas be used if possible. Note
10232 that this also means that you can write code without worrying about the
10233 possibility of an immediate abort at any point.
10234
10235 @node Optimization Levels
10236 @subsection Optimization Levels
10237 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10238
10239 @noindent
10240 Without any optimization ^option,^qualifier,^
10241 the compiler's goal is to reduce the cost of
10242 compilation and to make debugging produce the expected results.
10243 Statements are independent: if you stop the program with a breakpoint between
10244 statements, you can then assign a new value to any variable or change
10245 the program counter to any other statement in the subprogram and get exactly
10246 the results you would expect from the source code.
10247
10248 Turning on optimization makes the compiler attempt to improve the
10249 performance and/or code size at the expense of compilation time and
10250 possibly the ability to debug the program.
10251
10252 If you use multiple
10253 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10254 the last such option is the one that is effective.
10255
10256 @noindent
10257 The default is optimization off. This results in the fastest compile
10258 times, but GNAT makes absolutely no attempt to optimize, and the
10259 generated programs are considerably larger and slower than when
10260 optimization is enabled. You can use the
10261 @ifclear vms
10262 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10263 @option{-O2}, @option{-O3}, and @option{-Os})
10264 @end ifclear
10265 @ifset vms
10266 @code{OPTIMIZE} qualifier
10267 @end ifset
10268 to @command{gcc} to control the optimization level:
10269
10270 @table @option
10271 @item ^-O0^/OPTIMIZE=NONE^
10272 No optimization (the default);
10273 generates unoptimized code but has
10274 the fastest compilation time.
10275
10276 Note that many other compilers do fairly extensive optimization
10277 even if ``no optimization'' is specified. With gcc, it is
10278 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10279 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10280 really does mean no optimization at all. This difference between
10281 gcc and other compilers should be kept in mind when doing
10282 performance comparisons.
10283
10284 @item ^-O1^/OPTIMIZE=SOME^
10285 Moderate optimization;
10286 optimizes reasonably well but does not
10287 degrade compilation time significantly.
10288
10289 @item ^-O2^/OPTIMIZE=ALL^
10290 @ifset vms
10291 @itemx /OPTIMIZE=DEVELOPMENT
10292 @end ifset
10293 Full optimization;
10294 generates highly optimized code and has
10295 the slowest compilation time.
10296
10297 @item ^-O3^/OPTIMIZE=INLINING^
10298 Full optimization as in @option{-O2};
10299 also uses more aggressive automatic inlining of subprograms within a unit
10300 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10301
10302 @item ^-Os^/OPTIMIZE=SPACE^
10303 Optimize space usage (code and data) of resulting program.
10304 @end table
10305
10306 @noindent
10307 Higher optimization levels perform more global transformations on the
10308 program and apply more expensive analysis algorithms in order to generate
10309 faster and more compact code. The price in compilation time, and the
10310 resulting improvement in execution time,
10311 both depend on the particular application and the hardware environment.
10312 You should experiment to find the best level for your application.
10313
10314 Since the precise set of optimizations done at each level will vary from
10315 release to release (and sometime from target to target), it is best to think
10316 of the optimization settings in general terms.
10317 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10318 the GNU Compiler Collection (GCC)}, for details about
10319 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10320 individually enable or disable specific optimizations.
10321
10322 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10323 been tested extensively at all optimization levels. There are some bugs
10324 which appear only with optimization turned on, but there have also been
10325 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10326 level of optimization does not improve the reliability of the code
10327 generator, which in practice is highly reliable at all optimization
10328 levels.
10329
10330 Note regarding the use of @option{-O3}: The use of this optimization level
10331 is generally discouraged with GNAT, since it often results in larger
10332 executables which may run more slowly. See further discussion of this point
10333 in @ref{Inlining of Subprograms}.
10334
10335 @node Debugging Optimized Code
10336 @subsection Debugging Optimized Code
10337 @cindex Debugging optimized code
10338 @cindex Optimization and debugging
10339
10340 @noindent
10341 Although it is possible to do a reasonable amount of debugging at
10342 @ifclear vms
10343 nonzero optimization levels,
10344 the higher the level the more likely that
10345 @end ifclear
10346 @ifset vms
10347 @option{/OPTIMIZE} settings other than @code{NONE},
10348 such settings will make it more likely that
10349 @end ifset
10350 source-level constructs will have been eliminated by optimization.
10351 For example, if a loop is strength-reduced, the loop
10352 control variable may be completely eliminated and thus cannot be
10353 displayed in the debugger.
10354 This can only happen at @option{-O2} or @option{-O3}.
10355 Explicit temporary variables that you code might be eliminated at
10356 ^level^setting^ @option{-O1} or higher.
10357
10358 The use of the @option{^-g^/DEBUG^} switch,
10359 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10360 which is needed for source-level debugging,
10361 affects the size of the program executable on disk,
10362 and indeed the debugging information can be quite large.
10363 However, it has no effect on the generated code (and thus does not
10364 degrade performance)
10365
10366 Since the compiler generates debugging tables for a compilation unit before
10367 it performs optimizations, the optimizing transformations may invalidate some
10368 of the debugging data.  You therefore need to anticipate certain
10369 anomalous situations that may arise while debugging optimized code.
10370 These are the most common cases:
10371
10372 @enumerate
10373 @item
10374 @i{The ``hopping Program Counter'':}  Repeated @code{step} or @code{next}
10375 commands show
10376 the PC bouncing back and forth in the code.  This may result from any of
10377 the following optimizations:
10378
10379 @itemize @bullet
10380 @item
10381 @i{Common subexpression elimination:} using a single instance of code for a
10382 quantity that the source computes several times.  As a result you
10383 may not be able to stop on what looks like a statement.
10384
10385 @item
10386 @i{Invariant code motion:} moving an expression that does not change within a
10387 loop, to the beginning of the loop.
10388
10389 @item
10390 @i{Instruction scheduling:} moving instructions so as to
10391 overlap loads and stores (typically) with other code, or in
10392 general to move computations of values closer to their uses. Often
10393 this causes you to pass an assignment statement without the assignment
10394 happening and then later bounce back to the statement when the
10395 value is actually needed.  Placing a breakpoint on a line of code
10396 and then stepping over it may, therefore, not always cause all the
10397 expected side-effects.
10398 @end itemize
10399
10400 @item
10401 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10402 two identical pieces of code are merged and the program counter suddenly
10403 jumps to a statement that is not supposed to be executed, simply because
10404 it (and the code following) translates to the same thing as the code
10405 that @emph{was} supposed to be executed.  This effect is typically seen in
10406 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10407 a @code{break} in a C @code{^switch^switch^} statement.
10408
10409 @item
10410 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10411 There are various reasons for this effect:
10412
10413 @itemize @bullet
10414 @item
10415 In a subprogram prologue, a parameter may not yet have been moved to its
10416 ``home''.
10417
10418 @item
10419 A variable may be dead, and its register re-used.  This is
10420 probably the most common cause.
10421
10422 @item
10423 As mentioned above, the assignment of a value to a variable may
10424 have been moved.
10425
10426 @item
10427 A variable may be eliminated entirely by value propagation or
10428 other means.  In this case, GCC may incorrectly generate debugging
10429 information for the variable
10430 @end itemize
10431
10432 @noindent
10433 In general, when an unexpected value appears for a local variable or parameter
10434 you should first ascertain if that value was actually computed by
10435 your program, as opposed to being incorrectly reported by the debugger.
10436 Record fields or
10437 array elements in an object designated by an access value
10438 are generally less of a problem, once you have ascertained that the access
10439 value is sensible.
10440 Typically, this means checking variables in the preceding code and in the
10441 calling subprogram to verify that the value observed is explainable from other
10442 values (one must apply the procedure recursively to those
10443 other values); or re-running the code and stopping a little earlier
10444 (perhaps before the call) and stepping to better see how the variable obtained
10445 the value in question; or continuing to step @emph{from} the point of the
10446 strange value to see if code motion had simply moved the variable's
10447 assignments later.
10448 @end enumerate
10449
10450 @noindent
10451 In light of such anomalies, a recommended technique is to use @option{-O0}
10452 early in the software development cycle, when extensive debugging capabilities
10453 are most needed, and then move to @option{-O1} and later @option{-O2} as
10454 the debugger becomes less critical.
10455 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10456 a release management issue.
10457 @ifclear vms
10458 Note that if you use @option{-g} you can then use the @command{strip} program
10459 on the resulting executable,
10460 which removes both debugging information and global symbols.
10461 @end ifclear
10462
10463 @node Inlining of Subprograms
10464 @subsection Inlining of Subprograms
10465
10466 @noindent
10467 A call to a subprogram in the current unit is inlined if all the
10468 following conditions are met:
10469
10470 @itemize @bullet
10471 @item
10472 The optimization level is at least @option{-O1}.
10473
10474 @item
10475 The called subprogram is suitable for inlining: It must be small enough
10476 and not contain something that @command{gcc} cannot support in inlined
10477 subprograms.
10478
10479 @item
10480 @cindex pragma Inline
10481 @findex Inline
10482 Any one of the following applies: @code{pragma Inline} is applied to the
10483 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10484 subprogram is local to the unit and called once from within it; the
10485 subprogram is small and optimization level @option{-O2} is specified;
10486 optimization level @option{-O3} is specified.
10487 @end itemize
10488
10489 @noindent
10490 Calls to subprograms in @code{with}'ed units are normally not inlined.
10491 To achieve actual inlining (that is, replacement of the call by the code
10492 in the body of the subprogram), the following conditions must all be true:
10493
10494 @itemize @bullet
10495 @item
10496 The optimization level is at least @option{-O1}.
10497
10498 @item
10499 The called subprogram is suitable for inlining: It must be small enough
10500 and not contain something that @command{gcc} cannot support in inlined
10501 subprograms.
10502
10503 @item
10504 The call appears in a body (not in a package spec).
10505
10506 @item
10507 There is a @code{pragma Inline} for the subprogram.
10508
10509 @item
10510 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10511 @end itemize
10512
10513 Even if all these conditions are met, it may not be possible for
10514 the compiler to inline the call, due to the length of the body,
10515 or features in the body that make it impossible for the compiler
10516 to do the inlining.
10517
10518 Note that specifying the @option{-gnatn} switch causes additional
10519 compilation dependencies. Consider the following:
10520
10521 @smallexample @c ada
10522 @cartouche
10523 package R is
10524    procedure Q;
10525    pragma Inline (Q);
10526 end R;
10527 package body R is
10528    @dots{}
10529 end R;
10530
10531 with R;
10532 procedure Main is
10533 begin
10534    @dots{}
10535    R.Q;
10536 end Main;
10537 @end cartouche
10538 @end smallexample
10539
10540 @noindent
10541 With the default behavior (no @option{-gnatn} switch specified), the
10542 compilation of the @code{Main} procedure depends only on its own source,
10543 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10544 means that editing the body of @code{R} does not require recompiling
10545 @code{Main}.
10546
10547 On the other hand, the call @code{R.Q} is not inlined under these
10548 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10549 is compiled, the call will be inlined if the body of @code{Q} is small
10550 enough, but now @code{Main} depends on the body of @code{R} in
10551 @file{r.adb} as well as on the spec. This means that if this body is edited,
10552 the main program must be recompiled. Note that this extra dependency
10553 occurs whether or not the call is in fact inlined by @command{gcc}.
10554
10555 The use of front end inlining with @option{-gnatN} generates similar
10556 additional dependencies.
10557
10558 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10559 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10560 can be used to prevent
10561 all inlining. This switch overrides all other conditions and ensures
10562 that no inlining occurs. The extra dependences resulting from
10563 @option{-gnatn} will still be active, even if
10564 this switch is used to suppress the resulting inlining actions.
10565
10566 @cindex @option{-fno-inline-functions} (@command{gcc})
10567 Note: The @option{-fno-inline-functions} switch can be used to prevent
10568 automatic inlining of subprograms if @option{-O3} is used.
10569
10570 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10571 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10572 automatic inlining of small subprograms if @option{-O2} is used.
10573
10574 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10575 Note: The @option{-fno-inline-functions-called-once} switch
10576 can be used to prevent inlining of subprograms local to the unit
10577 and called once from within it if @option{-O1} is used.
10578
10579 Note regarding the use of @option{-O3}: @option{-gnatn} is made up of two
10580 sub-switches @option{-gnatn1} and @option{-gnatn2} that can be directly
10581 specified in lieu of it, @option{-gnatn} being translated into one of them
10582 based on the optimization level. With @option{-O2} or below, @option{-gnatn}
10583 is equivalent to @option{-gnatn1} which activates pragma @code{Inline} with
10584 moderate inlining across modules. With @option{-O3}, @option{-gnatn} is
10585 equivalent to @option{-gnatn2} which activates pragma @code{Inline} with
10586 full inlining across modules. If you have used pragma @code{Inline} in appropriate cases, then it is usually much better to use @option{-O2} and @option{-gnatn} and avoid the use of @option{-O3} which has the additional
10587 effect of inlining subprograms you did not think should be inlined. We have
10588 found that the use of @option{-O3} may slow down the compilation and increase
10589 the code size by performing excessive inlining, leading to increased
10590 instruction cache pressure from the increased code size and thus minor
10591 performance improvements. So the bottom line here is that you should not
10592 automatically assume that @option{-O3} is better than @option{-O2}, and
10593 indeed you should use @option{-O3} only if tests show that it actually
10594 improves performance for your program.
10595
10596 @node Vectorization of loops
10597 @subsection Vectorization of loops
10598 @cindex Optimization Switches
10599
10600 You can take advantage of the auto-vectorizer present in the @command{gcc}
10601 back end to vectorize loops with GNAT.  The corresponding command line switch
10602 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10603 and other aggressive optimizations helpful for vectorization also are enabled
10604 by default at this level, using @option{-O3} directly is recommended.
10605
10606 You also need to make sure that the target architecture features a supported
10607 SIMD instruction set.  For example, for the x86 architecture, you should at
10608 least specify @option{-msse2} to get significant vectorization (but you don't
10609 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10610 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10611
10612 The preferred loop form for vectorization is the @code{for} iteration scheme.
10613 Loops with a @code{while} iteration scheme can also be vectorized if they are
10614 very simple, but the vectorizer will quickly give up otherwise.  With either
10615 iteration scheme, the flow of control must be straight, in particular no
10616 @code{exit} statement may appear in the loop body.  The loop may however
10617 contain a single nested loop, if it can be vectorized when considered alone:
10618
10619 @smallexample @c ada
10620 @cartouche
10621    A : array (1..4, 1..4) of Long_Float;
10622    S : array (1..4) of Long_Float;
10623
10624    procedure Sum is
10625    begin
10626       for I in A'Range(1) loop
10627          for J in A'Range(2) loop
10628             S (I) := S (I) + A (I, J);
10629          end loop;
10630       end loop;
10631    end Sum;
10632 @end cartouche
10633 @end smallexample
10634
10635 The vectorizable operations depend on the targeted SIMD instruction set, but
10636 the adding and some of the multiplying operators are generally supported, as
10637 well as the logical operators for modular types.  Note that, in the former
10638 case, enabling overflow checks, for example with @option{-gnato}, totally
10639 disables vectorization.  The other checks are not supposed to have the same
10640 definitive effect, although compiling with @option{-gnatp} might well reveal
10641 cases where some checks do thwart vectorization.
10642
10643 Type conversions may also prevent vectorization if they involve semantics that
10644 are not directly supported by the code generator or the SIMD instruction set.
10645 A typical example is direct conversion from floating-point to integer types.
10646 The solution in this case is to use the following idiom:
10647
10648 @smallexample @c ada
10649    Integer (S'Truncation (F))
10650 @end smallexample
10651
10652 @noindent
10653 if @code{S} is the subtype of floating-point object @code{F}.
10654
10655 In most cases, the vectorizable loops are loops that iterate over arrays.
10656 All kinds of array types are supported, i.e. constrained array types with
10657 static bounds:
10658
10659 @smallexample @c ada
10660    type Array_Type is array (1 .. 4) of Long_Float;
10661 @end smallexample
10662
10663 @noindent
10664 constrained array types with dynamic bounds:
10665
10666 @smallexample @c ada
10667    type Array_Type is array (1 .. Q.N) of Long_Float;
10668
10669    type Array_Type is array (Q.K .. 4) of Long_Float;
10670
10671    type Array_Type is array (Q.K .. Q.N) of Long_Float;
10672 @end smallexample
10673
10674 @noindent
10675 or unconstrained array types:
10676
10677 @smallexample @c ada
10678   type Array_Type is array (Positive range <>) of Long_Float;
10679 @end smallexample
10680
10681 @noindent
10682 The quality of the generated code decreases when the dynamic aspect of the
10683 array type increases, the worst code being generated for unconstrained array
10684 types.  This is so because, the less information the compiler has about the
10685 bounds of the array, the more fallback code it needs to generate in order to
10686 fix things up at run time.
10687
10688 It is possible to specify that a given loop should be subject to vectorization
10689 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
10690
10691 @smallexample @c ada
10692   pragma Loop_Optimize (Vector);
10693 @end smallexample
10694
10695 @noindent
10696 placed immediately within the loop will convey the appropriate hint to the
10697 compiler for this loop.
10698
10699 You can obtain information about the vectorization performed by the compiler
10700 by specifying @option{-ftree-vectorizer-verbose=N}.  For more details of
10701 this switch, see @ref{Debugging Options,,Options for Debugging Your Program
10702 or GCC, gcc, Using the GNU Compiler Collection (GCC)}.
10703
10704 @node Other Optimization Switches
10705 @subsection Other Optimization Switches
10706 @cindex Optimization Switches
10707
10708 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10709 @command{gcc} optimization switches are potentially usable. These switches
10710 have not been extensively tested with GNAT but can generally be expected
10711 to work. Examples of switches in this category are @option{-funroll-loops}
10712 and the various target-specific @option{-m} options (in particular, it has
10713 been observed that @option{-march=xxx} can significantly improve performance
10714 on appropriate machines). For full details of these switches, see
10715 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10716 the GNU Compiler Collection (GCC)}.
10717
10718 @node Optimization and Strict Aliasing
10719 @subsection Optimization and Strict Aliasing
10720 @cindex Aliasing
10721 @cindex Strict Aliasing
10722 @cindex No_Strict_Aliasing
10723
10724 @noindent
10725 The strong typing capabilities of Ada allow an optimizer to generate
10726 efficient code in situations where other languages would be forced to
10727 make worst case assumptions preventing such optimizations. Consider
10728 the following example:
10729
10730 @smallexample @c ada
10731 @cartouche
10732 procedure R is
10733    type Int1 is new Integer;
10734    type Int2 is new Integer;
10735    type Int1A is access Int1;
10736    type Int2A is access Int2;
10737    Int1V : Int1A;
10738    Int2V : Int2A;
10739    @dots{}
10740
10741 begin
10742    @dots{}
10743    for J in Data'Range loop
10744       if Data (J) = Int1V.all then
10745          Int2V.all := Int2V.all + 1;
10746       end if;
10747    end loop;
10748    @dots{}
10749 end R;
10750 @end cartouche
10751 @end smallexample
10752
10753 @noindent
10754 In this example, since the variable @code{Int1V} can only access objects
10755 of type @code{Int1}, and @code{Int2V} can only access objects of type
10756 @code{Int2}, there is no possibility that the assignment to
10757 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10758 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10759 for all iterations of the loop and avoid the extra memory reference
10760 required to dereference it each time through the loop.
10761
10762 This kind of optimization, called strict aliasing analysis, is
10763 triggered by specifying an optimization level of @option{-O2} or
10764 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10765 when access values are involved.
10766
10767 However, although this optimization is always correct in terms of
10768 the formal semantics of the Ada Reference Manual, difficulties can
10769 arise if features like @code{Unchecked_Conversion} are used to break
10770 the typing system. Consider the following complete program example:
10771
10772 @smallexample @c ada
10773 @cartouche
10774 package p1 is
10775    type int1 is new integer;
10776    type int2 is new integer;
10777    type a1 is access int1;
10778    type a2 is access int2;
10779 end p1;
10780
10781 with p1; use p1;
10782 package p2 is
10783    function to_a2 (Input : a1) return a2;
10784 end p2;
10785
10786 with Unchecked_Conversion;
10787 package body p2 is
10788    function to_a2 (Input : a1) return a2 is
10789       function to_a2u is
10790         new Unchecked_Conversion (a1, a2);
10791    begin
10792       return to_a2u (Input);
10793    end to_a2;
10794 end p2;
10795
10796 with p2; use p2;
10797 with p1; use p1;
10798 with Text_IO; use Text_IO;
10799 procedure m is
10800    v1 : a1 := new int1;
10801    v2 : a2 := to_a2 (v1);
10802 begin
10803    v1.all := 1;
10804    v2.all := 0;
10805    put_line (int1'image (v1.all));
10806 end;
10807 @end cartouche
10808 @end smallexample
10809
10810 @noindent
10811 This program prints out 0 in @option{-O0} or @option{-O1}
10812 mode, but it prints out 1 in @option{-O2} mode. That's
10813 because in strict aliasing mode, the compiler can and
10814 does assume that the assignment to @code{v2.all} could not
10815 affect the value of @code{v1.all}, since different types
10816 are involved.
10817
10818 This behavior is not a case of non-conformance with the standard, since
10819 the Ada RM specifies that an unchecked conversion where the resulting
10820 bit pattern is not a correct value of the target type can result in an
10821 abnormal value and attempting to reference an abnormal value makes the
10822 execution of a program erroneous.  That's the case here since the result
10823 does not point to an object of type @code{int2}.  This means that the
10824 effect is entirely unpredictable.
10825
10826 However, although that explanation may satisfy a language
10827 lawyer, in practice an applications programmer expects an
10828 unchecked conversion involving pointers to create true
10829 aliases and the behavior of printing 1 seems plain wrong.
10830 In this case, the strict aliasing optimization is unwelcome.
10831
10832 Indeed the compiler recognizes this possibility, and the
10833 unchecked conversion generates a warning:
10834
10835 @smallexample
10836 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10837 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10838 p2.adb:5:07: warning:  or use "pragma No_Strict_Aliasing (a2);"
10839 @end smallexample
10840
10841 @noindent
10842 Unfortunately the problem is recognized when compiling the body of
10843 package @code{p2}, but the actual "bad" code is generated while
10844 compiling the body of @code{m} and this latter compilation does not see
10845 the suspicious @code{Unchecked_Conversion}.
10846
10847 As implied by the warning message, there are approaches you can use to
10848 avoid the unwanted strict aliasing optimization in a case like this.
10849
10850 One possibility is to simply avoid the use of @option{-O2}, but
10851 that is a bit drastic, since it throws away a number of useful
10852 optimizations that do not involve strict aliasing assumptions.
10853
10854 A less drastic approach is to compile the program using the
10855 option @option{-fno-strict-aliasing}. Actually it is only the
10856 unit containing the dereferencing of the suspicious pointer
10857 that needs to be compiled. So in this case, if we compile
10858 unit @code{m} with this switch, then we get the expected
10859 value of zero printed. Analyzing which units might need
10860 the switch can be painful, so a more reasonable approach
10861 is to compile the entire program with options @option{-O2}
10862 and @option{-fno-strict-aliasing}. If the performance is
10863 satisfactory with this combination of options, then the
10864 advantage is that the entire issue of possible "wrong"
10865 optimization due to strict aliasing is avoided.
10866
10867 To avoid the use of compiler switches, the configuration
10868 pragma @code{No_Strict_Aliasing} with no parameters may be
10869 used to specify that for all access types, the strict
10870 aliasing optimization should be suppressed.
10871
10872 However, these approaches are still overkill, in that they causes
10873 all manipulations of all access values to be deoptimized. A more
10874 refined approach is to concentrate attention on the specific
10875 access type identified as problematic.
10876
10877 First, if a careful analysis of uses of the pointer shows
10878 that there are no possible problematic references, then
10879 the warning can be suppressed by bracketing the
10880 instantiation of @code{Unchecked_Conversion} to turn
10881 the warning off:
10882
10883 @smallexample @c ada
10884    pragma Warnings (Off);
10885    function to_a2u is
10886      new Unchecked_Conversion (a1, a2);
10887    pragma Warnings (On);
10888 @end smallexample
10889
10890 @noindent
10891 Of course that approach is not appropriate for this particular
10892 example, since indeed there is a problematic reference. In this
10893 case we can take one of two other approaches.
10894
10895 The first possibility is to move the instantiation of unchecked
10896 conversion to the unit in which the type is declared. In
10897 this example, we would move the instantiation of
10898 @code{Unchecked_Conversion} from the body of package
10899 @code{p2} to the spec of package @code{p1}. Now the
10900 warning disappears. That's because any use of the
10901 access type knows there is a suspicious unchecked
10902 conversion, and the strict aliasing optimization
10903 is automatically suppressed for the type.
10904
10905 If it is not practical to move the unchecked conversion to the same unit
10906 in which the destination access type is declared (perhaps because the
10907 source type is not visible in that unit), you may use pragma
10908 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10909 same declarative sequence as the declaration of the access type:
10910
10911 @smallexample @c ada
10912    type a2 is access int2;
10913    pragma No_Strict_Aliasing (a2);
10914 @end smallexample
10915
10916 @noindent
10917 Here again, the compiler now knows that the strict aliasing optimization
10918 should be suppressed for any reference to type @code{a2} and the
10919 expected behavior is obtained.
10920
10921 Finally, note that although the compiler can generate warnings for
10922 simple cases of unchecked conversions, there are tricker and more
10923 indirect ways of creating type incorrect aliases which the compiler
10924 cannot detect. Examples are the use of address overlays and unchecked
10925 conversions involving composite types containing access types as
10926 components. In such cases, no warnings are generated, but there can
10927 still be aliasing problems. One safe coding practice is to forbid the
10928 use of address clauses for type overlaying, and to allow unchecked
10929 conversion only for primitive types. This is not really a significant
10930 restriction since any possible desired effect can be achieved by
10931 unchecked conversion of access values.
10932
10933 The aliasing analysis done in strict aliasing mode can certainly
10934 have significant benefits. We have seen cases of large scale
10935 application code where the time is increased by up to 5% by turning
10936 this optimization off. If you have code that includes significant
10937 usage of unchecked conversion, you might want to just stick with
10938 @option{-O1} and avoid the entire issue. If you get adequate
10939 performance at this level of optimization level, that's probably
10940 the safest approach. If tests show that you really need higher
10941 levels of optimization, then you can experiment with @option{-O2}
10942 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10943 has on size and speed of the code. If you really need to use
10944 @option{-O2} with strict aliasing in effect, then you should
10945 review any uses of unchecked conversion of access types,
10946 particularly if you are getting the warnings described above.
10947
10948 @node Aliased Variables and Optimization
10949 @subsection Aliased Variables and Optimization
10950 @cindex Aliasing
10951 There are scenarios in which programs may
10952 use low level techniques to modify variables
10953 that otherwise might be considered to be unassigned. For example,
10954 a variable can be passed to a procedure by reference, which takes
10955 the address of the parameter and uses the address to modify the
10956 variable's value, even though it is passed as an IN parameter.
10957 Consider the following example:
10958
10959 @smallexample @c ada
10960 procedure P is
10961    Max_Length : constant Natural := 16;
10962    type Char_Ptr is access all Character;
10963
10964    procedure Get_String(Buffer: Char_Ptr; Size : Integer);
10965    pragma Import (C, Get_String, "get_string");
10966
10967    Name : aliased String (1 .. Max_Length) := (others => ' ');
10968    Temp : Char_Ptr;
10969
10970    function Addr (S : String) return Char_Ptr is
10971       function To_Char_Ptr is
10972         new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
10973    begin
10974       return To_Char_Ptr (S (S'First)'Address);
10975    end;
10976
10977 begin
10978    Temp := Addr (Name);
10979    Get_String (Temp, Max_Length);
10980 end;
10981 @end smallexample
10982
10983 @noindent
10984 where Get_String is a C function that uses the address in Temp to
10985 modify the variable @code{Name}. This code is dubious, and arguably
10986 erroneous, and the compiler would be entitled to assume that
10987 @code{Name} is never modified, and generate code accordingly.
10988
10989 However, in practice, this would cause some existing code that
10990 seems to work with no optimization to start failing at high
10991 levels of optimzization.
10992
10993 What the compiler does for such cases is to assume that marking
10994 a variable as aliased indicates that some "funny business" may
10995 be going on. The optimizer recognizes the aliased keyword and
10996 inhibits optimizations that assume the value cannot be assigned.
10997 This means that the above example will in fact "work" reliably,
10998 that is, it will produce the expected results.
10999
11000 @ifset vms
11001 @node Coverage Analysis
11002 @subsection Coverage Analysis
11003
11004 @noindent
11005 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
11006 the user to determine the distribution of execution time across a program,
11007 @pxref{Profiling} for details of usage.
11008 @end ifset
11009
11010
11011 @node Text_IO Suggestions
11012 @section @code{Text_IO} Suggestions
11013 @cindex @code{Text_IO} and performance
11014
11015 @noindent
11016 The @code{Ada.Text_IO} package has fairly high overheads due in part to
11017 the requirement of maintaining page and line counts. If performance
11018 is critical, a recommendation is to use @code{Stream_IO} instead of
11019 @code{Text_IO} for volume output, since this package has less overhead.
11020
11021 If @code{Text_IO} must be used, note that by default output to the standard
11022 output and standard error files is unbuffered (this provides better
11023 behavior when output statements are used for debugging, or if the
11024 progress of a program is observed by tracking the output, e.g. by
11025 using the Unix @command{tail -f} command to watch redirected output.
11026
11027 If you are generating large volumes of output with @code{Text_IO} and
11028 performance is an important factor, use a designated file instead
11029 of the standard output file, or change the standard output file to
11030 be buffered using @code{Interfaces.C_Streams.setvbuf}.
11031
11032
11033
11034 @node Reducing Size of Ada Executables with gnatelim
11035 @section Reducing Size of Ada Executables with @code{gnatelim}
11036 @findex gnatelim
11037
11038 @noindent
11039 This section describes @command{gnatelim}, a tool which detects unused
11040 subprograms and helps the compiler to create a smaller executable for your
11041 program.
11042
11043 @menu
11044 * About gnatelim::
11045 * Running gnatelim::
11046 * Processing Precompiled Libraries::
11047 * Correcting the List of Eliminate Pragmas::
11048 * Making Your Executables Smaller::
11049 * Summary of the gnatelim Usage Cycle::
11050 @end menu
11051
11052 @node About gnatelim
11053 @subsection About @code{gnatelim}
11054
11055 @noindent
11056 When a program shares a set of Ada
11057 packages with other programs, it may happen that this program uses
11058 only a fraction of the subprograms defined in these packages. The code
11059 created for these unused subprograms increases the size of the executable.
11060
11061 @code{gnatelim} tracks unused subprograms in an Ada program and
11062 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
11063 subprograms that are declared but never called. By placing the list of
11064 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
11065 recompiling your program, you may decrease the size of its executable,
11066 because the compiler will not generate the code for 'eliminated' subprograms.
11067 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
11068 information about this pragma.
11069
11070 @code{gnatelim} needs as its input data the name of the main subprogram.
11071
11072 If a set of source files is specified as @code{gnatelim} arguments, it
11073 treats these files as a complete set of sources making up a program to
11074 analyse, and analyses only these sources.
11075
11076 After a full successful build of the main subprogram @code{gnatelim} can be
11077 called without  specifying sources to analyse, in this case it computes
11078 the source closure of the main unit from the @file{ALI} files.
11079
11080 The following command will create the set of @file{ALI} files needed for
11081 @code{gnatelim}:
11082
11083 @smallexample
11084 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
11085 @end smallexample
11086
11087 Note that @code{gnatelim} does not need object files.
11088
11089 @node Running gnatelim
11090 @subsection Running @code{gnatelim}
11091
11092 @noindent
11093 @code{gnatelim} has the following command-line interface:
11094
11095 @smallexample
11096 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
11097 @end smallexample
11098
11099 @noindent
11100 @var{main_unit_name} should be a name of a source file that contains the main
11101 subprogram of a program (partition).
11102
11103 Each @var{filename} is the name (including the extension) of a source
11104 file to process. ``Wildcards'' are allowed, and
11105 the file name may contain path information.
11106
11107 @samp{@var{gcc_switches}} is a list of switches for
11108 @command{gcc}. They will be passed on to all compiler invocations made by
11109 @command{gnatelim} to generate the ASIS trees. Here you can provide
11110 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
11111 use the @option{-gnatec} switch to set the configuration file,
11112 use the @option{-gnat05} switch if sources should be compiled in
11113 Ada 2005 mode etc.
11114
11115 @code{gnatelim} has the following switches:
11116
11117 @table @option
11118 @c !sort!
11119 @item --version
11120 @cindex @option{--version} @command{gnatelim}
11121 Display Copyright and version, then exit disregarding all other options.
11122
11123 @item --help
11124 @cindex @option{--help} @command{gnatelim}
11125 Display usage, then exit disregarding all other options.
11126
11127 @item ^-files^/FILES^=@var{filename}
11128 @cindex @option{^-files^/FILES^} (@code{gnatelim})
11129 Take the argument source files from the specified file. This file should be an
11130 ordinary text file containing file names separated by spaces or
11131 line breaks. You can use this switch more than once in the same call to
11132 @command{gnatelim}. You also can combine this switch with
11133 an explicit list of files.
11134
11135 @item ^-log^/LOG^
11136 @cindex @option{^-log^/LOG^} (@command{gnatelim})
11137 Duplicate all the output sent to @file{stderr} into a log file. The log file
11138 is named @file{gnatelim.log} and is located in the current directory.
11139
11140 @item ^-log^/LOGFILE^=@var{filename}
11141 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
11142 Duplicate all the output sent to @file{stderr} into a specified log file.
11143
11144 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
11145 @item ^--no-elim-dispatch^/NO_DISPATCH^
11146 Do not generate pragmas for dispatching operations.
11147
11148 @item ^--ignore^/IGNORE^=@var{filename}
11149 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
11150 Do not generate pragmas for subprograms declared in the sources
11151 listed in a specified file
11152
11153 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
11154 @item ^-o^/OUTPUT^=@var{report_file}
11155 Put @command{gnatelim} output into a specified file. If this file already exists,
11156 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
11157 into @file{stderr}
11158
11159 @item ^-q^/QUIET^
11160 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
11161 Quiet mode: by default @code{gnatelim} outputs to the standard error
11162 stream the number of program units left to be processed. This option turns
11163 this trace off.
11164
11165 @cindex @option{^-t^/TIME^} (@command{gnatelim})
11166 @item ^-t^/TIME^
11167 Print out execution time.
11168
11169 @item ^-v^/VERBOSE^
11170 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
11171 Verbose mode: @code{gnatelim} version information is printed as Ada
11172 comments to the standard output stream. Also, in addition to the number of
11173 program units left @code{gnatelim} will output the name of the current unit
11174 being processed.
11175
11176 @item ^-wq^/WARNINGS=QUIET^
11177 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
11178 Quiet warning mode - some warnings are suppressed. In particular warnings that
11179 indicate that the analysed set of sources is incomplete to make up a
11180 partition and that some subprogram bodies are missing are not generated.
11181 @end table
11182
11183 @noindent
11184 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11185 driver (see @ref{The GNAT Driver and Project Files}).
11186
11187 @node Processing Precompiled Libraries
11188 @subsection Processing Precompiled Libraries
11189
11190 @noindent
11191 If some program uses a precompiled Ada library, it can be processed by
11192 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11193 Eliminate pragma for a subprogram if the body of this subprogram has not
11194 been analysed, this is a typical case for subprograms from precompiled
11195 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11196 warnings about missing source files and non-analyzed subprogram bodies
11197 that can be generated when processing precompiled Ada libraries.
11198
11199 @node Correcting the List of Eliminate Pragmas
11200 @subsection Correcting the List of Eliminate Pragmas
11201
11202 @noindent
11203 In some rare cases @code{gnatelim} may try to eliminate
11204 subprograms that are actually called in the program. In this case, the
11205 compiler will generate an error message of the form:
11206
11207 @smallexample
11208 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11209 @end smallexample
11210
11211 @noindent
11212 You will need to manually remove the wrong @code{Eliminate} pragmas from
11213 the configuration file indicated in the error message. You should recompile
11214 your program from scratch after that, because you need a consistent
11215 configuration file(s) during the entire compilation.
11216
11217 @node Making Your Executables Smaller
11218 @subsection Making Your Executables Smaller
11219
11220 @noindent
11221 In order to get a smaller executable for your program you now have to
11222 recompile the program completely with the configuration file containing
11223 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11224 @file{gnat.adc} file located in your current directory, just do:
11225
11226 @smallexample
11227 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11228 @end smallexample
11229
11230 @noindent
11231 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11232 recompile everything
11233 with the set of pragmas @code{Eliminate} that you have obtained with
11234 @command{gnatelim}).
11235
11236 Be aware that the set of @code{Eliminate} pragmas is specific to each
11237 program. It is not recommended to merge sets of @code{Eliminate}
11238 pragmas created for different programs in one configuration file.
11239
11240 @node Summary of the gnatelim Usage Cycle
11241 @subsection Summary of the @code{gnatelim} Usage Cycle
11242
11243 @noindent
11244 Here is a quick summary of the steps to be taken in order to reduce
11245 the size of your executables with @code{gnatelim}. You may use
11246 other GNAT options to control the optimization level,
11247 to produce the debugging information, to set search path, etc.
11248
11249 @enumerate
11250 @item
11251 Create a complete set of @file{ALI} files (if the program has not been
11252 built already)
11253
11254 @smallexample
11255 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11256 @end smallexample
11257
11258 @item
11259 Generate a list of @code{Eliminate} pragmas in default configuration file
11260 @file{gnat.adc} in the current directory
11261 @smallexample
11262 @ifset vms
11263 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11264 @end ifset
11265 @ifclear vms
11266 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11267 @end ifclear
11268 @end smallexample
11269
11270 @item
11271 Recompile the application
11272
11273 @smallexample
11274 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11275 @end smallexample
11276
11277 @end enumerate
11278
11279 @node Reducing Size of Executables with unused subprogram/data elimination
11280 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11281 @findex unused subprogram/data elimination
11282
11283 @noindent
11284 This section describes how you can eliminate unused subprograms and data from
11285 your executable just by setting options at compilation time.
11286
11287 @menu
11288 * About unused subprogram/data elimination::
11289 * Compilation options::
11290 * Example of unused subprogram/data elimination::
11291 @end menu
11292
11293 @node About unused subprogram/data elimination
11294 @subsection About unused subprogram/data elimination
11295
11296 @noindent
11297 By default, an executable contains all code and data of its composing objects
11298 (directly linked or coming from statically linked libraries), even data or code
11299 never used by this executable.
11300
11301 This feature will allow you to eliminate such unused code from your
11302 executable, making it smaller (in disk and in memory).
11303
11304 This functionality is available on all Linux platforms except for the IA-64
11305 architecture and on all cross platforms using the ELF binary file format.
11306 In both cases GNU binutils version 2.16 or later are required to enable it.
11307
11308 @node Compilation options
11309 @subsection Compilation options
11310
11311 @noindent
11312 The operation of eliminating the unused code and data from the final executable
11313 is directly performed by the linker.
11314
11315 In order to do this, it has to work with objects compiled with the
11316 following options:
11317 @option{-ffunction-sections} @option{-fdata-sections}.
11318 @cindex @option{-ffunction-sections} (@command{gcc})
11319 @cindex @option{-fdata-sections} (@command{gcc})
11320 These options are usable with C and Ada files.
11321 They will place respectively each
11322 function or data in a separate section in the resulting object file.
11323
11324 Once the objects and static libraries are created with these options, the
11325 linker can perform the dead code elimination. You can do this by setting
11326 the @option{-Wl,--gc-sections} option to gcc command or in the
11327 @option{-largs} section of @command{gnatmake}. This will perform a
11328 garbage collection of code and data never referenced.
11329
11330 If the linker performs a partial link (@option{-r} ld linker option), then you
11331 will need to provide one or several entry point using the
11332 @option{-e} / @option{--entry} ld option.
11333
11334 Note that objects compiled without the @option{-ffunction-sections} and
11335 @option{-fdata-sections} options can still be linked with the executable.
11336 However, no dead code elimination will be performed on those objects (they will
11337 be linked as is).
11338
11339 The GNAT static library is now compiled with -ffunction-sections and
11340 -fdata-sections on some platforms. This allows you to eliminate the unused code
11341 and data of the GNAT library from your executable.
11342
11343 @node Example of unused subprogram/data elimination
11344 @subsection Example of unused subprogram/data elimination
11345
11346 @noindent
11347 Here is a simple example:
11348
11349 @smallexample @c ada
11350 with Aux;
11351
11352 procedure Test is
11353 begin
11354    Aux.Used (10);
11355 end Test;
11356
11357 package Aux is
11358    Used_Data   : Integer;
11359    Unused_Data : Integer;
11360
11361    procedure Used   (Data : Integer);
11362    procedure Unused (Data : Integer);
11363 end Aux;
11364
11365 package body Aux is
11366    procedure Used (Data : Integer) is
11367    begin
11368       Used_Data := Data;
11369    end Used;
11370
11371    procedure Unused (Data : Integer) is
11372    begin
11373       Unused_Data := Data;
11374    end Unused;
11375 end Aux;
11376 @end smallexample
11377
11378 @noindent
11379 @code{Unused} and @code{Unused_Data} are never referenced in this code
11380 excerpt, and hence they may be safely removed from the final executable.
11381
11382 @smallexample
11383 $ gnatmake test
11384
11385 $ nm test | grep used
11386 020015f0 T aux__unused
11387 02005d88 B aux__unused_data
11388 020015cc T aux__used
11389 02005d84 B aux__used_data
11390
11391 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11392      -largs -Wl,--gc-sections
11393
11394 $ nm test | grep used
11395 02005350 T aux__used
11396 0201ffe0 B aux__used_data
11397 @end smallexample
11398
11399 @noindent
11400 It can be observed that the procedure @code{Unused} and the object
11401 @code{Unused_Data} are removed by the linker when using the
11402 appropriate options.
11403
11404 @c ********************************
11405 @node Renaming Files with gnatchop
11406 @chapter Renaming Files with @code{gnatchop}
11407 @findex gnatchop
11408
11409 @noindent
11410 This chapter discusses how to handle files with multiple units by using
11411 the @code{gnatchop} utility. This utility is also useful in renaming
11412 files to meet the standard GNAT default file naming conventions.
11413
11414 @menu
11415 * Handling Files with Multiple Units::
11416 * Operating gnatchop in Compilation Mode::
11417 * Command Line for gnatchop::
11418 * Switches for gnatchop::
11419 * Examples of gnatchop Usage::
11420 @end menu
11421
11422 @node Handling Files with Multiple Units
11423 @section Handling Files with Multiple Units
11424
11425 @noindent
11426 The basic compilation model of GNAT requires that a file submitted to the
11427 compiler have only one unit and there be a strict correspondence
11428 between the file name and the unit name.
11429
11430 The @code{gnatchop} utility allows both of these rules to be relaxed,
11431 allowing GNAT to process files which contain multiple compilation units
11432 and files with arbitrary file names. @code{gnatchop}
11433 reads the specified file and generates one or more output files,
11434 containing one unit per file. The unit and the file name correspond,
11435 as required by GNAT.
11436
11437 If you want to permanently restructure a set of ``foreign'' files so that
11438 they match the GNAT rules, and do the remaining development using the
11439 GNAT structure, you can simply use @command{gnatchop} once, generate the
11440 new set of files and work with them from that point on.
11441
11442 Alternatively, if you want to keep your files in the ``foreign'' format,
11443 perhaps to maintain compatibility with some other Ada compilation
11444 system, you can set up a procedure where you use @command{gnatchop} each
11445 time you compile, regarding the source files that it writes as temporary
11446 files that you throw away.
11447
11448 Note that if your file containing multiple units starts with a byte order
11449 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11450 will each start with a copy of this BOM, meaning that they can be compiled
11451 automatically in UTF-8 mode without needing to specify an explicit encoding.
11452
11453 @node Operating gnatchop in Compilation Mode
11454 @section Operating gnatchop in Compilation Mode
11455
11456 @noindent
11457 The basic function of @code{gnatchop} is to take a file with multiple units
11458 and split it into separate files. The boundary between files is reasonably
11459 clear, except for the issue of comments and pragmas. In default mode, the
11460 rule is that any pragmas between units belong to the previous unit, except
11461 that configuration pragmas always belong to the following unit. Any comments
11462 belong to the following unit. These rules
11463 almost always result in the right choice of
11464 the split point without needing to mark it explicitly and most users will
11465 find this default to be what they want. In this default mode it is incorrect to
11466 submit a file containing only configuration pragmas, or one that ends in
11467 configuration pragmas, to @code{gnatchop}.
11468
11469 However, using a special option to activate ``compilation mode'',
11470 @code{gnatchop}
11471 can perform another function, which is to provide exactly the semantics
11472 required by the RM for handling of configuration pragmas in a compilation.
11473 In the absence of configuration pragmas (at the main file level), this
11474 option has no effect, but it causes such configuration pragmas to be handled
11475 in a quite different manner.
11476
11477 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11478 only configuration pragmas, then this file is appended to the
11479 @file{gnat.adc} file in the current directory. This behavior provides
11480 the required behavior described in the RM for the actions to be taken
11481 on submitting such a file to the compiler, namely that these pragmas
11482 should apply to all subsequent compilations in the same compilation
11483 environment. Using GNAT, the current directory, possibly containing a
11484 @file{gnat.adc} file is the representation
11485 of a compilation environment. For more information on the
11486 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11487
11488 Second, in compilation mode, if @code{gnatchop}
11489 is given a file that starts with
11490 configuration pragmas, and contains one or more units, then these
11491 configuration pragmas are prepended to each of the chopped files. This
11492 behavior provides the required behavior described in the RM for the
11493 actions to be taken on compiling such a file, namely that the pragmas
11494 apply to all units in the compilation, but not to subsequently compiled
11495 units.
11496
11497 Finally, if configuration pragmas appear between units, they are appended
11498 to the previous unit. This results in the previous unit being illegal,
11499 since the compiler does not accept configuration pragmas that follow
11500 a unit. This provides the required RM behavior that forbids configuration
11501 pragmas other than those preceding the first compilation unit of a
11502 compilation.
11503
11504 For most purposes, @code{gnatchop} will be used in default mode. The
11505 compilation mode described above is used only if you need exactly
11506 accurate behavior with respect to compilations, and you have files
11507 that contain multiple units and configuration pragmas. In this
11508 circumstance the use of @code{gnatchop} with the compilation mode
11509 switch provides the required behavior, and is for example the mode
11510 in which GNAT processes the ACVC tests.
11511
11512 @node Command Line for gnatchop
11513 @section Command Line for @code{gnatchop}
11514
11515 @noindent
11516 The @code{gnatchop} command has the form:
11517
11518 @smallexample
11519 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11520 @c      @ovar{directory}
11521 @c Expanding @ovar macro inline (explanation in macro def comments)
11522 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11523       @r{[}@var{directory}@r{]}
11524 @end smallexample
11525
11526 @noindent
11527 The only required argument is the file name of the file to be chopped.
11528 There are no restrictions on the form of this file name. The file itself
11529 contains one or more Ada units, in normal GNAT format, concatenated
11530 together. As shown, more than one file may be presented to be chopped.
11531
11532 When run in default mode, @code{gnatchop} generates one output file in
11533 the current directory for each unit in each of the files.
11534
11535 @var{directory}, if specified, gives the name of the directory to which
11536 the output files will be written. If it is not specified, all files are
11537 written to the current directory.
11538
11539 For example, given a
11540 file called @file{hellofiles} containing
11541
11542 @smallexample @c ada
11543 @group
11544 @cartouche
11545 procedure hello;
11546
11547 with Text_IO; use Text_IO;
11548 procedure hello is
11549 begin
11550    Put_Line ("Hello");
11551 end hello;
11552 @end cartouche
11553 @end group
11554 @end smallexample
11555
11556 @noindent
11557 the command
11558
11559 @smallexample
11560 $ gnatchop ^hellofiles^HELLOFILES.^
11561 @end smallexample
11562
11563 @noindent
11564 generates two files in the current directory, one called
11565 @file{hello.ads} containing the single line that is the procedure spec,
11566 and the other called @file{hello.adb} containing the remaining text. The
11567 original file is not affected. The generated files can be compiled in
11568 the normal manner.
11569
11570 @noindent
11571 When gnatchop is invoked on a file that is empty or that contains only empty
11572 lines and/or comments, gnatchop will not fail, but will not produce any
11573 new sources.
11574
11575 For example, given a
11576 file called @file{toto.txt} containing
11577
11578 @smallexample @c ada
11579 @group
11580 @cartouche
11581 --  Just a comment
11582 @end cartouche
11583 @end group
11584 @end smallexample
11585
11586 @noindent
11587 the command
11588
11589 @smallexample
11590 $ gnatchop ^toto.txt^TOT.TXT^
11591 @end smallexample
11592
11593 @noindent
11594 will not produce any new file and will result in the following warnings:
11595
11596 @smallexample
11597 toto.txt:1:01: warning: empty file, contains no compilation units
11598 no compilation units found
11599 no source files written
11600 @end smallexample
11601
11602 @node Switches for gnatchop
11603 @section Switches for @code{gnatchop}
11604
11605 @noindent
11606 @command{gnatchop} recognizes the following switches:
11607
11608 @table @option
11609 @c !sort!
11610
11611 @item --version
11612 @cindex @option{--version} @command{gnatchop}
11613 Display Copyright and version, then exit disregarding all other options.
11614
11615 @item --help
11616 @cindex @option{--help} @command{gnatchop}
11617 If @option{--version} was not used, display usage, then exit disregarding
11618 all other options.
11619
11620 @item ^-c^/COMPILATION^
11621 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11622 Causes @code{gnatchop} to operate in compilation mode, in which
11623 configuration pragmas are handled according to strict RM rules. See
11624 previous section for a full description of this mode.
11625
11626 @ifclear vms
11627 @item -gnat@var{xxx}
11628 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11629 used to parse the given file. Not all @var{xxx} options make sense,
11630 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11631 process a source file that uses Latin-2 coding for identifiers.
11632 @end ifclear
11633
11634 @item ^-h^/HELP^
11635 Causes @code{gnatchop} to generate a brief help summary to the standard
11636 output file showing usage information.
11637
11638 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11639 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11640 Limit generated file names to the specified number @code{mm}
11641 of characters.
11642 This is useful if the
11643 resulting set of files is required to be interoperable with systems
11644 which limit the length of file names.
11645 @ifset vms
11646 If no value is given, or
11647 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11648 a default of 39, suitable for OpenVMS Alpha
11649 Systems, is assumed
11650 @end ifset
11651 @ifclear vms
11652 No space is allowed between the @option{-k} and the numeric value. The numeric
11653 value may be omitted in which case a default of @option{-k8},
11654 suitable for use
11655 with DOS-like file systems, is used. If no @option{-k} switch
11656 is present then
11657 there is no limit on the length of file names.
11658 @end ifclear
11659
11660 @item ^-p^/PRESERVE^
11661 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11662 Causes the file ^modification^creation^ time stamp of the input file to be
11663 preserved and used for the time stamp of the output file(s). This may be
11664 useful for preserving coherency of time stamps in an environment where
11665 @code{gnatchop} is used as part of a standard build process.
11666
11667 @item ^-q^/QUIET^
11668 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11669 Causes output of informational messages indicating the set of generated
11670 files to be suppressed. Warnings and error messages are unaffected.
11671
11672 @item ^-r^/REFERENCE^
11673 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11674 @findex Source_Reference
11675 Generate @code{Source_Reference} pragmas. Use this switch if the output
11676 files are regarded as temporary and development is to be done in terms
11677 of the original unchopped file. This switch causes
11678 @code{Source_Reference} pragmas to be inserted into each of the
11679 generated files to refers back to the original file name and line number.
11680 The result is that all error messages refer back to the original
11681 unchopped file.
11682 In addition, the debugging information placed into the object file (when
11683 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11684 specified)
11685 also refers back to this original file so that tools like profilers and
11686 debuggers will give information in terms of the original unchopped file.
11687
11688 If the original file to be chopped itself contains
11689 a @code{Source_Reference}
11690 pragma referencing a third file, then gnatchop respects
11691 this pragma, and the generated @code{Source_Reference} pragmas
11692 in the chopped file refer to the original file, with appropriate
11693 line numbers. This is particularly useful when @code{gnatchop}
11694 is used in conjunction with @code{gnatprep} to compile files that
11695 contain preprocessing statements and multiple units.
11696
11697 @item ^-v^/VERBOSE^
11698 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11699 Causes @code{gnatchop} to operate in verbose mode. The version
11700 number and copyright notice are output, as well as exact copies of
11701 the gnat1 commands spawned to obtain the chop control information.
11702
11703 @item ^-w^/OVERWRITE^
11704 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11705 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11706 fatal error if there is already a file with the same name as a
11707 file it would otherwise output, in other words if the files to be
11708 chopped contain duplicated units. This switch bypasses this
11709 check, and causes all but the last instance of such duplicated
11710 units to be skipped.
11711
11712 @ifclear vms
11713 @item --GCC=@var{xxxx}
11714 @cindex @option{--GCC=} (@code{gnatchop})
11715 Specify the path of the GNAT parser to be used. When this switch is used,
11716 no attempt is made to add the prefix to the GNAT parser executable.
11717 @end ifclear
11718 @end table
11719
11720 @node Examples of gnatchop Usage
11721 @section Examples of @code{gnatchop} Usage
11722
11723 @table @code
11724 @ifset vms
11725 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11726 @end ifset
11727 @ifclear vms
11728 @item gnatchop -w hello_s.ada prerelease/files
11729 @end ifclear
11730
11731 Chops the source file @file{hello_s.ada}. The output files will be
11732 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11733 overwriting any
11734 files with matching names in that directory (no files in the current
11735 directory are modified).
11736
11737 @item gnatchop ^archive^ARCHIVE.^
11738 Chops the source file @file{^archive^ARCHIVE.^}
11739 into the current directory. One
11740 useful application of @code{gnatchop} is in sending sets of sources
11741 around, for example in email messages. The required sources are simply
11742 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11743 command), and then
11744 @command{gnatchop} is used at the other end to reconstitute the original
11745 file names.
11746
11747 @item gnatchop file1 file2 file3 direc
11748 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11749 the resulting files in the directory @file{direc}. Note that if any units
11750 occur more than once anywhere within this set of files, an error message
11751 is generated, and no files are written. To override this check, use the
11752 @option{^-w^/OVERWRITE^} switch,
11753 in which case the last occurrence in the last file will
11754 be the one that is output, and earlier duplicate occurrences for a given
11755 unit will be skipped.
11756 @end table
11757
11758 @node Configuration Pragmas
11759 @chapter Configuration Pragmas
11760 @cindex Configuration pragmas
11761 @cindex Pragmas, configuration
11762
11763 @menu
11764 * Handling of Configuration Pragmas::
11765 * The Configuration Pragmas Files::
11766 @end menu
11767
11768 @noindent
11769 Configuration pragmas include those pragmas described as
11770 such in the Ada Reference Manual, as well as
11771 implementation-dependent pragmas that are configuration pragmas.
11772 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11773 for details on these additional GNAT-specific configuration pragmas.
11774 Most notably, the pragma @code{Source_File_Name}, which allows
11775 specifying non-default names for source files, is a configuration
11776 pragma. The following is a complete list of configuration pragmas
11777 recognized by GNAT:
11778
11779 @smallexample
11780    Ada_83
11781    Ada_95
11782    Ada_05
11783    Ada_2005
11784    Ada_12
11785    Ada_2012
11786    Annotate
11787    Assertion_Policy
11788    Assume_No_Invalid_Values
11789    C_Pass_By_Copy
11790    Check_Name
11791    Check_Policy
11792    Compile_Time_Error
11793    Compile_Time_Warning
11794    Compiler_Unit
11795    Component_Alignment
11796    Convention_Identifier
11797    Debug_Policy
11798    Detect_Blocking
11799    Default_Storage_Pool
11800    Discard_Names
11801    Elaboration_Checks
11802    Eliminate
11803    Extend_System
11804    Extensions_Allowed
11805    External_Name_Casing
11806    Fast_Math
11807    Favor_Top_Level
11808    Float_Representation
11809    Implicit_Packing
11810    Initialize_Scalars
11811    Interrupt_State
11812    License
11813    Locking_Policy
11814    Long_Float
11815    No_Run_Time
11816    No_Strict_Aliasing
11817    Normalize_Scalars
11818    Optimize_Alignment
11819    Persistent_BSS
11820    Polling
11821    Priority_Specific_Dispatching
11822    Profile
11823    Profile_Warnings
11824    Propagate_Exceptions
11825    Queuing_Policy
11826    Ravenscar
11827    Restricted_Run_Time
11828    Restrictions
11829    Restrictions_Warnings
11830    Reviewable
11831    Short_Circuit_And_Or
11832    Source_File_Name
11833    Source_File_Name_Project
11834    SPARK_Mode
11835    Style_Checks
11836    Suppress
11837    Suppress_Exception_Locations
11838    Task_Dispatching_Policy
11839    Universal_Data
11840    Unsuppress
11841    Use_VADS_Size
11842    Validity_Checks
11843    Warnings
11844    Wide_Character_Encoding
11845 @end smallexample
11846
11847 @node Handling of Configuration Pragmas
11848 @section Handling of Configuration Pragmas
11849
11850 Configuration pragmas may either appear at the start of a compilation
11851 unit, or they can appear in a configuration pragma file to apply to
11852 all compilations performed in a given compilation environment.
11853
11854 GNAT also provides the @code{gnatchop} utility to provide an automatic
11855 way to handle configuration pragmas following the semantics for
11856 compilations (that is, files with multiple units), described in the RM.
11857 See @ref{Operating gnatchop in Compilation Mode} for details.
11858 However, for most purposes, it will be more convenient to edit the
11859 @file{gnat.adc} file that contains configuration pragmas directly,
11860 as described in the following section.
11861
11862 In the case of @code{Restrictions} pragmas appearing as configuration
11863 pragmas in individual compilation units, the exact handling depends on
11864 the type of restriction.
11865
11866 Restrictions that require partition-wide consistency (like
11867 @code{No_Tasking}) are
11868 recognized wherever they appear
11869 and can be freely inherited, e.g. from a with'ed unit to the with'ing
11870 unit. This makes sense since the binder will in any case insist on seeing
11871 consistent use, so any unit not conforming to any restrictions that are
11872 anywhere in the partition will be rejected, and you might as well find
11873 that out at compile time rather than at bind time.
11874
11875 For restrictions that do not require partition-wide consistency, e.g.
11876 SPARK or No_Implementation_Attributes, in general the restriction applies
11877 only to the unit in which the pragma appears, and not to any other units.
11878
11879 The exception is No_Elaboration_Code which always applies to the entire
11880 object file from a compilation, i.e. to the body, spec, and all subunits.
11881 This restriction can be specified in a configuration pragma file, or it
11882 can be on the body and/or the spec (in eithe case it applies to all the
11883 relevant units). It can appear on a subunit only if it has previously
11884 appeared in the body of spec.
11885
11886 @node The Configuration Pragmas Files
11887 @section The Configuration Pragmas Files
11888 @cindex @file{gnat.adc}
11889
11890 @noindent
11891 In GNAT a compilation environment is defined by the current
11892 directory at the time that a compile command is given. This current
11893 directory is searched for a file whose name is @file{gnat.adc}. If
11894 this file is present, it is expected to contain one or more
11895 configuration pragmas that will be applied to the current compilation.
11896 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11897 considered.
11898
11899 Configuration pragmas may be entered into the @file{gnat.adc} file
11900 either by running @code{gnatchop} on a source file that consists only of
11901 configuration pragmas, or more conveniently  by
11902 direct editing of the @file{gnat.adc} file, which is a standard format
11903 source file.
11904
11905 In addition to @file{gnat.adc}, additional files containing configuration
11906 pragmas may be applied to the current compilation using the switch
11907 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11908 contains only configuration pragmas. These configuration pragmas are
11909 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11910 is present and switch @option{-gnatA} is not used).
11911
11912 It is allowed to specify several switches @option{-gnatec}, all of which
11913 will be taken into account.
11914
11915 If you are using project file, a separate mechanism is provided using
11916 project attributes, see @ref{Specifying Configuration Pragmas} for more
11917 details.
11918
11919 @ifset vms
11920 Of special interest to GNAT OpenVMS Alpha is the following
11921 configuration pragma:
11922
11923 @smallexample @c ada
11924 @cartouche
11925 pragma Extend_System (Aux_DEC);
11926 @end cartouche
11927 @end smallexample
11928
11929 @noindent
11930 In the presence of this pragma, GNAT adds to the definition of the
11931 predefined package SYSTEM all the additional types and subprograms that are
11932 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11933 @end ifset
11934
11935 @node Handling Arbitrary File Naming Conventions with gnatname
11936 @chapter Handling Arbitrary File Naming Conventions with @code{gnatname}
11937 @cindex Arbitrary File Naming Conventions
11938
11939 @menu
11940 * Arbitrary File Naming Conventions::
11941 * Running gnatname::
11942 * Switches for gnatname::
11943 * Examples of gnatname Usage::
11944 @end menu
11945
11946 @node Arbitrary File Naming Conventions
11947 @section Arbitrary File Naming Conventions
11948
11949 @noindent
11950 The GNAT compiler must be able to know the source file name of a compilation
11951 unit.  When using the standard GNAT default file naming conventions
11952 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11953 does not need additional information.
11954
11955 @noindent
11956 When the source file names do not follow the standard GNAT default file naming
11957 conventions, the GNAT compiler must be given additional information through
11958 a configuration pragmas file (@pxref{Configuration Pragmas})
11959 or a project file.
11960 When the non-standard file naming conventions are well-defined,
11961 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11962 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11963 if the file naming conventions are irregular or arbitrary, a number
11964 of pragma @code{Source_File_Name} for individual compilation units
11965 must be defined.
11966 To help maintain the correspondence between compilation unit names and
11967 source file names within the compiler,
11968 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11969 set of files.
11970
11971 @node Running gnatname
11972 @section Running @code{gnatname}
11973
11974 @noindent
11975 The usual form of the @code{gnatname} command is
11976
11977 @smallexample
11978 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11979 @c       @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11980 @c Expanding @ovar macro inline (explanation in macro def comments)
11981 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11982       @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11983 @end smallexample
11984
11985 @noindent
11986 All of the arguments are optional. If invoked without any argument,
11987 @code{gnatname} will display its usage.
11988
11989 @noindent
11990 When used with at least one naming pattern, @code{gnatname} will attempt to
11991 find all the compilation units in files that follow at least one of the
11992 naming patterns. To find these compilation units,
11993 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11994 regular files.
11995
11996 @noindent
11997 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11998 Each Naming Pattern is enclosed between double quotes (or single
11999 quotes on Windows).
12000 A Naming Pattern is a regular expression similar to the wildcard patterns
12001 used in file names by the Unix shells or the DOS prompt.
12002
12003 @noindent
12004 @code{gnatname} may be called with several sections of directories/patterns.
12005 Sections are separated by switch @code{--and}. In each section, there must be
12006 at least one pattern. If no directory is specified in a section, the current
12007 directory (or the project directory is @code{-P} is used) is implied.
12008 The options other that the directory switches and the patterns apply globally
12009 even if they are in different sections.
12010
12011 @noindent
12012 Examples of Naming Patterns are
12013
12014 @smallexample
12015    "*.[12].ada"
12016    "*.ad[sb]*"
12017    "body_*"    "spec_*"
12018 @end smallexample
12019
12020 @noindent
12021 For a more complete description of the syntax of Naming Patterns,
12022 see the second kind of regular expressions described in @file{g-regexp.ads}
12023 (the ``Glob'' regular expressions).
12024
12025 @noindent
12026 When invoked with no switch @code{-P}, @code{gnatname} will create a
12027 configuration pragmas file @file{gnat.adc} in the current working directory,
12028 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
12029 unit.
12030
12031 @node Switches for gnatname
12032 @section Switches for @code{gnatname}
12033
12034 @noindent
12035 Switches for @code{gnatname} must precede any specified Naming Pattern.
12036
12037 @noindent
12038 You may specify any of the following switches to @code{gnatname}:
12039
12040 @table @option
12041 @c !sort!
12042
12043 @item --version
12044 @cindex @option{--version} @command{gnatname}
12045 Display Copyright and version, then exit disregarding all other options.
12046
12047 @item --help
12048 @cindex @option{--help} @command{gnatname}
12049 If @option{--version} was not used, display usage, then exit disregarding
12050 all other options.
12051
12052 @item --subdirs=<dir>
12053 Real object, library or exec directories are subdirectories <dir> of the
12054 specified ones.
12055
12056 @item --no-backup
12057 Do not create a backup copy of an existing project file.
12058
12059 @item --and
12060 Start another section of directories/patterns.
12061
12062 @item ^-c^/CONFIG_FILE=^@file{file}
12063 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
12064 Create a configuration pragmas file @file{file} (instead of the default
12065 @file{gnat.adc}).
12066 @ifclear vms
12067 There may be zero, one or more space between @option{-c} and
12068 @file{file}.
12069 @end ifclear
12070 @file{file} may include directory information. @file{file} must be
12071 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
12072 When a switch @option{^-c^/CONFIG_FILE^} is
12073 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
12074
12075 @item ^-d^/SOURCE_DIRS=^@file{dir}
12076 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
12077 Look for source files in directory @file{dir}. There may be zero, one or more
12078 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
12079 @file{dir} may end with @code{/**}, that is it may be of the form
12080 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
12081 subdirectories, recursively, have to be searched for sources.
12082 When a switch @option{^-d^/SOURCE_DIRS^}
12083 is specified, the current working directory will not be searched for source
12084 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
12085 or @option{^-D^/DIR_FILES^} switch.
12086 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
12087 If @file{dir} is a relative path, it is relative to the directory of
12088 the configuration pragmas file specified with switch
12089 @option{^-c^/CONFIG_FILE^},
12090 or to the directory of the project file specified with switch
12091 @option{^-P^/PROJECT_FILE^} or,
12092 if neither switch @option{^-c^/CONFIG_FILE^}
12093 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
12094 current working directory. The directory
12095 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
12096
12097 @item ^-D^/DIRS_FILE=^@file{file}
12098 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
12099 Look for source files in all directories listed in text file @file{file}.
12100 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
12101 and @file{file}.
12102 @file{file} must be an existing, readable text file.
12103 Each nonempty line in @file{file} must be a directory.
12104 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
12105 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
12106 @file{file}.
12107
12108 @item -eL
12109 Follow symbolic links when processing project files.
12110
12111 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
12112 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
12113 Foreign patterns. Using this switch, it is possible to add sources of languages
12114 other than Ada to the list of sources of a project file.
12115 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
12116 For example,
12117 @smallexample
12118 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
12119 @end smallexample
12120 @noindent
12121 will look for Ada units in all files with the @file{.ada} extension,
12122 and will add to the list of file for project @file{prj.gpr} the C files
12123 with extension @file{.^c^C^}.
12124
12125 @item ^-h^/HELP^
12126 @cindex @option{^-h^/HELP^} (@code{gnatname})
12127 Output usage (help) information. The output is written to @file{stdout}.
12128
12129 @item ^-P^/PROJECT_FILE=^@file{proj}
12130 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
12131 Create or update project file @file{proj}. There may be zero, one or more space
12132 between @option{-P} and @file{proj}. @file{proj} may include directory
12133 information. @file{proj} must be writable.
12134 There may be only one switch @option{^-P^/PROJECT_FILE^}.
12135 When a switch @option{^-P^/PROJECT_FILE^} is specified,
12136 no switch @option{^-c^/CONFIG_FILE^} may be specified.
12137 On all platforms, except on VMS, when @code{gnatname} is invoked for an
12138 existing project file <proj>.gpr, a backup copy of the project file is created
12139 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
12140 non negative number that makes this backup copy a new file.
12141
12142 @item ^-v^/VERBOSE^
12143 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
12144 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
12145 This includes name of the file written, the name of the directories to search
12146 and, for each file in those directories whose name matches at least one of
12147 the Naming Patterns, an indication of whether the file contains a unit,
12148 and if so the name of the unit.
12149
12150 @item ^-v -v^/VERBOSE /VERBOSE^
12151 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
12152 Very Verbose mode. In addition to the output produced in verbose mode,
12153 for each file in the searched directories whose name matches none of
12154 the Naming Patterns, an indication is given that there is no match.
12155
12156 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
12157 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
12158 Excluded patterns. Using this switch, it is possible to exclude some files
12159 that would match the name patterns. For example,
12160 @smallexample
12161 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
12162 @end smallexample
12163 @noindent
12164 will look for Ada units in all files with the @file{.ada} extension,
12165 except those whose names end with @file{_nt.ada}.
12166
12167 @end table
12168
12169 @node Examples of gnatname Usage
12170 @section Examples of @code{gnatname} Usage
12171
12172 @ifset vms
12173 @smallexample
12174 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
12175 @end smallexample
12176 @end ifset
12177
12178 @ifclear vms
12179 @smallexample
12180 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
12181 @end smallexample
12182 @end ifclear
12183
12184 @noindent
12185 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
12186 and be writable. In addition, the directory
12187 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
12188 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
12189
12190 @ifclear vms
12191 Note the optional spaces after @option{-c} and @option{-d}.
12192 @end ifclear
12193
12194 @smallexample
12195 @ifclear vms
12196 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
12197   -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12198 @end ifclear
12199 @ifset vms
12200 $ gnatname  /PROJECT_FILE=[HOME.ME]PROJ
12201   /EXCLUDED_PATTERN=*_nt_body.ada
12202   /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
12203   /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
12204 @end ifset
12205 @end smallexample
12206
12207 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
12208 even in conjunction with one or several switches
12209 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
12210 are used in this example.
12211
12212 @c *****************************************
12213 @c * G N A T  P r o j e c t  M a n a g e r *
12214 @c *****************************************
12215
12216 @c ------ macros for projects.texi
12217 @c These macros are needed when building the gprbuild documentation, but
12218 @c should have no effect in the gnat user's guide
12219
12220 @macro CODESAMPLE{TXT}
12221 @smallexample
12222 @group
12223 \TXT\
12224 @end group
12225 @end smallexample
12226 @end macro
12227
12228 @macro PROJECTFILE{TXT}
12229 @CODESAMPLE{\TXT\}
12230 @end macro
12231
12232 @c simulates a newline when in a @CODESAMPLE
12233 @macro NL{}
12234 @end macro
12235
12236 @macro TIP{TXT}
12237 @quotation
12238 @noindent
12239 \TXT\
12240 @end quotation
12241 @end macro
12242
12243 @macro TIPHTML{TXT}
12244 \TXT\
12245 @end macro
12246
12247 @macro IMPORTANT{TXT}
12248 @quotation
12249 @noindent
12250 \TXT\
12251 @end quotation
12252
12253 @end macro
12254
12255 @macro NOTE{TXT}
12256 @quotation
12257 @noindent
12258 \TXT\
12259 @end quotation
12260 @end macro
12261
12262 @include projects.texi
12263
12264 @c ---------------------------------------------
12265 @c Tools Supporting Project Files
12266 @c ---------------------------------------------
12267
12268 @node Tools Supporting Project Files
12269 @chapter Tools Supporting Project Files
12270
12271 @noindent
12272
12273 @menu
12274 * gnatmake and Project Files::
12275 * The GNAT Driver and Project Files::
12276 @end menu
12277
12278 @c ---------------------------------------------
12279 @node gnatmake and Project Files
12280 @section gnatmake and Project Files
12281 @c ---------------------------------------------
12282
12283 @noindent
12284 This section covers several topics related to @command{gnatmake} and
12285 project files: defining ^switches^switches^ for @command{gnatmake}
12286 and for the tools that it invokes; specifying configuration pragmas;
12287 the use of the @code{Main} attribute; building and rebuilding library project
12288 files.
12289
12290 @menu
12291 * Switches Related to Project Files::
12292 * Switches and Project Files::
12293 * Specifying Configuration Pragmas::
12294 * Project Files and Main Subprograms::
12295 * Library Project Files::
12296 @end menu
12297
12298 @c ---------------------------------------------
12299 @node Switches Related to Project Files
12300 @subsection Switches Related to Project Files
12301 @c ---------------------------------------------
12302
12303 @noindent
12304 The following switches are used by GNAT tools that support project files:
12305
12306 @table @option
12307
12308 @item ^-P^/PROJECT_FILE=^@var{project}
12309 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
12310 Indicates the name of a project file. This project file will be parsed with
12311 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12312 if any, and using the external references indicated
12313 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12314 @ifclear vms
12315 There may zero, one or more spaces between @option{-P} and @var{project}.
12316 @end ifclear
12317
12318 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12319
12320 Since the Project Manager parses the project file only after all the switches
12321 on the command line are checked, the order of the switches
12322 @option{^-P^/PROJECT_FILE^},
12323 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12324 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12325
12326 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12327 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
12328 Indicates that external variable @var{name} has the value @var{value}.
12329 The Project Manager will use this value for occurrences of
12330 @code{external(name)} when parsing the project file.
12331
12332 @ifclear vms
12333 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12334 put between quotes.
12335 @smallexample
12336   -XOS=NT
12337   -X"user=John Doe"
12338 @end smallexample
12339 @end ifclear
12340
12341 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12342 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12343 @var{name}, only the last one is used.
12344
12345 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12346 takes precedence over the value of the same name in the environment.
12347
12348 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12349 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
12350 Indicates the verbosity of the parsing of GNAT project files.
12351
12352 @ifclear vms
12353 @option{-vP0} means Default;
12354 @option{-vP1} means Medium;
12355 @option{-vP2} means High.
12356 @end ifclear
12357
12358 @ifset vms
12359 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12360 HIGH.
12361 @end ifset
12362
12363 The default is ^Default^DEFAULT^: no output for syntactically correct
12364 project files.
12365 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12366 only the last one is used.
12367
12368 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
12369 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
12370 Add directory <dir> at the beginning of the project search path, in order,
12371 after the current working directory.
12372
12373 @ifclear vms
12374 @item -eL
12375 @cindex @option{-eL} (any project-aware tool)
12376 Follow all symbolic links when processing project files.
12377 @end ifclear
12378
12379 @item ^--subdirs^/SUBDIRS^=<subdir>
12380 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
12381 This switch is recognized by @command{gnatmake} and @command{gnatclean}. It
12382 indicate that the real directories (except the source directories) are the
12383 subdirectories <subdir> of the directories specified in the project files.
12384 This applies in particular to object directories, library directories and
12385 exec directories. If the subdirectories do not exist, they are created
12386 automatically.
12387
12388 @end table
12389
12390 @c ---------------------------------------------
12391 @node Switches and Project Files
12392 @subsection Switches and Project Files
12393 @c ---------------------------------------------
12394
12395 @noindent
12396 @ifset vms
12397 It is not currently possible to specify VMS style qualifiers in the project
12398 files; only Unix style ^switches^switches^ may be specified.
12399 @end ifset
12400
12401 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12402 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12403 attribute, a @code{Switches} attribute, or both;
12404 as their names imply, these ^switch^switch^-related
12405 attributes affect the ^switches^switches^ that are used for each of these GNAT
12406 components when
12407 @command{gnatmake} is invoked.  As will be explained below, these
12408 component-specific ^switches^switches^ precede
12409 the ^switches^switches^ provided on the @command{gnatmake} command line.
12410
12411 The @code{^Default_Switches^Default_Switches^} attribute is an attribute
12412 indexed by language name (case insensitive) whose value is a string list.
12413 For example:
12414
12415 @smallexample @c projectfile
12416 @group
12417 package Compiler is
12418   for ^Default_Switches^Default_Switches^ ("Ada")
12419       use ("^-gnaty^-gnaty^",
12420            "^-v^-v^");
12421 end Compiler;
12422 @end group
12423 @end smallexample
12424
12425 @noindent
12426 The @code{Switches} attribute is indexed on a file name (which may or may
12427 not be case sensitive, depending
12428 on the operating system) whose value is a string list.  For example:
12429
12430 @smallexample @c projectfile
12431 @group
12432 package Builder is
12433    for Switches ("main1.adb")
12434        use ("^-O2^-O2^");
12435    for Switches ("main2.adb")
12436        use ("^-g^-g^");
12437 end Builder;
12438 @end group
12439 @end smallexample
12440
12441 @noindent
12442 For the @code{Builder} package, the file names must designate source files
12443 for main subprograms.  For the @code{Binder} and @code{Linker} packages, the
12444 file names must designate @file{ALI} or source files for main subprograms.
12445 In each case just the file name without an explicit extension is acceptable.
12446
12447 For each tool used in a program build (@command{gnatmake}, the compiler, the
12448 binder, and the linker), the corresponding package @dfn{contributes} a set of
12449 ^switches^switches^ for each file on which the tool is invoked, based on the
12450 ^switch^switch^-related attributes defined in the package.
12451 In particular, the ^switches^switches^
12452 that each of these packages contributes for a given file @var{f} comprise:
12453
12454 @itemize @bullet
12455 @item the value of attribute @code{Switches (@var{f})},
12456   if it is specified in the package for the given file,
12457 @item otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12458   if it is specified in the package.
12459
12460 @end itemize
12461
12462 @noindent
12463 If neither of these attributes is defined in the package, then the package does
12464 not contribute any ^switches^switches^ for the given file.
12465
12466 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12467 two sets, in the following order: those contributed for the file
12468 by the @code{Builder} package;
12469 and the switches passed on the command line.
12470
12471 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12472 the ^switches^switches^ passed to the tool comprise three sets,
12473 in the following order:
12474
12475 @enumerate
12476 @item
12477 the applicable ^switches^switches^ contributed for the file
12478 by the @code{Builder} package in the project file supplied on the command line;
12479
12480 @item
12481 those contributed for the file by the package (in the relevant project file --
12482 see below) corresponding to the tool; and
12483
12484 @item
12485 the applicable switches passed on the command line.
12486 @end enumerate
12487
12488 The term @emph{applicable ^switches^switches^} reflects the fact that
12489 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12490 tools, depending on the individual ^switch^switch^.
12491
12492 @command{gnatmake} may invoke the compiler on source files from different
12493 projects. The Project Manager will use the appropriate project file to
12494 determine the @code{Compiler} package for each source file being compiled.
12495 Likewise for the @code{Binder} and @code{Linker} packages.
12496
12497 As an example, consider the following package in a project file:
12498
12499 @smallexample @c projectfile
12500 @group
12501 project Proj1 is
12502    package Compiler is
12503       for ^Default_Switches^Default_Switches^ ("Ada")
12504           use ("^-g^-g^");
12505       for Switches ("a.adb")
12506           use ("^-O1^-O1^");
12507       for Switches ("b.adb")
12508           use ("^-O2^-O2^",
12509                "^-gnaty^-gnaty^");
12510    end Compiler;
12511 end Proj1;
12512 @end group
12513 @end smallexample
12514
12515 @noindent
12516 If @command{gnatmake} is invoked with this project file, and it needs to
12517 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12518 @file{a.adb} will be compiled with the ^switch^switch^
12519 @option{^-O1^-O1^},
12520 @file{b.adb} with ^switches^switches^
12521 @option{^-O2^-O2^}
12522 and @option{^-gnaty^-gnaty^},
12523 and @file{c.adb} with @option{^-g^-g^}.
12524
12525 The following example illustrates the ordering of the ^switches^switches^
12526 contributed by different packages:
12527
12528 @smallexample @c projectfile
12529 @group
12530 project Proj2 is
12531    package Builder is
12532       for Switches ("main.adb")
12533           use ("^-g^-g^",
12534                "^-O1^-)1^",
12535                "^-f^-f^");
12536    end Builder;
12537 @end group
12538
12539 @group
12540    package Compiler is
12541       for Switches ("main.adb")
12542           use ("^-O2^-O2^");
12543    end Compiler;
12544 end Proj2;
12545 @end group
12546 @end smallexample
12547
12548 @noindent
12549 If you issue the command:
12550
12551 @smallexample
12552     gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
12553 @end smallexample
12554
12555 @noindent
12556 then the compiler will be invoked on @file{main.adb} with the following
12557 sequence of ^switches^switches^
12558
12559 @smallexample
12560    ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
12561 @end smallexample
12562
12563 @noindent
12564 with the last @option{^-O^-O^}
12565 ^switch^switch^ having precedence over the earlier ones;
12566 several other ^switches^switches^
12567 (such as @option{^-c^-c^}) are added implicitly.
12568
12569 The ^switches^switches^
12570 @option{^-g^-g^}
12571 and @option{^-O1^-O1^} are contributed by package
12572 @code{Builder},  @option{^-O2^-O2^} is contributed
12573 by the package @code{Compiler}
12574 and @option{^-O0^-O0^} comes from the command line.
12575
12576 The @option{^-g^-g^}
12577 ^switch^switch^ will also be passed in the invocation of
12578 @command{Gnatlink.}
12579
12580 A final example illustrates switch contributions from packages in different
12581 project files:
12582
12583 @smallexample @c projectfile
12584 @group
12585 project Proj3 is
12586    for Source_Files use ("pack.ads", "pack.adb");
12587    package Compiler is
12588       for ^Default_Switches^Default_Switches^ ("Ada")
12589           use ("^-gnata^-gnata^");
12590    end Compiler;
12591 end Proj3;
12592 @end group
12593
12594 @group
12595 with "Proj3";
12596 project Proj4 is
12597    for Source_Files use ("foo_main.adb", "bar_main.adb");
12598    package Builder is
12599       for Switches ("foo_main.adb")
12600           use ("^-s^-s^",
12601                "^-g^-g^");
12602    end Builder;
12603 end Proj4;
12604 @end group
12605
12606 @group
12607 -- Ada source file:
12608 with Pack;
12609 procedure Foo_Main is
12610    @dots{}
12611 end Foo_Main;
12612 @end group
12613 @end smallexample
12614
12615 @noindent
12616 If the command is
12617 @smallexample
12618 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
12619 @end smallexample
12620
12621 @noindent
12622 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
12623 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
12624 @option{^-gnato^-gnato^} (passed on the command line).
12625 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
12626 are @option{^-g^-g^} from @code{Proj4.Builder},
12627 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
12628 and @option{^-gnato^-gnato^} from the command line.
12629
12630 When using @command{gnatmake} with project files, some ^switches^switches^ or
12631 arguments may be expressed as relative paths. As the working directory where
12632 compilation occurs may change, these relative paths are converted to absolute
12633 paths. For the ^switches^switches^ found in a project file, the relative paths
12634 are relative to the project file directory, for the switches on the command
12635 line, they are relative to the directory where @command{gnatmake} is invoked.
12636 The ^switches^switches^ for which this occurs are:
12637 ^-I^-I^,
12638 ^-A^-A^,
12639 ^-L^-L^,
12640 ^-aO^-aO^,
12641 ^-aL^-aL^,
12642 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
12643 ^switch^switch^
12644 ^-o^-o^, object files specified in package @code{Linker} or after
12645 -largs on the command line). The exception to this rule is the ^switch^switch^
12646 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
12647
12648 @c ---------------------------------------------
12649 @node Specifying Configuration Pragmas
12650 @subsection Specifying Configuration Pragmas
12651 @c ---------------------------------------------
12652
12653 @noindent
12654 When using @command{gnatmake} with project files, if there exists a file
12655 @file{gnat.adc} that contains configuration pragmas, this file will be
12656 ignored.
12657
12658 Configuration pragmas can be defined by means of the following attributes in
12659 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
12660 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
12661
12662 Both these attributes are single string attributes. Their values is the path
12663 name of a file containing configuration pragmas. If a path name is relative,
12664 then it is relative to the project directory of the project file where the
12665 attribute is defined.
12666
12667 When compiling a source, the configuration pragmas used are, in order,
12668 those listed in the file designated by attribute
12669 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
12670 project file, if it is specified, and those listed in the file designated by
12671 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
12672 the project file of the source, if it exists.
12673
12674 @c ---------------------------------------------
12675 @node Project Files and Main Subprograms
12676 @subsection Project Files and Main Subprograms
12677 @c ---------------------------------------------
12678
12679 @noindent
12680 When using a project file, you can invoke @command{gnatmake}
12681 with one or several main subprograms, by specifying their source files on the
12682 command line.
12683
12684 @smallexample
12685     gnatmake ^-P^/PROJECT_FILE=^prj main1.adb main2.adb main3.adb
12686 @end smallexample
12687
12688 @noindent
12689 Each of these needs to be a source file of the same project, except
12690 when the switch ^-u^/UNIQUE^ is used.
12691
12692 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
12693 same project, one of the project in the tree rooted at the project specified
12694 on the command line. The package @code{Builder} of this common project, the
12695 "main project" is the one that is considered by @command{gnatmake}.
12696
12697 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
12698 imported directly or indirectly by the project specified on the command line.
12699 Note that if such a source file is not part of the project specified on the
12700 command line, the ^switches^switches^ found in package @code{Builder} of the
12701 project specified on the command line, if any, that are transmitted
12702 to the compiler will still be used, not those found in the project file of
12703 the source file.
12704
12705 When using a project file, you can also invoke @command{gnatmake} without
12706 explicitly specifying any main, and the effect depends on whether you have
12707 defined the @code{Main} attribute.  This attribute has a string list value,
12708 where each element in the list is the name of a source file (the file
12709 extension is optional) that contains a unit that can be a main subprogram.
12710
12711 If the @code{Main} attribute is defined in a project file as a non-empty
12712 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
12713 line, then invoking @command{gnatmake} with this project file but without any
12714 main on the command line is equivalent to invoking @command{gnatmake} with all
12715 the file names in the @code{Main} attribute on the command line.
12716
12717 Example:
12718 @smallexample @c projectfile
12719 @group
12720    project Prj is
12721       for Main use ("main1.adb", "main2.adb", "main3.adb");
12722    end Prj;
12723 @end group
12724 @end smallexample
12725
12726 @noindent
12727 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
12728 is equivalent to
12729 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1.adb main2.adb main3.adb"}.
12730
12731 When the project attribute @code{Main} is not specified, or is specified
12732 as an empty string list, or when the switch @option{-u} is used on the command
12733 line, then invoking @command{gnatmake} with no main on the command line will
12734 result in all immediate sources of the project file being checked, and
12735 potentially recompiled. Depending on the presence of the switch @option{-u},
12736 sources from other project files on which the immediate sources of the main
12737 project file depend are also checked and potentially recompiled. In other
12738 words, the @option{-u} switch is applied to all of the immediate sources of the
12739 main project file.
12740
12741 When no main is specified on the command line and attribute @code{Main} exists
12742 and includes several mains, or when several mains are specified on the
12743 command line, the default ^switches^switches^ in package @code{Builder} will
12744 be used for all mains, even if there are specific ^switches^switches^
12745 specified for one or several mains.
12746
12747 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
12748 the specific ^switches^switches^ for each main, if they are specified.
12749
12750 @c ---------------------------------------------
12751 @node Library Project Files
12752 @subsection Library Project Files
12753 @c ---------------------------------------------
12754
12755 @noindent
12756 When @command{gnatmake} is invoked with a main project file that is a library
12757 project file, it is not allowed to specify one or more mains on the command
12758 line.
12759
12760 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
12761 ^-l^/ACTION=LINK^ have special meanings.
12762
12763 @itemize @bullet
12764 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
12765   to @command{gnatmake} that @command{gnatbind} should be invoked for the
12766   library.
12767
12768 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
12769   to @command{gnatmake} that the binder generated file should be compiled
12770   (in the case of a stand-alone library) and that the library should be built.
12771 @end itemize
12772
12773 @c ---------------------------------------------
12774 @node The GNAT Driver and Project Files
12775 @section The GNAT Driver and Project Files
12776 @c ---------------------------------------------
12777
12778 @noindent
12779 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
12780 can benefit from project files:
12781 (@command{^gnatbind^gnatbind^},
12782 @command{^gnatcheck^gnatcheck^},
12783 @command{^gnatclean^gnatclean^},
12784 @command{^gnatelim^gnatelim^},
12785 @command{^gnatfind^gnatfind^},
12786 @command{^gnatlink^gnatlink^},
12787 @command{^gnatls^gnatls^},
12788 @command{^gnatmetric^gnatmetric^},
12789 @command{^gnatpp^gnatpp^},
12790 @command{^gnatstub^gnatstub^},
12791 and @command{^gnatxref^gnatxref^}). However, none of these tools can be invoked
12792 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
12793 They must be invoked through the @command{gnat} driver.
12794
12795 The @command{gnat} driver is a wrapper that accepts a number of commands and
12796 calls the corresponding tool. It was designed initially for VMS platforms (to
12797 convert VMS qualifiers to Unix-style switches), but it is now available on all
12798 GNAT platforms.
12799
12800 On non-VMS platforms, the @command{gnat} driver accepts the following commands
12801 (case insensitive):
12802
12803 @itemize @bullet
12804 @item BIND to invoke @command{^gnatbind^gnatbind^}
12805 @item CHOP to invoke @command{^gnatchop^gnatchop^}
12806 @item CLEAN to invoke @command{^gnatclean^gnatclean^}
12807 @item COMP or COMPILE to invoke the compiler
12808 @item ELIM to invoke @command{^gnatelim^gnatelim^}
12809 @item FIND to invoke @command{^gnatfind^gnatfind^}
12810 @item KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
12811 @item LINK to invoke @command{^gnatlink^gnatlink^}
12812 @item LS or LIST to invoke @command{^gnatls^gnatls^}
12813 @item MAKE to invoke @command{^gnatmake^gnatmake^}
12814 @item NAME to invoke @command{^gnatname^gnatname^}
12815 @item PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
12816 @item PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
12817 @item METRIC to invoke @command{^gnatmetric^gnatmetric^}
12818 @item STUB to invoke @command{^gnatstub^gnatstub^}
12819 @item XREF to invoke @command{^gnatxref^gnatxref^}
12820
12821 @end itemize
12822
12823 @noindent
12824 (note that the compiler is invoked using the command
12825 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
12826
12827 On non-VMS platforms, between @command{gnat} and the command, two
12828 special switches may be used:
12829
12830 @itemize @bullet
12831 @item @command{-v} to display the invocation of the tool.
12832 @item @command{-dn} to prevent the @command{gnat} driver from removing
12833   the temporary files it has created. These temporary files are
12834   configuration files and temporary file list files.
12835
12836 @end itemize
12837
12838 @noindent
12839 The command may be followed by switches and arguments for the invoked
12840 tool.
12841
12842 @smallexample
12843   gnat bind -C main.ali
12844   gnat ls -a main
12845   gnat chop foo.txt
12846 @end smallexample
12847
12848 @noindent
12849 Switches may also be put in text files, one switch per line, and the text
12850 files may be specified with their path name preceded by '@@'.
12851
12852 @smallexample
12853    gnat bind @@args.txt main.ali
12854 @end smallexample
12855
12856 @noindent
12857 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
12858 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
12859 (@option{^-P^/PROJECT_FILE^},
12860 @option{^-X^/EXTERNAL_REFERENCE^} and
12861 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
12862 the switches of the invoking tool.
12863
12864 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
12865 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
12866 the immediate sources of the specified project file.
12867
12868 When GNAT METRIC is used with a project file, but with no source
12869 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
12870 with all the immediate sources of the specified project file and with
12871 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
12872 of the project.
12873
12874 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
12875 a project file, no source is specified on the command line and
12876 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
12877 the underlying tool (^gnatpp^gnatpp^ or
12878 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
12879 not only for the immediate sources of the main project.
12880 @ifclear vms
12881 (-U stands for Universal or Union of the project files of the project tree)
12882 @end ifclear
12883
12884 For each of the following commands, there is optionally a corresponding
12885 package in the main project.
12886
12887 @itemize @bullet
12888 @item package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
12889
12890 @item package @code{Check} for command CHECK (invoking
12891   @code{^gnatcheck^gnatcheck^})
12892
12893 @item package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
12894
12895 @item package @code{Cross_Reference} for command XREF (invoking
12896   @code{^gnatxref^gnatxref^})
12897
12898 @item package @code{Eliminate} for command ELIM (invoking
12899   @code{^gnatelim^gnatelim^})
12900
12901 @item package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
12902
12903 @item package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
12904
12905 @item package @code{Gnatstub} for command STUB
12906   (invoking @code{^gnatstub^gnatstub^})
12907
12908 @item package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
12909
12910 @item package @code{Check} for command CHECK
12911   (invoking @code{^gnatcheck^gnatcheck^})
12912
12913 @item package @code{Metrics} for command METRIC
12914   (invoking @code{^gnatmetric^gnatmetric^})
12915
12916 @item package @code{Pretty_Printer} for command PP or PRETTY
12917   (invoking @code{^gnatpp^gnatpp^})
12918
12919 @end itemize
12920
12921 @noindent
12922 Package @code{Gnatls} has a unique attribute @code{Switches},
12923 a simple variable with a string list value. It contains ^switches^switches^
12924 for the invocation of @code{^gnatls^gnatls^}.
12925
12926 @smallexample @c projectfile
12927 @group
12928 project Proj1 is
12929    package gnatls is
12930       for Switches
12931           use ("^-a^-a^",
12932                "^-v^-v^");
12933    end gnatls;
12934 end Proj1;
12935 @end group
12936 @end smallexample
12937
12938 @noindent
12939 All other packages have two attribute @code{Switches} and
12940 @code{^Default_Switches^Default_Switches^}.
12941
12942 @code{Switches} is an indexed attribute, indexed by the
12943 source file name, that has a string list value: the ^switches^switches^ to be
12944 used when the tool corresponding to the package is invoked for the specific
12945 source file.
12946
12947 @code{^Default_Switches^Default_Switches^} is an attribute,
12948 indexed by  the programming language that has a string list value.
12949 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
12950 ^switches^switches^ for the invocation of the tool corresponding
12951 to the package, except if a specific @code{Switches} attribute
12952 is specified for the source file.
12953
12954 @smallexample @c projectfile
12955 @group
12956 project Proj is
12957
12958    for Source_Dirs use ("**");
12959
12960    package gnatls is
12961       for Switches use
12962           ("^-a^-a^",
12963            "^-v^-v^");
12964    end gnatls;
12965 @end group
12966 @group
12967
12968    package Compiler is
12969       for ^Default_Switches^Default_Switches^ ("Ada")
12970           use ("^-gnatv^-gnatv^",
12971                "^-gnatwa^-gnatwa^");
12972    end Binder;
12973 @end group
12974 @group
12975
12976    package Binder is
12977       for ^Default_Switches^Default_Switches^ ("Ada")
12978           use ("^-C^-C^",
12979                "^-e^-e^");
12980    end Binder;
12981 @end group
12982 @group
12983
12984    package Linker is
12985       for ^Default_Switches^Default_Switches^ ("Ada")
12986           use ("^-C^-C^");
12987       for Switches ("main.adb")
12988           use ("^-C^-C^",
12989                "^-v^-v^",
12990                "^-v^-v^");
12991    end Linker;
12992 @end group
12993 @group
12994
12995    package Finder is
12996       for ^Default_Switches^Default_Switches^ ("Ada")
12997            use ("^-a^-a^",
12998                 "^-f^-f^");
12999    end Finder;
13000 @end group
13001 @group
13002
13003    package Cross_Reference is
13004       for ^Default_Switches^Default_Switches^ ("Ada")
13005           use ("^-a^-a^",
13006                "^-f^-f^",
13007                "^-d^-d^",
13008                "^-u^-u^");
13009    end Cross_Reference;
13010 end Proj;
13011 @end group
13012 @end smallexample
13013
13014 @noindent
13015 With the above project file, commands such as
13016
13017 @smallexample
13018    ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13019    ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13020    ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13021    ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13022    ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13023 @end smallexample
13024
13025 @noindent
13026 will set up the environment properly and invoke the tool with the switches
13027 found in the package corresponding to the tool:
13028 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13029 except @code{Switches ("main.adb")}
13030 for @code{^gnatlink^gnatlink^}.
13031 It is also possible to invoke some of the tools,
13032 (@code{^gnatcheck^gnatcheck^},
13033 @code{^gnatmetric^gnatmetric^},
13034 and @code{^gnatpp^gnatpp^})
13035 on a set of project units thanks to the combination of the switches
13036 @option{-P}, @option{-U} and possibly the main unit when one is interested
13037 in its closure. For instance,
13038 @smallexample
13039 gnat metric -Pproj
13040 @end smallexample
13041
13042 @noindent
13043 will compute the metrics for all the immediate units of project
13044 @code{proj}.
13045 @smallexample
13046 gnat metric -Pproj -U
13047 @end smallexample
13048
13049 @noindent
13050 will compute the metrics for all the units of the closure of projects
13051 rooted at @code{proj}.
13052 @smallexample
13053 gnat metric -Pproj -U main_unit
13054 @end smallexample
13055
13056 @noindent
13057 will compute the metrics for the closure of units rooted at
13058 @code{main_unit}. This last possibility relies implicitly
13059 on @command{gnatbind}'s option @option{-R}. But if the argument files for the
13060 tool invoked by the @command{gnat} driver are explicitly  specified
13061 either directly or through the tool @option{-files} option, then the tool
13062 is called only for these explicitly specified files.
13063
13064 @c *****************************************
13065 @c * Cross-referencing tools
13066 @c *****************************************
13067
13068 @node The Cross-Referencing Tools gnatxref and gnatfind
13069 @chapter  The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13070 @findex gnatxref
13071 @findex gnatfind
13072
13073 @noindent
13074 The compiler generates cross-referencing information (unless
13075 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13076 This information indicates where in the source each entity is declared and
13077 referenced. Note that entities in package Standard are not included, but
13078 entities in all other predefined units are included in the output.
13079
13080 Before using any of these two tools, you need to compile successfully your
13081 application, so that GNAT gets a chance to generate the cross-referencing
13082 information.
13083
13084 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13085 information to provide the user with the capability to easily locate the
13086 declaration and references to an entity. These tools are quite similar,
13087 the difference being that @code{gnatfind} is intended for locating
13088 definitions and/or references to a specified entity or entities, whereas
13089 @code{gnatxref} is oriented to generating a full report of all
13090 cross-references.
13091
13092 To use these tools, you must not compile your application using the
13093 @option{-gnatx} switch on the @command{gnatmake} command line
13094 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13095 information will not be generated.
13096
13097 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
13098 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
13099
13100 @menu
13101 * Switches for gnatxref::
13102 * Switches for gnatfind::
13103 * Project Files for gnatxref and gnatfind::
13104 * Regular Expressions in gnatfind and gnatxref::
13105 * Examples of gnatxref Usage::
13106 * Examples of gnatfind Usage::
13107 @end menu
13108
13109 @node Switches for gnatxref
13110 @section @code{gnatxref} Switches
13111
13112 @noindent
13113 The command invocation for @code{gnatxref} is:
13114 @smallexample
13115 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
13116 @c Expanding @ovar macro inline (explanation in macro def comments)
13117 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
13118 @end smallexample
13119
13120 @noindent
13121 where
13122
13123 @table @var
13124 @item sourcefile1
13125 @itemx sourcefile2
13126 identifies the source files for which a report is to be generated. The
13127 ``with''ed units will be processed too. You must provide at least one file.
13128
13129 These file names are considered to be regular expressions, so for instance
13130 specifying @file{source*.adb} is the same as giving every file in the current
13131 directory whose name starts with @file{source} and whose extension is
13132 @file{adb}.
13133
13134 You shouldn't specify any directory name, just base names. @command{gnatxref}
13135 and @command{gnatfind} will be able to locate these files by themselves using
13136 the source path. If you specify directories, no result is produced.
13137
13138 @end table
13139
13140 @noindent
13141 The switches can be:
13142 @table @option
13143 @c !sort!
13144 @item --version
13145 @cindex @option{--version} @command{gnatxref}
13146 Display Copyright and version, then exit disregarding all other options.
13147
13148 @item --help
13149 @cindex @option{--help} @command{gnatxref}
13150 If @option{--version} was not used, display usage, then exit disregarding
13151 all other options.
13152
13153 @item ^-a^/ALL_FILES^
13154 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13155 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13156 the read-only files found in the library search path. Otherwise, these files
13157 will be ignored. This option can be used to protect Gnat sources or your own
13158 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13159 much faster, and their output much smaller. Read-only here refers to access
13160 or permissions status in the file system for the current user.
13161
13162 @item -aIDIR
13163 @cindex @option{-aIDIR} (@command{gnatxref})
13164 When looking for source files also look in directory DIR. The order in which
13165 source file search is undertaken is the same as for @command{gnatmake}.
13166
13167 @item -aODIR
13168 @cindex @option{-aODIR} (@command{gnatxref})
13169 When searching for library and object files, look in directory
13170 DIR. The order in which library files are searched is the same as for
13171 @command{gnatmake}.
13172
13173 @item -nostdinc
13174 @cindex @option{-nostdinc} (@command{gnatxref})
13175 Do not look for sources in the system default directory.
13176
13177 @item -nostdlib
13178 @cindex @option{-nostdlib} (@command{gnatxref})
13179 Do not look for library files in the system default directory.
13180
13181 @item --ext=@var{extension}
13182 @cindex @option{--ext} (@command{gnatxref})
13183 Specify an alternate ali file extension. The default is @code{ali} and other
13184 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
13185 switch. Note that if this switch overrides the default, which means that only
13186 the new extension will be considered.
13187
13188 @item --RTS=@var{rts-path}
13189 @cindex @option{--RTS} (@command{gnatxref})
13190 Specifies the default location of the runtime library. Same meaning as the
13191 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13192
13193 @item ^-d^/DERIVED_TYPES^
13194 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13195 If this switch is set @code{gnatxref} will output the parent type
13196 reference for each matching derived types.
13197
13198 @item ^-f^/FULL_PATHNAME^
13199 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13200 If this switch is set, the output file names will be preceded by their
13201 directory (if the file was found in the search path). If this switch is
13202 not set, the directory will not be printed.
13203
13204 @item ^-g^/IGNORE_LOCALS^
13205 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13206 If this switch is set, information is output only for library-level
13207 entities, ignoring local entities. The use of this switch may accelerate
13208 @code{gnatfind} and @code{gnatxref}.
13209
13210 @item -IDIR
13211 @cindex @option{-IDIR} (@command{gnatxref})
13212 Equivalent to @samp{-aODIR -aIDIR}.
13213
13214 @item -pFILE
13215 @cindex @option{-pFILE} (@command{gnatxref})
13216 Specify a project file to use @xref{GNAT Project Manager}.
13217 If you need to use the @file{.gpr}
13218 project files, you should use gnatxref through the GNAT driver
13219 (@command{gnat xref -Pproject}).
13220
13221 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13222 project file in the current directory.
13223
13224 If a project file is either specified or found by the tools, then the content
13225 of the source directory and object directory lines are added as if they
13226 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13227 and @samp{^-aO^OBJECT_SEARCH^}.
13228 @item ^-u^/UNUSED^
13229 Output only unused symbols. This may be really useful if you give your
13230 main compilation unit on the command line, as @code{gnatxref} will then
13231 display every unused entity and 'with'ed package.
13232
13233 @ifclear vms
13234 @item -v
13235 Instead of producing the default output, @code{gnatxref} will generate a
13236 @file{tags} file that can be used by vi. For examples how to use this
13237 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
13238 to the standard output, thus you will have to redirect it to a file.
13239 @end ifclear
13240
13241 @end table
13242
13243 @noindent
13244 All these switches may be in any order on the command line, and may even
13245 appear after the file names. They need not be separated by spaces, thus
13246 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13247 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13248
13249 @node Switches for gnatfind
13250 @section @code{gnatfind} Switches
13251
13252 @noindent
13253 The command line for @code{gnatfind} is:
13254
13255 @smallexample
13256 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13257 @c       @r{[}@var{file1} @var{file2} @dots{}]
13258 @c Expanding @ovar macro inline (explanation in macro def comments)
13259 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13260       @r{[}@var{file1} @var{file2} @dots{}@r{]}
13261 @end smallexample
13262
13263 @noindent
13264 where
13265
13266 @table @var
13267 @item pattern
13268 An entity will be output only if it matches the regular expression found
13269 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
13270
13271 Omitting the pattern is equivalent to specifying @samp{*}, which
13272 will match any entity. Note that if you do not provide a pattern, you
13273 have to provide both a sourcefile and a line.
13274
13275 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13276 for matching purposes. At the current time there is no support for
13277 8-bit codes other than Latin-1, or for wide characters in identifiers.
13278
13279 @item sourcefile
13280 @code{gnatfind} will look for references, bodies or declarations
13281 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
13282 and column @var{column}. See @ref{Examples of gnatfind Usage}
13283 for syntax examples.
13284
13285 @item line
13286 is a decimal integer identifying the line number containing
13287 the reference to the entity (or entities) to be located.
13288
13289 @item column
13290 is a decimal integer identifying the exact location on the
13291 line of the first character of the identifier for the
13292 entity reference. Columns are numbered from 1.
13293
13294 @item file1 file2 @dots{}
13295 The search will be restricted to these source files. If none are given, then
13296 the search will be done for every library file in the search path.
13297 These file must appear only after the pattern or sourcefile.
13298
13299 These file names are considered to be regular expressions, so for instance
13300 specifying @file{source*.adb} is the same as giving every file in the current
13301 directory whose name starts with @file{source} and whose extension is
13302 @file{adb}.
13303
13304 The location of the spec of the entity will always be displayed, even if it
13305 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{}  The
13306 occurrences of the entity in the separate units of the ones given on the
13307 command line will also be displayed.
13308
13309 Note that if you specify at least one file in this part, @code{gnatfind} may
13310 sometimes not be able to find the body of the subprograms.
13311
13312 @end table
13313
13314 @noindent
13315 At least one of 'sourcefile' or 'pattern' has to be present on
13316 the command line.
13317
13318 The following switches are available:
13319 @table @option
13320 @c !sort!
13321
13322 @cindex @option{--version} @command{gnatfind}
13323 Display Copyright and version, then exit disregarding all other options.
13324
13325 @item --help
13326 @cindex @option{--help} @command{gnatfind}
13327 If @option{--version} was not used, display usage, then exit disregarding
13328 all other options.
13329
13330 @item ^-a^/ALL_FILES^
13331 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
13332 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13333 the read-only files found in the library search path. Otherwise, these files
13334 will be ignored. This option can be used to protect Gnat sources or your own
13335 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13336 much faster, and their output much smaller. Read-only here refers to access
13337 or permission status in the file system for the current user.
13338
13339 @item -aIDIR
13340 @cindex @option{-aIDIR} (@command{gnatfind})
13341 When looking for source files also look in directory DIR. The order in which
13342 source file search is undertaken is the same as for @command{gnatmake}.
13343
13344 @item -aODIR
13345 @cindex @option{-aODIR} (@command{gnatfind})
13346 When searching for library and object files, look in directory
13347 DIR. The order in which library files are searched is the same as for
13348 @command{gnatmake}.
13349
13350 @item -nostdinc
13351 @cindex @option{-nostdinc} (@command{gnatfind})
13352 Do not look for sources in the system default directory.
13353
13354 @item -nostdlib
13355 @cindex @option{-nostdlib} (@command{gnatfind})
13356 Do not look for library files in the system default directory.
13357
13358 @item --ext=@var{extension}
13359 @cindex @option{--ext} (@command{gnatfind})
13360 Specify an alternate ali file extension. The default is @code{ali} and other
13361 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
13362 switch. Note that if this switch overrides the default, which means that only
13363 the new extension will be considered.
13364
13365 @item --RTS=@var{rts-path}
13366 @cindex @option{--RTS} (@command{gnatfind})
13367 Specifies the default location of the runtime library. Same meaning as the
13368 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13369
13370 @item ^-d^/DERIVED_TYPE_INFORMATION^
13371 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
13372 If this switch is set, then @code{gnatfind} will output the parent type
13373 reference for each matching derived types.
13374
13375 @item ^-e^/EXPRESSIONS^
13376 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
13377 By default, @code{gnatfind} accept the simple regular expression set for
13378 @samp{pattern}. If this switch is set, then the pattern will be
13379 considered as full Unix-style regular expression.
13380
13381 @item ^-f^/FULL_PATHNAME^
13382 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
13383 If this switch is set, the output file names will be preceded by their
13384 directory (if the file was found in the search path). If this switch is
13385 not set, the directory will not be printed.
13386
13387 @item ^-g^/IGNORE_LOCALS^
13388 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
13389 If this switch is set, information is output only for library-level
13390 entities, ignoring local entities. The use of this switch may accelerate
13391 @code{gnatfind} and @code{gnatxref}.
13392
13393 @item -IDIR
13394 @cindex @option{-IDIR} (@command{gnatfind})
13395 Equivalent to @samp{-aODIR -aIDIR}.
13396
13397 @item -pFILE
13398 @cindex @option{-pFILE} (@command{gnatfind})
13399 Specify a project file (@pxref{GNAT Project Manager}) to use.
13400 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13401 project file in the current directory.
13402
13403 If a project file is either specified or found by the tools, then the content
13404 of the source directory and object directory lines are added as if they
13405 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
13406 @samp{^-aO^/OBJECT_SEARCH^}.
13407
13408 @item ^-r^/REFERENCES^
13409 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
13410 By default, @code{gnatfind} will output only the information about the
13411 declaration, body or type completion of the entities. If this switch is
13412 set, the @code{gnatfind} will locate every reference to the entities in
13413 the files specified on the command line (or in every file in the search
13414 path if no file is given on the command line).
13415
13416 @item ^-s^/PRINT_LINES^
13417 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
13418 If this switch is set, then @code{gnatfind} will output the content
13419 of the Ada source file lines were the entity was found.
13420
13421 @item ^-t^/TYPE_HIERARCHY^
13422 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
13423 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13424 the specified type. It act like -d option but recursively from parent
13425 type to parent type. When this switch is set it is not possible to
13426 specify more than one file.
13427
13428 @end table
13429
13430 @noindent
13431 All these switches may be in any order on the command line, and may even
13432 appear after the file names. They need not be separated by spaces, thus
13433 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13434 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13435
13436 As stated previously, gnatfind will search in every directory in the
13437 search path. You can force it to look only in the current directory if
13438 you specify @code{*} at the end of the command line.
13439
13440 @node Project Files for gnatxref and gnatfind
13441 @section Project Files for @command{gnatxref} and @command{gnatfind}
13442
13443 @noindent
13444 Project files allow a programmer to specify how to compile its
13445 application, where to find sources, etc.  These files are used
13446 @ifclear vms
13447 primarily by GPS, but they can also be used
13448 @end ifclear
13449 by the two tools
13450 @code{gnatxref} and @code{gnatfind}.
13451
13452 A project file name must end with @file{.gpr}. If a single one is
13453 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13454 extract the information from it. If multiple project files are found, none of
13455 them is read, and you have to use the @samp{-p} switch to specify the one
13456 you want to use.
13457
13458 The following lines can be included, even though most of them have default
13459 values which can be used in most cases.
13460 The lines can be entered in any order in the file.
13461 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
13462 each line. If you have multiple instances, only the last one is taken into
13463 account.
13464
13465 @table @code
13466 @item src_dir=DIR
13467 [default: @code{"^./^[]^"}]
13468 specifies a directory where to look for source files. Multiple @code{src_dir}
13469 lines can be specified and they will be searched in the order they
13470 are specified.
13471
13472 @item obj_dir=DIR
13473 [default: @code{"^./^[]^"}]
13474 specifies a directory where to look for object and library files. Multiple
13475 @code{obj_dir} lines can be specified, and they will be searched in the order
13476 they are specified
13477
13478 @item comp_opt=SWITCHES
13479 [default: @code{""}]
13480 creates a variable which can be referred to subsequently by using
13481 the @code{$@{comp_opt@}} notation. This is intended to store the default
13482 switches given to @command{gnatmake} and @command{gcc}.
13483
13484 @item bind_opt=SWITCHES
13485 [default: @code{""}]
13486 creates a variable which can be referred to subsequently by using
13487 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13488 switches given to @command{gnatbind}.
13489
13490 @item link_opt=SWITCHES
13491 [default: @code{""}]
13492 creates a variable which can be referred to subsequently by using
13493 the @samp{$@{link_opt@}} notation. This is intended to store the default
13494 switches given to @command{gnatlink}.
13495
13496 @item main=EXECUTABLE
13497 [default: @code{""}]
13498 specifies the name of the executable for the application. This variable can
13499 be referred to in the following lines by using the @samp{$@{main@}} notation.
13500
13501 @ifset vms
13502 @item comp_cmd=COMMAND
13503 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
13504 @end ifset
13505 @ifclear vms
13506 @item comp_cmd=COMMAND
13507 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
13508 @end ifclear
13509 specifies the command used to compile a single file in the application.
13510
13511 @ifset vms
13512 @item make_cmd=COMMAND
13513 [default: @code{"GNAT MAKE $@{main@}
13514 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
13515 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
13516 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
13517 @end ifset
13518 @ifclear vms
13519 @item make_cmd=COMMAND
13520 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
13521 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
13522 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
13523 @end ifclear
13524 specifies the command used to recompile the whole application.
13525
13526 @item run_cmd=COMMAND
13527 [default: @code{"$@{main@}"}]
13528 specifies the command used to run the application.
13529
13530 @item debug_cmd=COMMAND
13531 [default: @code{"gdb $@{main@}"}]
13532 specifies the command used to debug the application
13533
13534 @end table
13535
13536 @noindent
13537 @command{gnatxref} and @command{gnatfind} only take into account the
13538 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
13539
13540 @node Regular Expressions in gnatfind and gnatxref
13541 @section  Regular Expressions in @code{gnatfind} and @code{gnatxref}
13542
13543 @noindent
13544 As specified in the section about @command{gnatfind}, the pattern can be a
13545 regular expression. Actually, there are to set of regular expressions
13546 which are recognized by the program:
13547
13548 @table @code
13549 @item globbing patterns
13550 These are the most usual regular expression. They are the same that you
13551 generally used in a Unix shell command line, or in a DOS session.
13552
13553 Here is a more formal grammar:
13554 @smallexample
13555 @group
13556 @iftex
13557 @leftskip=.5cm
13558 @end iftex
13559 regexp ::= term
13560 term   ::= elmt            -- matches elmt
13561 term   ::= elmt elmt       -- concatenation (elmt then elmt)
13562 term   ::= *               -- any string of 0 or more characters
13563 term   ::= ?               -- matches any character
13564 term   ::= [char @{char@}]   -- matches any character listed
13565 term   ::= [char - char]   -- matches any character in range
13566 @end group
13567 @end smallexample
13568
13569 @item full regular expression
13570 The second set of regular expressions is much more powerful. This is the
13571 type of regular expressions recognized by utilities such a @file{grep}.
13572
13573 The following is the form of a regular expression, expressed in Ada
13574 reference manual style BNF is as follows
13575
13576 @smallexample
13577 @iftex
13578 @leftskip=.5cm
13579 @end iftex
13580 @group
13581 regexp ::= term @{| term@}   -- alternation (term or term @dots{})
13582
13583 term ::= item @{item@}       -- concatenation (item then item)
13584
13585 item ::= elmt              -- match elmt
13586 item ::= elmt *            -- zero or more elmt's
13587 item ::= elmt +            -- one or more elmt's
13588 item ::= elmt ?            -- matches elmt or nothing
13589 @end group
13590 @group
13591 elmt ::= nschar            -- matches given character
13592 elmt ::= [nschar @{nschar@}]   -- matches any character listed
13593 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
13594 elmt ::= [char - char]     -- matches chars in given range
13595 elmt ::= \ char            -- matches given character
13596 elmt ::= .                 -- matches any single character
13597 elmt ::= ( regexp )        -- parens used for grouping
13598
13599 char ::= any character, including special characters
13600 nschar ::= any character except ()[].*+?^^^
13601 @end group
13602 @end smallexample
13603
13604 Following are a few examples:
13605
13606 @table @samp
13607 @item abcde|fghi
13608 will match any of the two strings @samp{abcde} and @samp{fghi},
13609
13610 @item abc*d
13611 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
13612 @samp{abcccd}, and so on,
13613
13614 @item [a-z]+
13615 will match any string which has only lowercase characters in it (and at
13616 least one character.
13617
13618 @end table
13619 @end table
13620
13621 @node Examples of gnatxref Usage
13622 @section Examples of @code{gnatxref} Usage
13623
13624 @subsection General Usage
13625
13626 @noindent
13627 For the following examples, we will consider the following units:
13628
13629 @smallexample @c ada
13630 @group
13631 @cartouche
13632 main.ads:
13633 1: with Bar;
13634 2: package Main is
13635 3:     procedure Foo (B : in Integer);
13636 4:     C : Integer;
13637 5: private
13638 6:     D : Integer;
13639 7: end Main;
13640
13641 main.adb:
13642 1: package body Main is
13643 2:     procedure Foo (B : in Integer) is
13644 3:     begin
13645 4:        C := B;
13646 5:        D := B;
13647 6:        Bar.Print (B);
13648 7:        Bar.Print (C);
13649 8:     end Foo;
13650 9: end Main;
13651
13652 bar.ads:
13653 1: package Bar is
13654 2:     procedure Print (B : Integer);
13655 3: end bar;
13656 @end cartouche
13657 @end group
13658 @end smallexample
13659
13660 @table @code
13661
13662 @noindent
13663 The first thing to do is to recompile your application (for instance, in
13664 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13665 the cross-referencing information.
13666 You can then issue any of the following commands:
13667
13668 @item gnatxref main.adb
13669 @code{gnatxref} generates cross-reference information for main.adb
13670 and every unit 'with'ed by main.adb.
13671
13672 The output would be:
13673 @smallexample
13674 @iftex
13675 @leftskip=0cm
13676 @end iftex
13677 B                                                      Type: Integer
13678   Decl: bar.ads           2:22
13679 B                                                      Type: Integer
13680   Decl: main.ads          3:20
13681   Body: main.adb          2:20
13682   Ref:  main.adb          4:13     5:13     6:19
13683 Bar                                                    Type: Unit
13684   Decl: bar.ads           1:9
13685   Ref:  main.adb          6:8      7:8
13686        main.ads           1:6
13687 C                                                      Type: Integer
13688   Decl: main.ads          4:5
13689   Modi: main.adb          4:8
13690   Ref:  main.adb          7:19
13691 D                                                      Type: Integer
13692   Decl: main.ads          6:5
13693   Modi: main.adb          5:8
13694 Foo                                                    Type: Unit
13695   Decl: main.ads          3:15
13696   Body: main.adb          2:15
13697 Main                                                    Type: Unit
13698   Decl: main.ads          2:9
13699   Body: main.adb          1:14
13700 Print                                                   Type: Unit
13701   Decl: bar.ads           2:15
13702   Ref:  main.adb          6:12     7:12
13703 @end smallexample
13704
13705 @noindent
13706 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13707 its body is in main.adb, line 1, column 14 and is not referenced any where.
13708
13709 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13710 is referenced in main.adb, line 6 column 12 and line 7 column 12.
13711
13712 @item gnatxref package1.adb package2.ads
13713 @code{gnatxref} will generates cross-reference information for
13714 package1.adb, package2.ads and any other package 'with'ed by any
13715 of these.
13716
13717 @end table
13718
13719 @ifclear vms
13720 @subsection Using gnatxref with vi
13721
13722 @code{gnatxref} can generate a tags file output, which can be used
13723 directly from @command{vi}. Note that the standard version of @command{vi}
13724 will not work properly with overloaded symbols. Consider using another
13725 free implementation of @command{vi}, such as @command{vim}.
13726
13727 @smallexample
13728 $ gnatxref -v gnatfind.adb > tags
13729 @end smallexample
13730
13731 @noindent
13732 will generate the tags file for @code{gnatfind} itself (if the sources
13733 are in the search path!).
13734
13735 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
13736 (replacing @var{entity} by whatever you are looking for), and vi will
13737 display a new file with the corresponding declaration of entity.
13738 @end ifclear
13739
13740 @node Examples of gnatfind Usage
13741 @section Examples of @code{gnatfind} Usage
13742
13743 @table @code
13744
13745 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
13746 Find declarations for all entities xyz referenced at least once in
13747 main.adb. The references are search in every library file in the search
13748 path.
13749
13750 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
13751 switch is set)
13752
13753 The output will look like:
13754 @smallexample
13755 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13756 ^directory/^[directory]^main.adb:24:10: xyz <= body
13757 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13758 @end smallexample
13759
13760 @noindent
13761 that is to say, one of the entities xyz found in main.adb is declared at
13762 line 12 of main.ads (and its body is in main.adb), and another one is
13763 declared at line 45 of foo.ads
13764
13765 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
13766 This is the same command as the previous one, instead @code{gnatfind} will
13767 display the content of the Ada source file lines.
13768
13769 The output will look like:
13770
13771 @smallexample
13772 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13773    procedure xyz;
13774 ^directory/^[directory]^main.adb:24:10: xyz <= body
13775    procedure xyz is
13776 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13777    xyz : Integer;
13778 @end smallexample
13779
13780 @noindent
13781 This can make it easier to find exactly the location your are looking
13782 for.
13783
13784 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
13785 Find references to all entities containing an x that are
13786 referenced on line 123 of main.ads.
13787 The references will be searched only in main.ads and foo.adb.
13788
13789 @item gnatfind main.ads:123
13790 Find declarations and bodies for all entities that are referenced on
13791 line 123 of main.ads.
13792
13793 This is the same as @code{gnatfind "*":main.adb:123}.
13794
13795 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
13796 Find the declaration for the entity referenced at column 45 in
13797 line 123 of file main.adb in directory mydir. Note that it
13798 is usual to omit the identifier name when the column is given,
13799 since the column position identifies a unique reference.
13800
13801 The column has to be the beginning of the identifier, and should not
13802 point to any character in the middle of the identifier.
13803
13804 @end table
13805
13806 @c *********************************
13807 @node The GNAT Pretty-Printer gnatpp
13808 @chapter The GNAT Pretty-Printer @command{gnatpp}
13809 @findex gnatpp
13810 @cindex Pretty-Printer
13811
13812 @menu
13813 * Switches for gnatpp::
13814 * Formatting Rules::
13815 @end menu
13816
13817 @noindent
13818 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
13819 for source reformatting / pretty-printing.
13820 It takes an Ada source file as input and generates a reformatted
13821 version as output.
13822 You can specify various style directives via switches; e.g.,
13823 identifier case conventions, rules of indentation, and comment layout.
13824
13825 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
13826 tree for the input source and thus requires the input to be syntactically and
13827 semantically legal.
13828 If this condition is not met, @command{gnatpp} will terminate with an
13829 error message; no output file will be generated.
13830
13831 @command{gnatpp} cannot process sources that contain
13832 preprocessing directives.
13833
13834 If the compilation unit
13835 contained in the input source depends semantically upon units located
13836 outside the current directory, you have to provide the source search path
13837 when invoking @command{gnatpp}, if these units are contained in files with
13838 names that do not follow the GNAT file naming rules, you have to provide
13839 the configuration file describing the corresponding naming scheme;
13840 see the description of the @command{gnatpp}
13841 switches below. Another possibility is to use a project file and to
13842 call @command{gnatpp} through the @command{gnat} driver
13843 (see @ref{The GNAT Driver and Project Files}).
13844
13845 The @command{gnatpp} command has the form
13846
13847 @smallexample
13848 @c $ gnatpp @ovar{switches} @var{filename}
13849 @c Expanding @ovar macro inline (explanation in macro def comments)
13850 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
13851 @end smallexample
13852
13853 @noindent
13854 where
13855 @itemize @bullet
13856 @item
13857 @var{switches} is an optional sequence of switches defining such properties as
13858 the formatting rules, the source search path, and the destination for the
13859 output source file
13860
13861 @item
13862 @var{filename} is the name (including the extension) of the source file to
13863 reformat; ``wildcards'' or several file names on the same gnatpp command are
13864 allowed.  The file name may contain path information; it does not have to
13865 follow the GNAT file naming rules
13866
13867 @item
13868 @samp{@var{gcc_switches}} is a list of switches for
13869 @command{gcc}. They will be passed on to all compiler invocations made by
13870 @command{gnatelim} to generate the ASIS trees. Here you can provide
13871 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13872 use the @option{-gnatec} switch to set the configuration file,
13873 use the @option{-gnat05} switch if sources should be compiled in
13874 Ada 2005 mode  etc.
13875 @end itemize
13876
13877 @node Switches for gnatpp
13878 @section Switches for @command{gnatpp}
13879
13880 @noindent
13881 The following subsections describe the various switches accepted by
13882 @command{gnatpp}, organized by category.
13883
13884 @ifclear vms
13885 You specify a switch by supplying a name and generally also a value.
13886 In many cases the values for a switch with a given name are incompatible with
13887 each other
13888 (for example the switch that controls the casing of a reserved word may have
13889 exactly one value: upper case, lower case, or
13890 mixed case) and thus exactly one such switch can be in effect for an
13891 invocation of @command{gnatpp}.
13892 If more than one is supplied, the last one is used.
13893 However, some values for the same switch are mutually compatible.
13894 You may supply several such switches to @command{gnatpp}, but then
13895 each must be specified in full, with both the name and the value.
13896 Abbreviated forms (the name appearing once, followed by each value) are
13897 not permitted.
13898 For example, to set
13899 the alignment of the assignment delimiter both in declarations and in
13900 assignment statements, you must write @option{-A2A3}
13901 (or @option{-A2 -A3}), but not @option{-A23}.
13902 @end ifclear
13903
13904 @ifset vms
13905 In many cases the set of options for a given qualifier are incompatible with
13906 each other (for example the qualifier that controls the casing of a reserved
13907 word may have exactly one option, which specifies either upper case, lower
13908 case, or mixed case), and thus exactly one such option can be in effect for
13909 an invocation of @command{gnatpp}.
13910 If more than one is supplied, the last one is used.
13911 However, some qualifiers have options that are mutually compatible,
13912 and then you may then supply several such options when invoking
13913 @command{gnatpp}.
13914 @end ifset
13915
13916 In most cases, it is obvious whether or not the
13917 ^values for a switch with a given name^options for a given qualifier^
13918 are compatible with each other.
13919 When the semantics might not be evident, the summaries below explicitly
13920 indicate the effect.
13921
13922 @menu
13923 * Alignment Control::
13924 * Casing Control::
13925 * Construct Layout Control::
13926 * General Text Layout Control::
13927 * Other Formatting Options::
13928 * Setting the Source Search Path::
13929 * Output File Control::
13930 * Other gnatpp Switches::
13931 @end menu
13932
13933 @node Alignment Control
13934 @subsection Alignment Control
13935 @cindex Alignment control in @command{gnatpp}
13936
13937 @noindent
13938 Programs can be easier to read if certain constructs are vertically aligned.
13939 By default all alignments are set ON.
13940 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
13941 OFF, and then use one or more of the other
13942 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
13943 to activate alignment for specific constructs.
13944
13945 @table @option
13946 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
13947
13948 @ifset vms
13949 @item /ALIGN=ON
13950 Set all alignments to ON
13951 @end ifset
13952
13953 @item ^-A0^/ALIGN=OFF^
13954 Set all alignments to OFF
13955
13956 @item ^-A1^/ALIGN=COLONS^
13957 Align @code{:} in declarations
13958
13959 @item ^-A2^/ALIGN=DECLARATIONS^
13960 Align @code{:=} in initializations in declarations
13961
13962 @item ^-A3^/ALIGN=STATEMENTS^
13963 Align @code{:=} in assignment statements
13964
13965 @item ^-A4^/ALIGN=ARROWS^
13966 Align @code{=>} in associations
13967
13968 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
13969 Align @code{at} keywords in the component clauses in record
13970 representation clauses
13971 @end table
13972
13973 @noindent
13974 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
13975 is allowed.
13976
13977 @node Casing Control
13978 @subsection Casing Control
13979 @cindex Casing control in @command{gnatpp}
13980
13981 @noindent
13982 @command{gnatpp} allows you to specify the casing for reserved words,
13983 pragma names, attribute designators and identifiers.
13984 For identifiers you may define a
13985 general rule for name casing but also override this rule
13986 via a set of dictionary files.
13987
13988 Three types of casing are supported: lower case, upper case, and mixed case.
13989 Lower and upper case are self-explanatory (but since some letters in
13990 Latin1 and other GNAT-supported character sets
13991 exist only in lower-case form, an upper case conversion will have no
13992 effect on them.)
13993 ``Mixed case'' means that the first letter, and also each letter immediately
13994 following an underscore, are converted to their uppercase forms;
13995 all the other letters are converted to their lowercase forms.
13996
13997 @table @option
13998 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
13999 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14000 Attribute designators are lower case
14001
14002 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14003 Attribute designators are upper case
14004
14005 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14006 Attribute designators are mixed case (this is the default)
14007
14008 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14009 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14010 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14011 lower case (this is the default)
14012
14013 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14014 Keywords are upper case
14015
14016 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14017 @item ^-nD^/NAME_CASING=AS_DECLARED^
14018 Name casing for defining occurrences are as they appear in the source file
14019 (this is the default)
14020
14021 @item ^-nU^/NAME_CASING=UPPER_CASE^
14022 Names are in upper case
14023
14024 @item ^-nL^/NAME_CASING=LOWER_CASE^
14025 Names are in lower case
14026
14027 @item ^-nM^/NAME_CASING=MIXED_CASE^
14028 Names are in mixed case
14029
14030 @cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
14031 @item ^-neD^/ENUM_CASING=AS_DECLARED^
14032 Enumeration literal casing for defining occurrences are as they appear in the
14033 source file. Overrides ^-n^/NAME_CASING^ casing setting.
14034
14035 @item ^-neU^/ENUM_CASING=UPPER_CASE^
14036 Enumeration literals are in upper case.  Overrides ^-n^/NAME_CASING^ casing
14037 setting.
14038
14039 @item ^-neL^/ENUM_CASING=LOWER_CASE^
14040 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
14041 setting.
14042
14043 @item ^-neM^/ENUM_CASING=MIXED_CASE^
14044 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
14045 setting.
14046
14047 @cindex @option{^-nt@var{x}^/TYPE_CASING^} (@command{gnatpp})
14048 @item ^-neD^/TYPE_CASING=AS_DECLARED^
14049 Names introduced by type and subtype declarations are always
14050 cased as they appear in the declaration in the source file.
14051 Overrides ^-n^/NAME_CASING^ casing setting.
14052
14053 @item ^-ntU^/TYPE_CASING=UPPER_CASE^
14054 Names introduced by type and subtype declarations are always in
14055 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
14056
14057 @item ^-ntL^/TYPE_CASING=LOWER_CASE^
14058 Names introduced by type and subtype declarations are always in
14059 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
14060
14061 @item ^-ntM^/TYPE_CASING=MIXED_CASE^
14062 Names introduced by type and subtype declarations are always in
14063 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
14064
14065 @item ^-nnU^/NUMBER_CASING=UPPER_CASE^
14066 Names introduced by number declarations are always in
14067 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
14068
14069 @item ^-nnL^/NUMBER_CASING=LOWER_CASE^
14070 Names introduced by number declarations are always in
14071 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
14072
14073 @item ^-nnM^/NUMBER_CASING=MIXED_CASE^
14074 Names introduced by number declarations are always in
14075 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
14076
14077 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14078 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14079 Pragma names are lower case
14080
14081 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14082 Pragma names are upper case
14083
14084 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14085 Pragma names are mixed case (this is the default)
14086
14087 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14088 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14089 Use @var{file} as a @emph{dictionary file} that defines
14090 the casing for a set of specified names,
14091 thereby overriding the effect on these names by
14092 any explicit or implicit
14093 ^-n^/NAME_CASING^ switch.
14094 To supply more than one dictionary file,
14095 use ^several @option{-D} switches^a list of files as options^.
14096
14097 @noindent
14098 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14099 to define the casing for the Ada predefined names and
14100 the names declared in the GNAT libraries.
14101
14102 @item ^-D-^/SPECIFIC_CASING^
14103 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14104 Do not use the default dictionary file;
14105 instead, use the casing
14106 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14107 dictionary file(s)
14108 @end table
14109
14110 @noindent
14111 The structure of a dictionary file, and details on the conventions
14112 used in the default dictionary file, are defined in @ref{Name Casing}.
14113
14114 The @option{^-D-^/SPECIFIC_CASING^} and
14115 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14116 compatible.
14117
14118 @node Construct Layout Control
14119 @subsection Construct Layout Control
14120 @cindex Layout control in @command{gnatpp}
14121
14122 @noindent
14123 This group of @command{gnatpp} switches controls the layout of comments and
14124 complex syntactic constructs.  See @ref{Formatting Comments} for details
14125 on their effect.
14126
14127 @table @option
14128 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14129 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14130 All the comments remain unchanged
14131
14132 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14133 GNAT-style comment line indentation (this is the default).
14134
14135 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
14136 Reference-manual comment line indentation.
14137
14138 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14139 GNAT-style comment beginning
14140
14141 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14142 Reformat comment blocks
14143
14144 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
14145 Keep unchanged special form comments
14146
14147 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14148 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14149 GNAT-style layout (this is the default)
14150
14151 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14152 Compact layout
14153
14154 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14155 Uncompact layout
14156
14157 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
14158 @item ^-N^/NOTABS^
14159 All the VT characters are removed from the comment text. All the HT characters
14160 are expanded with the sequences of space characters to get to the next tab
14161 stops.
14162
14163 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
14164 @item ^--no-separate-is^/NO_SEPARATE_IS^
14165 Do not place the keyword @code{is} on a separate line in a subprogram body in
14166 case if the spec occupies more than one line.
14167
14168 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
14169 @item ^--separate-label^/SEPARATE_LABEL^
14170 Place statement label(s) on a separate line, with the following statement
14171 on the next line.
14172
14173 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
14174 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
14175 Place the keyword @code{loop} in FOR and WHILE loop statements and the
14176 keyword @code{then} in IF statements on a separate line.
14177
14178 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
14179 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
14180 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
14181 keyword @code{then} in IF statements on a separate line. This option is
14182 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
14183
14184 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
14185 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
14186 Start each USE clause in a context clause from a separate line.
14187
14188 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
14189 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
14190 Use a separate line for a loop or block statement name, but do not use an extra
14191 indentation level for the statement itself.
14192
14193 @end table
14194
14195 @ifclear vms
14196 @noindent
14197 The @option{-c1} and @option{-c2} switches are incompatible.
14198 The @option{-c3} and @option{-c4} switches are compatible with each other and
14199 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
14200 the other comment formatting switches.
14201
14202 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14203 @end ifclear
14204
14205 @ifset vms
14206 @noindent
14207 For the @option{/COMMENTS_LAYOUT} qualifier:
14208 @itemize @bullet
14209 @item
14210 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14211 @item
14212 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14213 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14214 @end itemize
14215
14216 @noindent
14217 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14218 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14219 @end ifset
14220
14221 @node General Text Layout Control
14222 @subsection General Text Layout Control
14223
14224 @noindent
14225 These switches allow control over line length and indentation.
14226
14227 @table @option
14228 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
14229 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14230 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
14231
14232 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
14233 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14234 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
14235
14236 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
14237 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14238 Indentation level for continuation lines (relative to the line being
14239 continued), @var{nnn} from 1@dots{}9.
14240 The default
14241 value is one less than the (normal) indentation level, unless the
14242 indentation is set to 1 (in which case the default value for continuation
14243 line indentation is also 1)
14244 @end table
14245
14246 @node Other Formatting Options
14247 @subsection Other Formatting Options
14248
14249 @noindent
14250 These switches control the inclusion of missing end/exit labels, and
14251 the indentation level in @b{case} statements.
14252
14253 @table @option
14254 @item ^-e^/NO_MISSED_LABELS^
14255 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14256 Do not insert missing end/exit labels. An end label is the name of
14257 a construct that may optionally be repeated at the end of the
14258 construct's declaration;
14259 e.g., the names of packages, subprograms, and tasks.
14260 An exit label is the name of a loop that may appear as target
14261 of an exit statement within the loop.
14262 By default, @command{gnatpp} inserts these end/exit labels when
14263 they are absent from the original source. This option suppresses such
14264 insertion, so that the formatted source reflects the original.
14265
14266 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14267 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14268 Insert a Form Feed character after a pragma Page.
14269
14270 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
14271 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14272 Do not use an additional indentation level for @b{case} alternatives
14273 and variants if there are @var{nnn} or more (the default
14274 value is 10).
14275 If @var{nnn} is 0, an additional indentation level is
14276 used for @b{case} alternatives and variants regardless of their number.
14277
14278 @item ^--call_threshold=@var{nnn}^/MAX_ACT=@var{nnn}^
14279 @cindex @option{^--call_threshold^/MAX_ACT^} (@command{gnatpp})
14280 If the number of parameter associations is greater than @var{nnn} and if at
14281 least one association uses named notation, start each association from
14282 a new line. If @var{nnn} is 0, no check for the number of associations
14283 is made, this is the default.
14284
14285 @item ^--par_threshold=@var{nnn}^/MAX_PAR=@var{nnn}^
14286 @cindex @option{^--par_threshold^/MAX_PAR^} (@command{gnatpp})
14287 If the number of parameter specifications is greater than @var{nnn}
14288 (or equal to @var{nnn} in case of a function), start each specification from
14289 a new line. The default for @var{nnn} is 3.
14290 @end table
14291
14292 @node Setting the Source Search Path
14293 @subsection Setting the Source Search Path
14294
14295 @noindent
14296 To define the search path for the input source file, @command{gnatpp}
14297 uses the same switches as the GNAT compiler, with the same effects.
14298
14299 @table @option
14300 @item ^-I^/SEARCH=^@var{dir}
14301 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
14302 The same as the corresponding gcc switch
14303
14304 @item ^-I-^/NOCURRENT_DIRECTORY^
14305 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
14306 The same as the corresponding gcc switch
14307
14308 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14309 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
14310 The same as the corresponding gcc switch
14311
14312 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14313 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
14314 The same as the corresponding gcc switch
14315
14316 @end table
14317
14318 @node Output File Control
14319 @subsection Output File Control
14320
14321 @noindent
14322 By default the output is sent to the file whose name is obtained by appending
14323 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
14324 (if the file with this name already exists, it is unconditionally overwritten).
14325 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14326 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14327 as output file.
14328 The output may be redirected by the following switches:
14329
14330 @table @option
14331 @item ^-pipe^/STANDARD_OUTPUT^
14332 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
14333 Send the output to @code{Standard_Output}
14334
14335 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14336 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14337 Write the output into @var{output_file}.
14338 If @var{output_file} already exists, @command{gnatpp} terminates without
14339 reading or processing the input file.
14340
14341 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14342 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
14343 Write the output into @var{output_file}, overwriting the existing file
14344 (if one is present).
14345
14346 @item ^-r^/REPLACE^
14347 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
14348 Replace the input source file with the reformatted output, and copy the
14349 original input source into the file whose name is obtained by appending the
14350 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14351 If a file with this name already exists, @command{gnatpp} terminates without
14352 reading or processing the input file.
14353
14354 @item ^-rf^/OVERRIDING_REPLACE^
14355 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14356 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14357 already exists, it is overwritten.
14358
14359 @item ^-rnb^/REPLACE_NO_BACKUP^
14360 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
14361 Replace the input source file with the reformatted output without
14362 creating any backup copy of the input source.
14363
14364 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
14365 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
14366 Specifies the format of the reformatted output file. The @var{xxx}
14367 ^string specified with the switch^option^ may be either
14368 @itemize @bullet
14369 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
14370 @item ``@option{^crlf^CRLF^}''
14371 the same as @option{^crlf^CRLF^}
14372 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
14373 @item ``@option{^lf^LF^}''
14374 the same as @option{^unix^UNIX^}
14375 @end itemize
14376
14377 @item ^-W^/RESULT_ENCODING=^@var{e}
14378 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
14379 Specify the wide character encoding method used to write the code in the
14380 result file
14381 @var{e} is one of the following:
14382
14383 @itemize @bullet
14384
14385 @item ^h^HEX^
14386 Hex encoding
14387
14388 @item ^u^UPPER^
14389 Upper half encoding
14390
14391 @item ^s^SHIFT_JIS^
14392 Shift/JIS encoding
14393
14394 @item ^e^EUC^
14395 EUC encoding
14396
14397 @item ^8^UTF8^
14398 UTF-8 encoding
14399
14400 @item ^b^BRACKETS^
14401 Brackets encoding (default value)
14402 @end itemize
14403
14404 @end table
14405
14406 @noindent
14407 Options @option{^-pipe^/STANDARD_OUTPUT^},
14408 @option{^-o^/OUTPUT^} and
14409 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14410 contains only one file to reformat.
14411 Option
14412 @option{^--eol^/END_OF_LINE^}
14413 and
14414 @option{^-W^/RESULT_ENCODING^}
14415 cannot be used together
14416 with @option{^-pipe^/STANDARD_OUTPUT^} option.
14417
14418 @node Other gnatpp Switches
14419 @subsection Other @code{gnatpp} Switches
14420
14421 @noindent
14422 The additional @command{gnatpp} switches are defined in this subsection.
14423
14424 @table @option
14425 @item --version
14426 @cindex @option{--version} @command{gnatpp}
14427 Display Copyright and version, then exit disregarding all other options.
14428
14429 @item --help
14430 @cindex @option{--help} @command{gnatpp}
14431 Display usage, then exit disregarding all other options.
14432
14433 @item ^-files @var{filename}^/FILES=@var{filename}^
14434 @cindex @option{^-files^/FILES^} (@code{gnatpp})
14435 Take the argument source files from the specified file. This file should be an
14436 ordinary text file containing file names separated by spaces or
14437 line breaks. You can use this switch more than once in the same call to
14438 @command{gnatpp}. You also can combine this switch with an explicit list of
14439 files.
14440
14441 @item ^-v^/VERBOSE^
14442 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
14443 Verbose mode;
14444 @command{gnatpp} generates version information and then
14445 a trace of the actions it takes to produce or obtain the ASIS tree.
14446
14447 @item ^-w^/WARNINGS^
14448 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
14449 Warning mode;
14450 @command{gnatpp} generates a warning whenever it cannot provide
14451 a required layout in the result source.
14452 @end table
14453
14454 @node Formatting Rules
14455 @section Formatting Rules
14456
14457 @noindent
14458 The following subsections show how @command{gnatpp} treats ``white space'',
14459 comments, program layout, and name casing.
14460 They provide the detailed descriptions of the switches shown above.
14461
14462 @menu
14463 * White Space and Empty Lines::
14464 * Formatting Comments::
14465 * Construct Layout::
14466 * Name Casing::
14467 @end menu
14468
14469 @node White Space and Empty Lines
14470 @subsection White Space and Empty Lines
14471
14472 @noindent
14473 @command{gnatpp} does not have an option to control space characters.
14474 It will add or remove spaces according to the style illustrated by the
14475 examples in the @cite{Ada Reference Manual}.
14476
14477 The only format effectors
14478 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
14479 that will appear in the output file are platform-specific line breaks,
14480 and also format effectors within (but not at the end of) comments.
14481 In particular, each horizontal tab character that is not inside
14482 a comment will be treated as a space and thus will appear in the
14483 output file as zero or more spaces depending on
14484 the reformatting of the line in which it appears.
14485 The only exception is a Form Feed character, which is inserted after a
14486 pragma @code{Page} when @option{-ff} is set.
14487
14488 The output file will contain no lines with trailing ``white space'' (spaces,
14489 format effectors).
14490
14491 Empty lines in the original source are preserved
14492 only if they separate declarations or statements.
14493 In such contexts, a
14494 sequence of two or more empty lines is replaced by exactly one empty line.
14495 Note that a blank line will be removed if it separates two ``comment blocks''
14496 (a comment block is a sequence of whole-line comments).
14497 In order to preserve a visual separation between comment blocks, use an
14498 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
14499 Likewise, if for some reason you wish to have a sequence of empty lines,
14500 use a sequence of empty comments instead.
14501
14502 @node Formatting Comments
14503 @subsection Formatting Comments
14504
14505 @noindent
14506 Comments in Ada code are of two kinds:
14507 @itemize @bullet
14508 @item
14509 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14510 ``white space'') on a line
14511
14512 @item
14513 an @emph{end-of-line comment}, which follows some other Ada lexical element
14514 on the same line.
14515 @end itemize
14516
14517 @noindent
14518 The indentation of a whole-line comment is that of either
14519 the preceding or following line in
14520 the formatted source, depending on switch settings as will be described below.
14521
14522 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
14523 between the end of the preceding Ada lexical element and the beginning
14524 of the comment as appear in the original source,
14525 unless either the comment has to be split to
14526 satisfy the line length limitation, or else the next line contains a
14527 whole line comment that is considered a continuation of this end-of-line
14528 comment (because it starts at the same position).
14529 In the latter two
14530 cases, the start of the end-of-line comment is moved right to the nearest
14531 multiple of the indentation level.
14532 This may result in a ``line overflow'' (the right-shifted comment extending
14533 beyond the maximum line length), in which case the comment is split as
14534 described below.
14535
14536 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
14537 (GNAT-style comment line indentation)
14538 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
14539 (reference-manual comment line indentation).
14540 With reference-manual style, a whole-line comment is indented as if it
14541 were a declaration or statement at the same place
14542 (i.e., according to the indentation of the preceding line(s)).
14543 With GNAT style, a whole-line comment that is immediately followed by an
14544 @b{if} or @b{case} statement alternative, a record variant, or the reserved
14545 word @b{begin}, is indented based on the construct that follows it.
14546
14547 For example:
14548 @smallexample @c ada
14549 @cartouche
14550 if A then
14551     null;
14552        -- some comment
14553 else
14554    null;
14555 end if;
14556 @end cartouche
14557 @end smallexample
14558
14559 @noindent
14560 Reference-manual indentation produces:
14561
14562 @smallexample @c ada
14563 @cartouche
14564 if A then
14565    null;
14566    --  some comment
14567 else
14568    null;
14569 end if;
14570 @end cartouche
14571 @end smallexample
14572
14573 @noindent
14574 while GNAT-style indentation produces:
14575
14576 @smallexample @c ada
14577 @cartouche
14578 if A then
14579    null;
14580 --  some comment
14581 else
14582    null;
14583 end if;
14584 @end cartouche
14585 @end smallexample
14586
14587 @noindent
14588 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
14589 (GNAT style comment beginning) has the following
14590 effect:
14591
14592 @itemize @bullet
14593 @item
14594 For each whole-line comment that does not end with two hyphens,
14595 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
14596 to ensure that there are at least two spaces between these hyphens and the
14597 first non-blank character of the comment.
14598 @end itemize
14599
14600 @noindent
14601 For an end-of-line comment, if in the original source the next line is a
14602 whole-line comment that starts at the same position
14603 as the end-of-line comment,
14604 then the whole-line comment (and all whole-line comments
14605 that follow it and that start at the same position)
14606 will start at this position in the output file.
14607
14608 @noindent
14609 That is, if in the original source we have:
14610
14611 @smallexample @c ada
14612 @cartouche
14613 begin
14614 A := B + C;            --  B must be in the range Low1..High1
14615                        --  C must be in the range Low2..High2
14616              --B+C will be in the range Low1+Low2..High1+High2
14617 X := X + 1;
14618 @end cartouche
14619 @end smallexample
14620
14621 @noindent
14622 Then in the formatted source we get
14623
14624 @smallexample @c ada
14625 @cartouche
14626 begin
14627    A := B + C;            --  B must be in the range Low1..High1
14628                           --  C must be in the range Low2..High2
14629    --  B+C will be in the range Low1+Low2..High1+High2
14630    X := X + 1;
14631 @end cartouche
14632 @end smallexample
14633
14634 @noindent
14635 A comment that exceeds the line length limit will be split.
14636 Unless switch
14637 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
14638 the line belongs to a reformattable block, splitting the line generates a
14639 @command{gnatpp} warning.
14640 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
14641 comments may be reformatted in typical
14642 word processor style (that is, moving words between lines and putting as
14643 many words in a line as possible).
14644
14645 @noindent
14646 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
14647 that has a special format (that is, a character that is neither a letter nor digit
14648 not white space nor line break immediately following the leading @code{--} of
14649 the comment) should be without any change moved from the argument source
14650 into reformatted source. This switch allows to preserve comments that are used
14651 as a special marks in the code (e.g.@: SPARK annotation).
14652
14653 @node Construct Layout
14654 @subsection Construct Layout
14655
14656 @noindent
14657 In several cases the suggested layout in the Ada Reference Manual includes
14658 an extra level of indentation that many programmers prefer to avoid. The
14659 affected cases include:
14660
14661 @itemize @bullet
14662
14663 @item Record type declaration (RM 3.8)
14664
14665 @item Record representation clause (RM 13.5.1)
14666
14667 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
14668
14669 @item Block statement in case if a block has a statement identifier (RM 5.6)
14670 @end itemize
14671
14672 @noindent
14673 In compact mode (when GNAT style layout or compact layout is set),
14674 the pretty printer uses one level of indentation instead
14675 of two. This is achieved in the record definition and record representation
14676 clause cases by putting the @code{record} keyword on the same line as the
14677 start of the declaration or representation clause, and in the block and loop
14678 case by putting the block or loop header on the same line as the statement
14679 identifier.
14680
14681 @noindent
14682 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
14683 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
14684 layout on the one hand, and uncompact layout
14685 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
14686 can be illustrated by the following examples:
14687
14688 @iftex
14689 @cartouche
14690 @multitable @columnfractions .5 .5
14691 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
14692
14693 @item
14694 @smallexample @c ada
14695 type q is record
14696    a : integer;
14697    b : integer;
14698 end record;
14699 @end smallexample
14700 @tab
14701 @smallexample @c ada
14702 type q is
14703    record
14704       a : integer;
14705       b : integer;
14706    end record;
14707 @end smallexample
14708
14709 @item
14710 @smallexample @c ada
14711 for q use record
14712    a at 0 range  0 .. 31;
14713    b at 4 range  0 .. 31;
14714 end record;
14715 @end smallexample
14716 @tab
14717 @smallexample @c ada
14718 for q use
14719    record
14720       a at 0 range  0 .. 31;
14721       b at 4 range  0 .. 31;
14722    end record;
14723 @end smallexample
14724
14725 @item
14726 @smallexample @c ada
14727 Block : declare
14728    A : Integer := 3;
14729 begin
14730    Proc (A, A);
14731 end Block;
14732 @end smallexample
14733 @tab
14734 @smallexample @c ada
14735 Block :
14736    declare
14737       A : Integer := 3;
14738    begin
14739       Proc (A, A);
14740    end Block;
14741 @end smallexample
14742
14743 @item
14744 @smallexample @c ada
14745 Clear : for J in 1 .. 10 loop
14746    A (J) := 0;
14747 end loop Clear;
14748 @end smallexample
14749 @tab
14750 @smallexample @c ada
14751 Clear :
14752    for J in 1 .. 10 loop
14753       A (J) := 0;
14754    end loop Clear;
14755 @end smallexample
14756 @end multitable
14757 @end cartouche
14758 @end iftex
14759
14760 @ifnottex
14761 @smallexample
14762 @cartouche
14763 GNAT style, compact layout              Uncompact layout
14764
14765 type q is record                        type q is
14766    a : integer;                            record
14767    b : integer;                               a : integer;
14768 end record;                                   b : integer;
14769                                            end record;
14770
14771 for q use record                        for q use
14772    a at 0 range  0 .. 31;                  record
14773    b at 4 range  0 .. 31;                     a at 0 range  0 .. 31;
14774 end record;                                   b at 4 range  0 .. 31;
14775                                            end record;
14776
14777 Block : declare                         Block :
14778    A : Integer := 3;                       declare
14779 begin                                         A : Integer := 3;
14780    Proc (A, A);                            begin
14781 end Block;                                    Proc (A, A);
14782                                            end Block;
14783
14784 Clear : for J in 1 .. 10 loop           Clear :
14785    A (J) := 0;                             for J in 1 .. 10 loop
14786 end loop Clear;                               A (J) := 0;
14787                                            end loop Clear;
14788 @end cartouche
14789 @end smallexample
14790 @end ifnottex
14791
14792 @noindent
14793 A further difference between GNAT style layout and compact layout is that
14794 GNAT style layout inserts empty lines as separation for
14795 compound statements, return statements and bodies.
14796
14797 Note that the layout specified by
14798 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
14799 for named block and loop statements overrides the layout defined by these
14800 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
14801 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
14802 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
14803
14804 @node Name Casing
14805 @subsection Name Casing
14806
14807 @noindent
14808 @command{gnatpp} always converts the usage occurrence of a (simple) name to
14809 the same casing as the corresponding defining identifier.
14810
14811 You control the casing for defining occurrences via the
14812 @option{^-n^/NAME_CASING^} switch.
14813 @ifclear vms
14814 With @option{-nD} (``as declared'', which is the default),
14815 @end ifclear
14816 @ifset vms
14817 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
14818 @end ifset
14819 defining occurrences appear exactly as in the source file
14820 where they are declared.
14821 The other ^values for this switch^options for this qualifier^ ---
14822 @option{^-nU^UPPER_CASE^},
14823 @option{^-nL^LOWER_CASE^},
14824 @option{^-nM^MIXED_CASE^} ---
14825 result in
14826 ^upper, lower, or mixed case, respectively^the corresponding casing^.
14827 If @command{gnatpp} changes the casing of a defining
14828 occurrence, it analogously changes the casing of all the
14829 usage occurrences of this name.
14830
14831 If the defining occurrence of a name is not in the source compilation unit
14832 currently being processed by @command{gnatpp}, the casing of each reference to
14833 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
14834 switch (subject to the dictionary file mechanism described below).
14835 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
14836 had affected the
14837 casing for the defining occurrence of the name.
14838
14839 Some names may need to be spelled with casing conventions that are not
14840 covered by the upper-, lower-, and mixed-case transformations.
14841 You can arrange correct casing by placing such names in a
14842 @emph{dictionary file},
14843 and then supplying a @option{^-D^/DICTIONARY^} switch.
14844 The casing of names from dictionary files overrides
14845 any @option{^-n^/NAME_CASING^} switch.
14846
14847 To handle the casing of Ada predefined names and the names from GNAT libraries,
14848 @command{gnatpp} assumes a default dictionary file.
14849 The name of each predefined entity is spelled with the same casing as is used
14850 for the entity in the @cite{Ada Reference Manual}.
14851 The name of each entity in the GNAT libraries is spelled with the same casing
14852 as is used in the declaration of that entity.
14853
14854 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
14855 default dictionary file.
14856 Instead, the casing for predefined and GNAT-defined names will be established
14857 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
14858 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
14859 will appear as just shown,
14860 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
14861 To ensure that even such names are rendered in uppercase,
14862 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
14863 (or else, less conveniently, place these names in upper case in a dictionary
14864 file).
14865
14866 A dictionary file is
14867 a plain text file; each line in this file can be either a blank line
14868 (containing only space characters and ASCII.HT characters), an Ada comment
14869 line, or the specification of exactly one @emph{casing schema}.
14870
14871 A casing schema is a string that has the following syntax:
14872
14873 @smallexample
14874 @cartouche
14875   @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
14876
14877   @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
14878 @end cartouche
14879 @end smallexample
14880
14881 @noindent
14882 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
14883 @var{identifier} lexical element and the @var{letter_or_digit} category.)
14884
14885 The casing schema string can be followed by white space and/or an Ada-style
14886 comment; any amount of white space is allowed before the string.
14887
14888 If a dictionary file is passed as
14889 @ifclear vms
14890 the value of a @option{-D@var{file}} switch
14891 @end ifclear
14892 @ifset vms
14893 an option to the @option{/DICTIONARY} qualifier
14894 @end ifset
14895 then for every
14896 simple name and every identifier, @command{gnatpp} checks if the dictionary
14897 defines the casing for the name or for some of its parts (the term ``subword''
14898 is used below to denote the part of a name which is delimited by ``_'' or by
14899 the beginning or end of the word and which does not contain any ``_'' inside):
14900
14901 @itemize @bullet
14902 @item
14903 if the whole name is in the dictionary, @command{gnatpp} uses for this name
14904 the casing defined by the dictionary; no subwords are checked for this word
14905
14906 @item
14907 for every subword @command{gnatpp} checks if the dictionary contains the
14908 corresponding string of the form @code{*@var{simple_identifier}*},
14909 and if it does, the casing of this @var{simple_identifier} is used
14910 for this subword
14911
14912 @item
14913 if the whole name does not contain any ``_'' inside, and if for this name
14914 the dictionary contains two entries - one of the form @var{identifier},
14915 and another - of the form *@var{simple_identifier}*, then the first one
14916 is applied to define the casing of this name
14917
14918 @item
14919 if more than one dictionary file is passed as @command{gnatpp} switches, each
14920 dictionary adds new casing exceptions and overrides all the existing casing
14921 exceptions set by the previous dictionaries
14922
14923 @item
14924 when @command{gnatpp} checks if the word or subword is in the dictionary,
14925 this check is not case sensitive
14926 @end itemize
14927
14928 @noindent
14929 For example, suppose we have the following source to reformat:
14930
14931 @smallexample @c ada
14932 @cartouche
14933 procedure test is
14934    name1 : integer := 1;
14935    name4_name3_name2 : integer := 2;
14936    name2_name3_name4 : Boolean;
14937    name1_var : Float;
14938 begin
14939    name2_name3_name4 := name4_name3_name2 > name1;
14940 end;
14941 @end cartouche
14942 @end smallexample
14943
14944 @noindent
14945 And suppose we have two dictionaries:
14946
14947 @smallexample
14948 @cartouche
14949 @i{dict1:}
14950    NAME1
14951    *NaMe3*
14952    *Name1*
14953 @end cartouche
14954
14955 @cartouche
14956 @i{dict2:}
14957   *NAME3*
14958 @end cartouche
14959 @end smallexample
14960
14961 @noindent
14962 If @command{gnatpp} is called with the following switches:
14963
14964 @smallexample
14965 @ifclear vms
14966 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
14967 @end ifclear
14968 @ifset vms
14969 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
14970 @end ifset
14971 @end smallexample
14972
14973 @noindent
14974 then we will get the following name casing in the @command{gnatpp} output:
14975
14976 @smallexample @c ada
14977 @cartouche
14978 procedure Test is
14979    NAME1             : Integer := 1;
14980    Name4_NAME3_Name2 : Integer := 2;
14981    Name2_NAME3_Name4 : Boolean;
14982    Name1_Var         : Float;
14983 begin
14984    Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
14985 end Test;
14986 @end cartouche
14987 @end smallexample
14988
14989 @ifclear vms
14990 @c *********************************
14991 @node The Ada-to-XML converter gnat2xml
14992 @chapter The Ada-to-XML converter @command{gnat2xml}
14993 @findex gnat2xml
14994 @cindex XML generation
14995
14996 @noindent
14997 The @command{gnat2xml} tool is an ASIS-based utility that converts
14998 Ada source code into XML.
14999
15000 @menu
15001 * Switches for gnat2xml::
15002 * Driving gnat2xml with gnatmake or gprbuild::
15003 * Other Programs::
15004 * Structure of the XML::
15005 @end menu
15006
15007 @node Switches for gnat2xml
15008 @section Switches for @command{gnat2xml}
15009
15010 @noindent
15011 @command{gnat2xml} takes Ada source code as input, and produces XML
15012 that conforms to the schema.
15013
15014 Usage:
15015
15016 @smallexample
15017 gnat2xml [options] files
15018 @end smallexample
15019
15020 ``files'' are the Ada source file names.
15021
15022 @noindent
15023 Options:
15024 @smallexample
15025 -h
15026 --help -- generate usage information and quit, ignoring all other options
15027
15028 -mdir -- generate one .xml file for each Ada source file, in directory
15029          @file{dir}. (Default is to generate the XML to standard output.)
15030
15031 -q -- debugging version, with interspersed source, and a more
15032       compact representation of "sloc". This version does not conform
15033       to any schema.
15034
15035 -I <include-dir>
15036     directories to search for dependencies
15037     You can also set the ADA_INCLUDE_PATH environment variable for this.
15038
15039 -v -- verbose (print out the command line options, and the names of
15040       output files as they are generated).
15041
15042 -t -- do not delete tree files when done (they are deleted by default).
15043
15044 -cargs ... -- options to pass to gcc
15045 @end smallexample
15046
15047 @noindent
15048 You can generate the ``tree files'' ahead of time using the -gnatct switch:
15049
15050 @smallexample
15051 gnatmake -gnat2012 -gnatct *.ad[sb]
15052 @end smallexample
15053
15054 @noindent
15055 If tree files do not exist, @command{gnat2xml} will create them by running gcc.
15056 See the ASIS documentation for more information on tree files.
15057
15058 Example:
15059
15060 @smallexample
15061 mkdir xml-files
15062 gnat2xml -v -mxml-files *.ad[sb] -cargs -gnat2012
15063 @end smallexample
15064
15065 @noindent
15066 The above will create *.xml files in the @file{xml-files} subdirectory.
15067 For example, if there is an Ada package Mumble.Dumble, whose spec and
15068 body source code lives in mumble-dumble.ads and mumble-dumble.adb,
15069 the above will produce xml-files/mumble-dumble.ads.xml and
15070 xml-files/mumble-dumble.adb.xml.
15071
15072 @node Driving gnat2xml with gnatmake or gprbuild
15073 @section Driving @command{gnat2xml} with @command{gnatmake} or @command{gprbuild}
15074
15075 @noindent
15076 You can use gnatmake or gprbuild to drive @command{gnat2xml} to get
15077 incremental updates of the XML files on a per-source-file basis. For
15078 example, if you already have a bunch of XML files, and then you change
15079 one source file, it will regenerate XML files only for that source
15080 file, and other source files that depend on it. Gnatmake and gprbuild
15081 take care of tracking inter-file dependencies. For example, if
15082 this.adb says @code{with That;}, then this.adb depends on that.ads.
15083
15084 To do this, you tell gnatmake/gprbuild to pretend that
15085 @command{gnat2xml} is the Ada compiler (instead of using gcc as the
15086 Ada compiler, as is normal).
15087
15088 To tell gnatmake to use @command{gnat2xml} instead of gcc as the
15089 ``compiler'', for example:
15090
15091 @smallexample
15092 gnatmake -gnatc *.adb --GCC="gnat2xml -t -mxml"
15093 @end smallexample
15094
15095 @noindent
15096 The @option{--GCC=} switch tells gnatmake that the ``compiler'' to run
15097 is @command{gnat2xml -t -mxml}. The @option{-t} switch means to keep the tree
15098 files, so they can be reused on the next run. (@command{gnat2xml}
15099 deletes them by default.) As usual, @option{-mxml} means to put the
15100 XML files in the @file{xml} subdirectory.
15101
15102 You must give the @option{-gnatc} switch to gnatmake, which means
15103 ``compile only; do not generate object code''. Otherwise, gnatmake will
15104 complain about missing object (*.o) files; @command{gnat2xml} of
15105 course does not generate *.o files.
15106
15107 Using gprbuild is similar: you tell it to use @command{gnat2xml}
15108 instead of gcc. First write a project file, such as my_project.gpr:
15109
15110 @smallexample @c projectfile
15111 project My_Project is
15112
15113    package Compiler is
15114       for Driver ("ada") use "gnat2xml";
15115       --  Use gnat2xml instead of the usual gcc.
15116
15117       for Default_Switches ("ada") use ("-t", "-mxml");
15118       --  Same switches as in the gnatmake case.
15119    end Compiler;
15120
15121 end My_Project;
15122 @end smallexample
15123
15124 @noindent
15125 Then:
15126
15127 @smallexample @c projectfile
15128 gprbuild --no-object-check -P my_project.gpr
15129 @end smallexample
15130
15131 @noindent
15132 The @option{--no-object-check} switch serves the same purpose as
15133 @option{-gnatc} in the gnatmake case --- it tells gprbuild not to
15134 expect that the ``compiler'' (really @command{gnat2xml}) will produce
15135 *.o files.
15136
15137 See the gprbuild documentation for information on many other things
15138 you can put in the project file, such as telling it where to find
15139 the source files.
15140
15141 @node Other Programs
15142 @section Other Programs
15143
15144 @noindent
15145 The distribution includes two other programs that are related to
15146 @command{gnat2xml}:
15147
15148 @command{gnat2xsd} is the schema generator, which generates the schema
15149 to standard output, based on the structure of Ada as encoded by
15150 ASIS. You don't need to run @command{gnat2xsd} in order to use
15151 @command{gnat2xml}. To generate the schema, type:
15152
15153 @smallexample
15154 gnat2xsd > ada-schema.xsd
15155 @end smallexample
15156
15157 @noindent
15158 @command{gnat2xml} generates XML files that will validate against
15159 @file{ada-schema.xsd}.
15160
15161 @command{xml2gnat} is a back-translator that translates the XML back
15162 into Ada source code. The Ada generated by @command{xml2gnat} has
15163 identical semantics to the original Ada code passed to
15164 @command{gnat2xml}. It is not textually identical, however --- for
15165 example, no attempt is made to preserve the original indentation.
15166
15167 @node Structure of the XML
15168 @section Structure of the XML
15169
15170 @noindent
15171 The primary documentation for the structure of the XML generated by
15172 @command{gnat2xml} is the schema (see @command{gnat2xsd} above). The
15173 following documentation gives additional details needed to understand
15174 the schema and therefore the XML.
15175
15176 The elements listed under Defining Occurrences, Usage Occurrences, and
15177 Other Elements represent the syntactic structure of the Ada program.
15178 Element names are given in lower case, with the corresponding element
15179 type Capitalized_Like_This. The element and element type names are
15180 derived directly from the ASIS enumeration type Flat_Element_Kinds,
15181 declared in Asis.Extensions.Flat_Kinds, with the leading ``An_'' or ``A_''
15182 removed. For example, the ASIS enumeration literal
15183 An_Assignment_Statement corresponds to the XML element
15184 assignment_statement of XML type Assignment_Statement.
15185
15186 To understand the details of the schema and the corresponding XML, it is
15187 necessary to understand the ASIS standard, as well as the GNAT-specific
15188 extension to ASIS.
15189
15190 A defining occurrence is an identifier (or character literal or operator
15191 symbol) declared by a declaration. A usage occurrence is an identifier
15192 (or ...) that references such a declared entity. For example, in:
15193
15194 @smallexample
15195 type T is range 1..10;
15196 X, Y : constant T := 1;
15197 @end smallexample
15198
15199 @noindent
15200 The first ``T'' is the defining occurrence of a type. The ``X'' is the
15201 defining occurrence of a constant, as is the ``Y'', and the second ``T'' is
15202 a usage occurrence referring to the defining occurrence of T.
15203
15204 Each element has a 'sloc' (source location), and subelements for each
15205 syntactic subtree, reflecting the Ada grammar as implemented by ASIS.
15206 The types of subelements are as defined in the ASIS standard. For
15207 example, for the right-hand side of an assignment_statement we have
15208 the following comment in asis-statements.ads:
15209
15210 @smallexample
15211 ------------------------------------------------------------------------------
15212 --  18.3  function Assignment_Expression
15213 ------------------------------------------------------------------------------
15214
15215    function Assignment_Expression
15216      (Statement : Asis.Statement)
15217       return      Asis.Expression;
15218
15219 ------------------------------------------------------------------------------
15220 ...
15221 --  Returns the expression from the right hand side of the assignment.
15222 ...
15223 --  Returns Element_Kinds:
15224 --       An_Expression
15225 @end smallexample
15226
15227 @noindent
15228 The corresponding sub-element of type Assignment_Statement is:
15229
15230 @smallexample
15231 <xsd:element name="assignment_expression_q" type="Expression_Class"/>
15232 @end smallexample
15233
15234 @noindent
15235 where Expression_Class is defined by an xsd:choice of all the
15236 various kinds of expression.
15237
15238 The 'sloc' of each element indicates the starting and ending line and
15239 column numbers. Column numbers are character counts; that is, a tab
15240 counts as 1, not as however many spaces it might expand to.
15241
15242 Subelements of type Element have names ending in ``_q'' (for ASIS
15243 ``Query''), and those of type Element_List end in ``_ql'' (``Query returning
15244 List'').
15245
15246 Some subelements are ``Boolean''. For example, Private_Type_Definition
15247 has has_abstract_q and has_limited_q, to indicate whether those
15248 keywords are present, as in @code{type T is abstract limited
15249 private;}. False is represented by a Nil_Element. True is represented
15250 by an element type specific to that query (for example, Abstract and
15251 Limited).
15252
15253 The root of the tree is a Compilation_Unit, with attributes:
15254
15255 @itemize @bullet
15256 @item
15257 unit_kind, unit_class, and unit_origin. These are strings that match the
15258 enumeration literals of types Unit_Kinds, Unit_Classes, and Unit_Origins
15259 in package Asis.
15260
15261 @item
15262 unit_full_name is the full expanded name of the unit, starting from a
15263 root library unit. So for @code{package P.Q.R is ...},
15264 @code{unit_full_name="P.Q.R"}. Same for @code{separate (P.Q) package R is ...}.
15265
15266 @item
15267 def_name is the same as unit_full_name for library units; for subunits,
15268 it is just the simple name.
15269
15270 @item
15271 source_file is the name of the Ada source file. For example, for
15272 the spec of @code{P.Q.R}, @code{source_file="p-q-r.ads"}. This allows one to
15273 interpret the source locations --- the ``sloc'' of all elements
15274 within this Compilation_Unit refers to line and column numbers
15275 within the named file.
15276 @end itemize
15277
15278 @noindent
15279 Defining occurrences have these attributes:
15280
15281 @itemize @bullet
15282 @item
15283 def_name is the simple name of the declared entity, as written in the Ada
15284 source code.
15285
15286 @item
15287 def is a unique URI of the form:
15288
15289  ada://kind/fully/qualified/name
15290
15291 where:
15292
15293  kind indicates the kind of Ada entity being declared (see below), and
15294
15295  fully/qualified/name, is the fully qualified name of the Ada
15296  entity, with each of ``fully'', ``qualified'', and ``name'' being
15297  mangled for uniqueness. We do not document the mangling
15298  algorithm, which is subject to change; we just guarantee that the
15299  names are unique in the face of overloading.
15300
15301 @item
15302 type is the type of the declared object, or @code{null} for
15303 declarations of things other than objects.
15304 @end itemize
15305
15306 @noindent
15307 Usage occurrences have these attributes:
15308
15309 @itemize @bullet
15310 @item
15311 ref_name is the same as the def_name of the corresponding defining
15312 occurrence. This attribute is not of much use, because of
15313 overloading; use ref for lookups, instead.
15314
15315 @item
15316 ref is the same as the def of the corresponding defining
15317 occurrence.
15318 @end itemize
15319
15320 @noindent
15321 In summary, @code{def_name} and @code{ref_name} are as in the source
15322 code of the declaration, possibly overloaded, whereas @code{def} and
15323 @code{ref} are unique-ified.
15324
15325 Literal elements have this attribute:
15326
15327 @itemize @bullet
15328 @item
15329 lit_val is the value of the literal as written in the source text,
15330 appropriately escaped (e.g. @code{"} ---> @code{&quot;}). This applies
15331 only to numeric and string literals. Enumeration literals in Ada are
15332 not really "literals" in the usual sense; they are usage occurrences,
15333 and have ref_name and ref as described above. Note also that string
15334 literals used as operator symbols are treated as defining or usage
15335 occurrences, not as literals.
15336 @end itemize
15337
15338 @noindent
15339 Elements that can syntactically represent names and expressions (which
15340 includes usage occurrences, plus function calls and so forth) have this
15341 attribute:
15342
15343 @itemize @bullet
15344 @item
15345 type. If the element represents an expression or the name of an object,
15346 'type' is the 'def' for the defining occurrence of the type of that
15347 expression or name. Names of other kinds of entities, such as package
15348 names and type names, do not have a type in Ada; these have type="null"
15349 in the XML.
15350 @end itemize
15351
15352 @noindent
15353 Pragma elements have this attribute:
15354
15355 @itemize @bullet
15356 @item
15357 pragma_name is the name of the pragma. For language-defined pragmas, the
15358 pragma name is redundant with the element kind (for example, an
15359 assert_pragma element necessarily has pragma_name="Assert"). However, all
15360 implementation-defined pragmas are lumped together in ASIS as a single
15361 element kind (for example, the GNAT-specific pragma Unreferenced is
15362 represented by an implementation_defined_pragma element with
15363 pragma_name="Unreferenced").
15364 @end itemize
15365
15366 @noindent
15367 Defining occurrences of formal parameters and generic formal objects have this
15368 attribute:
15369
15370 @itemize @bullet
15371 @item
15372 mode indicates that the parameter is of mode 'in', 'in out', or 'out'.
15373 @end itemize
15374
15375 @noindent
15376 The "kind" part of the "def" and "ref" attributes is taken from the ASIS
15377 enumeration type Flat_Declaration_Kinds, declared in
15378 Asis.Extensions.Flat_Kinds, with the leading "An_" or "A_" removed, and
15379 any trailing "_Declaration" or "_Specification" removed. Thus, the
15380 possible kinds are as follows:
15381
15382 @smallexample
15383 ordinary_type
15384 task_type
15385 protected_type
15386 incomplete_type
15387 tagged_incomplete_type
15388 private_type
15389 private_extension
15390 subtype
15391 variable
15392 constant
15393 deferred_constant
15394 single_task
15395 single_protected
15396 integer_number
15397 real_number
15398 enumeration_literal
15399 discriminant
15400 component
15401 loop_parameter
15402 generalized_iterator
15403 element_iterator
15404 procedure
15405 function
15406 parameter
15407 procedure_body
15408 function_body
15409 return_variable
15410 return_constant
15411 null_procedure
15412 expression_function
15413 package
15414 package_body
15415 object_renaming
15416 exception_renaming
15417 package_renaming
15418 procedure_renaming
15419 function_renaming
15420 generic_package_renaming
15421 generic_procedure_renaming
15422 generic_function_renaming
15423 task_body
15424 protected_body
15425 entry
15426 entry_body
15427 entry_index
15428 procedure_body_stub
15429 function_body_stub
15430 package_body_stub
15431 task_body_stub
15432 protected_body_stub
15433 exception
15434 choice_parameter
15435 generic_procedure
15436 generic_function
15437 generic_package
15438 package_instantiation
15439 procedure_instantiation
15440 function_instantiation
15441 formal_object
15442 formal_type
15443 formal_incomplete_type
15444 formal_procedure
15445 formal_function
15446 formal_package
15447 formal_package_declaration_with_box
15448 @end smallexample
15449 @end ifclear
15450
15451 @c *********************************
15452 @node The GNAT Metrics Tool gnatmetric
15453 @chapter The GNAT Metrics Tool @command{gnatmetric}
15454 @findex gnatmetric
15455 @cindex Metric tool
15456
15457 @noindent
15458 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
15459 for computing various program metrics.
15460 It takes an Ada source file as input and generates a file containing the
15461 metrics data as output. Various switches control which
15462 metrics are computed and output.
15463
15464 @menu
15465 * Switches for gnatmetric::
15466 @end menu
15467
15468 @command{gnatmetric} generates and uses the ASIS
15469 tree for the input source and thus requires the input to be syntactically and
15470 semantically legal.
15471 If this condition is not met, @command{gnatmetric} will generate
15472 an error message; no metric information for this file will be
15473 computed and reported.
15474
15475 If the compilation unit contained in the input source depends semantically
15476 upon units in files located outside the current directory, you have to provide
15477 the source search path when invoking @command{gnatmetric}.
15478 If it depends semantically upon units that are contained
15479 in files with names that do not follow the GNAT file naming rules, you have to
15480 provide the configuration file describing the corresponding naming scheme (see
15481 the description of the @command{gnatmetric} switches below.)
15482 Alternatively, you may use a project file and invoke @command{gnatmetric}
15483 through the @command{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15484
15485 The @command{gnatmetric} command has the form
15486
15487 @smallexample
15488 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15489 @c Expanding @ovar macro inline (explanation in macro def comments)
15490 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15491 @end smallexample
15492
15493 @noindent
15494 where
15495 @itemize @bullet
15496 @item
15497 @var{switches} specify the metrics to compute and define the destination for
15498 the output
15499
15500 @item
15501 Each @var{filename} is the name (including the extension) of a source
15502 file to process. ``Wildcards'' are allowed, and
15503 the file name may contain path information.
15504 If no @var{filename} is supplied, then the @var{switches} list must contain
15505 at least one
15506 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15507 Including both a @option{-files} switch and one or more
15508 @var{filename} arguments is permitted.
15509
15510 @item
15511 @samp{@var{gcc_switches}} is a list of switches for
15512 @command{gcc}. They will be passed on to all compiler invocations made by
15513 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15514 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
15515 and use the @option{-gnatec} switch to set the configuration file,
15516 use the @option{-gnat05} switch if sources should be compiled in
15517 Ada 2005 mode etc.
15518 @end itemize
15519
15520 @node Switches for gnatmetric
15521 @section Switches for @command{gnatmetric}
15522
15523 @noindent
15524 The following subsections describe the various switches accepted by
15525 @command{gnatmetric}, organized by category.
15526
15527 @menu
15528 * Output Files Control::
15529 * Disable Metrics For Local Units::
15530 * Specifying a set of metrics to compute::
15531 * Other gnatmetric Switches::
15532 * Generate project-wide metrics::
15533 @end menu
15534
15535 @node Output Files Control
15536 @subsection Output File Control
15537 @cindex Output file control in @command{gnatmetric}
15538
15539 @noindent
15540 @command{gnatmetric} has two output formats. It can generate a
15541 textual (human-readable) form, and also XML. By default only textual
15542 output is generated.
15543
15544 When generating the output in textual form, @command{gnatmetric} creates
15545 for each Ada source file a corresponding text file
15546 containing the computed metrics, except for the case when the set of metrics
15547 specified by gnatmetric parameters consists only of metrics that are computed
15548 for the whole set of analyzed sources, but not for each Ada source.
15549 By default, this file is placed in the same directory as where the source
15550 file is located, and its name is obtained
15551 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
15552 input file.
15553
15554 All the output information generated in XML format is placed in a single
15555 file. By default this file is placed in the current directory and has the
15556 name ^@file{metrix.xml}^@file{METRIX$XML}^.
15557
15558 Some of the computed metrics are summed over the units passed to
15559 @command{gnatmetric}; for example, the total number of lines of code.
15560 By default this information is sent to @file{stdout}, but a file
15561 can be specified with the @option{-og} switch.
15562
15563 The following switches control the @command{gnatmetric} output:
15564
15565 @table @option
15566 @cindex @option{^-x^/XML^} (@command{gnatmetric})
15567 @item ^-x^/XML^
15568 Generate the XML output
15569
15570 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
15571 @item ^-xs^/XSD^
15572 Generate the XML output and the XML schema file that describes the structure
15573 of the XML metric report, this schema is assigned to the XML file. The schema
15574 file has the same name as the XML output file with @file{.xml} suffix replaced
15575 with @file{.xsd}
15576
15577 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
15578 @item ^-nt^/NO_TEXT^
15579 Do not generate the output in text form (implies @option{^-x^/XML^})
15580
15581 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
15582 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
15583 Put text files with detailed metrics into @var{output_dir}
15584
15585 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
15586 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
15587 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
15588 in the name of the output file.
15589
15590 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
15591 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
15592 Put global metrics into @var{file_name}
15593
15594 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
15595 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
15596 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
15597
15598 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
15599 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
15600 Use ``short'' source file names in the output.  (The @command{gnatmetric}
15601 output includes the name(s) of the Ada source file(s) from which the metrics
15602 are computed.  By default each name includes the absolute path. The
15603 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
15604 to exclude all directory information from the file names that are output.)
15605
15606 @end table
15607
15608 @node Disable Metrics For Local Units
15609 @subsection Disable Metrics For Local Units
15610 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15611
15612 @noindent
15613 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15614 one compilation
15615 unit per one source file. It computes line metrics for the whole source
15616 file, and it also computes syntax
15617 and complexity metrics for the file's outermost unit.
15618
15619 By default, @command{gnatmetric} will also compute all metrics for certain
15620 kinds of locally declared program units:
15621
15622 @itemize @bullet
15623 @item
15624 subprogram (and generic subprogram) bodies;
15625
15626 @item
15627 package (and generic package) specs and bodies;
15628
15629 @item
15630 task object and type specifications and bodies;
15631
15632 @item
15633 protected object and type specifications and bodies.
15634 @end itemize
15635
15636 @noindent
15637 These kinds of entities will be referred to as
15638 @emph{eligible local program units}, or simply @emph{eligible local units},
15639 @cindex Eligible local unit (for @command{gnatmetric})
15640 in the discussion below.
15641
15642 Note that a subprogram declaration, generic instantiation,
15643 or renaming declaration only receives metrics
15644 computation when it appear as the outermost entity
15645 in a source file.
15646
15647 Suppression of metrics computation for eligible local units can be
15648 obtained via the following switch:
15649
15650 @table @option
15651 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
15652 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
15653 Do not compute detailed metrics for eligible local program units
15654
15655 @end table
15656
15657 @node Specifying a set of metrics to compute
15658 @subsection Specifying a set of metrics to compute
15659
15660 @noindent
15661 By default all the metrics are computed and reported. The switches
15662 described in this subsection allow you to control, on an individual
15663 basis, whether metrics are computed and
15664 reported. If at least one positive metric
15665 switch is specified (that is, a switch that defines that a given
15666 metric or set of metrics is to be computed), then only
15667 explicitly specified metrics are reported.
15668
15669 @menu
15670 * Line Metrics Control::
15671 * Syntax Metrics Control::
15672 * Complexity Metrics Control::
15673 * Coupling Metrics Control::
15674 @end menu
15675
15676 @node Line Metrics Control
15677 @subsubsection Line Metrics Control
15678 @cindex Line metrics control in @command{gnatmetric}
15679
15680 @noindent
15681 For any (legal) source file, and for each of its
15682 eligible local program units, @command{gnatmetric} computes the following
15683 metrics:
15684
15685 @itemize @bullet
15686 @item
15687 the total number of lines;
15688
15689 @item
15690 the total number of code lines (i.e., non-blank lines that are not comments)
15691
15692 @item
15693 the number of comment lines
15694
15695 @item
15696 the number of code lines containing end-of-line comments;
15697
15698 @item
15699 the comment percentage: the ratio between the number of lines that contain
15700 comments and the number of all non-blank lines, expressed as a percentage;
15701
15702 @item
15703 the number of empty lines and lines containing only space characters and/or
15704 format effectors (blank lines)
15705
15706 @item
15707 the average number of code lines in subprogram bodies, task bodies, entry
15708 bodies and statement sequences in package bodies (this metric is only computed
15709 across the whole set of the analyzed units)
15710
15711 @end itemize
15712
15713 @noindent
15714 @command{gnatmetric} sums the values of the line metrics for all the
15715 files being processed and then generates the cumulative results. The tool
15716 also computes for all the files being processed the average number of code
15717 lines in bodies.
15718
15719 You can use the following switches to select the specific line metrics
15720 to be computed and reported.
15721
15722 @table @option
15723 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
15724
15725 @ifclear vms
15726 @cindex @option{--no-lines@var{x}}
15727 @end ifclear
15728
15729 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
15730 Report all the line metrics
15731
15732 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
15733 Do not report any of line metrics
15734
15735 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
15736 Report the number of all lines
15737
15738 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
15739 Do not report the number of all lines
15740
15741 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
15742 Report the number of code lines
15743
15744 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
15745 Do not report the number of code lines
15746
15747 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
15748 Report the number of comment lines
15749
15750 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
15751 Do not report the number of comment lines
15752
15753 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
15754 Report the number of code lines containing
15755 end-of-line comments
15756
15757 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
15758 Do not report the number of code lines containing
15759 end-of-line comments
15760
15761 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
15762 Report the comment percentage in the program text
15763
15764 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
15765 Do not report the comment percentage in the program text
15766
15767 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
15768 Report the number of blank lines
15769
15770 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
15771 Do not report the number of blank lines
15772
15773 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
15774 Report the average number of code lines in subprogram bodies, task bodies,
15775 entry bodies and statement sequences in package bodies. The metric is computed
15776 and reported for the whole set of processed Ada sources only.
15777
15778 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
15779 Do not report the average number of code lines in subprogram bodies,
15780 task bodies, entry bodies and statement sequences in package bodies.
15781
15782 @end table
15783
15784 @node Syntax Metrics Control
15785 @subsubsection Syntax Metrics Control
15786 @cindex Syntax metrics control in @command{gnatmetric}
15787
15788 @noindent
15789 @command{gnatmetric} computes various syntactic metrics for the
15790 outermost unit and for each eligible local unit:
15791
15792 @table @emph
15793 @item LSLOC (``Logical Source Lines Of Code'')
15794 The total number of declarations and the total number of statements. Note
15795 that the definition of declarations is the one given in the reference
15796 manual:
15797
15798 @noindent
15799 ``Each of the following is defined to be a declaration: any basic_declaration;
15800 an enumeration_literal_specification; a discriminant_specification;
15801 a component_declaration; a loop_parameter_specification; a
15802 parameter_specification; a subprogram_body; an entry_declaration;
15803 an entry_index_specification; a choice_parameter_specification;
15804 a generic_formal_parameter_declaration.''
15805
15806 This means for example that each enumeration literal adds one to the count,
15807 as well as each subprogram parameter.
15808
15809 Thus the results from this metric will be significantly greater than might
15810 be expected from a naive view of counting semicolons.
15811
15812 @item Maximal static nesting level of inner program units
15813 According to
15814 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
15815 package, a task unit, a protected unit, a
15816 protected entry, a generic unit, or an explicitly declared subprogram other
15817 than an enumeration literal.''
15818
15819 @item Maximal nesting level of composite syntactic constructs
15820 This corresponds to the notion of the
15821 maximum nesting level in the GNAT built-in style checks
15822 (@pxref{Style Checking})
15823 @end table
15824
15825 @noindent
15826 For the outermost unit in the file, @command{gnatmetric} additionally computes
15827 the following metrics:
15828
15829 @table @emph
15830 @item Public subprograms
15831 This metric is computed for package specs. It is the
15832 number of subprograms and generic subprograms declared in the visible
15833 part (including the visible part of nested packages, protected objects, and
15834 protected types).
15835
15836 @item All subprograms
15837 This metric is computed for bodies and subunits. The
15838 metric is equal to a total number of subprogram bodies in the compilation
15839 unit.
15840 Neither generic instantiations nor renamings-as-a-body nor body stubs
15841 are counted. Any subprogram body is counted, independently of its nesting
15842 level and enclosing constructs. Generic bodies and bodies of protected
15843 subprograms are counted in the same way as ``usual'' subprogram bodies.
15844
15845 @item Public types
15846 This metric is computed for package specs and
15847 generic package declarations. It is the total number of types
15848 that can be referenced from outside this compilation unit, plus the
15849 number of types from all the visible parts of all the visible generic
15850 packages. Generic formal types are not counted.  Only types, not subtypes,
15851 are included.
15852
15853 @noindent
15854 Along with the total number of public types, the following
15855 types are counted and reported separately:
15856
15857 @itemize @bullet
15858 @item
15859 Abstract types
15860
15861 @item
15862 Root tagged types (abstract, non-abstract, private, non-private). Type
15863 extensions are @emph{not} counted
15864
15865 @item
15866 Private types (including private extensions)
15867
15868 @item
15869 Task types
15870
15871 @item
15872 Protected types
15873
15874 @end itemize
15875
15876 @item All types
15877 This metric is computed for any compilation unit. It is equal to the total
15878 number of the declarations of different types given in the compilation unit.
15879 The private and the corresponding full type declaration are counted as one
15880 type declaration. Incomplete type declarations and generic formal types
15881 are not counted.
15882 No distinction is made among different kinds of types (abstract,
15883 private etc.); the total number of types is computed and reported.
15884
15885 @end table
15886
15887 @noindent
15888 By default, all the syntax metrics are computed and reported. You can use the
15889 following switches to select specific syntax metrics.
15890
15891 @table @option
15892
15893 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
15894
15895 @ifclear vms
15896 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
15897 @end ifclear
15898
15899 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
15900 Report all the syntax metrics
15901
15902 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
15903 Do not report any of syntax metrics
15904
15905 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
15906 Report the total number of declarations
15907
15908 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
15909 Do not report the total number of declarations
15910
15911 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
15912 Report the total number of statements
15913
15914 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
15915 Do not report the total number of statements
15916
15917 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
15918 Report the number of public subprograms in a compilation unit
15919
15920 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
15921 Do not report the number of public subprograms in a compilation unit
15922
15923 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
15924 Report the number of all the subprograms in a compilation unit
15925
15926 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
15927 Do not report the number of all the subprograms in a compilation unit
15928
15929 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
15930 Report the number of public types in a compilation unit
15931
15932 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
15933 Do not report the number of public types in a compilation unit
15934
15935 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
15936 Report the number of all the types in a compilation unit
15937
15938 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
15939 Do not report the number of all the types in a compilation unit
15940
15941 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
15942 Report the maximal program unit nesting level
15943
15944 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
15945 Do not report the maximal program unit nesting level
15946
15947 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
15948 Report the maximal construct nesting level
15949
15950 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
15951 Do not report the maximal construct nesting level
15952
15953 @end table
15954
15955 @node Complexity Metrics Control
15956 @subsubsection Complexity Metrics Control
15957 @cindex Complexity metrics control in @command{gnatmetric}
15958
15959 @noindent
15960 For a program unit that is an executable body (a subprogram body (including
15961 generic bodies), task body, entry body or a package body containing
15962 its own statement sequence) @command{gnatmetric} computes the following
15963 complexity metrics:
15964
15965 @itemize @bullet
15966 @item
15967 McCabe cyclomatic complexity;
15968
15969 @item
15970 McCabe essential complexity;
15971
15972 @item
15973 maximal loop nesting level;
15974
15975 @item
15976 extra exit points (for subprograms);
15977 @end itemize
15978
15979 @noindent
15980 The McCabe cyclomatic complexity metric is defined
15981 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
15982
15983 According to McCabe, both control statements and short-circuit control forms
15984 should be taken into account when computing cyclomatic complexity.
15985 For Ada 2012 we have also take into account conditional expressions
15986 and quantified expressions. For each body, we compute three metric values:
15987
15988 @itemize @bullet
15989 @item
15990 the complexity introduced by control
15991 statements only, without taking into account short-circuit forms,
15992
15993 @item
15994 the complexity introduced by short-circuit control forms only, and
15995
15996 @item
15997 the total
15998 cyclomatic complexity, which is the sum of these two values.
15999 @end itemize
16000
16001 @noindent
16002
16003 The cyclomatic complexity is also computed for Ada 2012 expression functions.
16004 An expression function cannot have statements as its components, so only one
16005 metric value is computed as a cyclomatic complexity of an expression function.
16006
16007 The origin of cyclomatic complexity metric is the need to estimate the number
16008 of independent paths in the control flow graph that in turn gives the number
16009 of tests needed to satisfy paths coverage testing completeness criterion.
16010 Considered from the testing point of view, a static Ada @code{loop} (that is,
16011 the @code{loop} statement having static subtype in loop parameter
16012 specification) does not add to cyclomatic complexity. By providing
16013 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
16014 may specify that such loops should not be counted when computing the
16015 cyclomatic complexity metric
16016
16017 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
16018 counted for the code that is reduced by excluding all the pure structural Ada
16019 control statements. An compound statement is considered as a non-structural
16020 if it contains a @code{raise} or @code{return} statement as it subcomponent,
16021 or if it contains a @code{goto} statement that transfers the control outside
16022 the operator. A selective accept statement with @code{terminate} alternative
16023 is considered as non-structural statement. When computing this metric,
16024 @code{exit} statements are treated in the same way as @code{goto}
16025 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
16026
16027 The Ada essential complexity metric defined here is intended to quantify
16028 the extent to which the software is unstructured. It is adapted from
16029 the McCabe essential complexity metric defined in
16030 @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more
16031 suitable for typical Ada usage. For example, short circuit forms
16032 are not penalized as unstructured in the Ada essential complexity metric.
16033
16034 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
16035 the code in the exception handlers and in all the nested program units. The
16036 code of assertions and predicates (that is, subprogram preconditions and
16037 postconditions, subtype predicates and type invariants) is also skipped.
16038
16039 By default, all the complexity metrics are computed and reported.
16040 For more fine-grained control you can use
16041 the following switches:
16042
16043 @table @option
16044 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
16045
16046 @ifclear vms
16047 @cindex @option{--no-complexity@var{x}}
16048 @end ifclear
16049
16050 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
16051 Report all the complexity metrics
16052
16053 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
16054 Do not report any of complexity metrics
16055
16056 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
16057 Report the McCabe Cyclomatic Complexity
16058
16059 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
16060 Do not report the McCabe Cyclomatic Complexity
16061
16062 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
16063 Report the Essential Complexity
16064
16065 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
16066 Do not report the Essential Complexity
16067
16068 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
16069 Report maximal loop nesting level
16070
16071 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
16072 Do not report maximal loop nesting level
16073
16074 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
16075 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
16076 task bodies, entry bodies and statement sequences in package bodies.
16077 The metric is computed and reported for whole set of processed Ada sources
16078 only.
16079
16080 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
16081 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
16082 bodies, task bodies, entry bodies and statement sequences in package bodies
16083
16084 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
16085 @item ^-ne^/NO_EXITS_AS_GOTOS^
16086 Do not consider @code{exit} statements as @code{goto}s when
16087 computing Essential Complexity
16088
16089 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
16090 @item ^--no-static-loop^/NO_STATIC_LOOP^
16091 Do not consider static loops when computing cyclomatic complexity
16092
16093 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
16094 Report the extra exit points for subprogram bodies. As an exit point, this
16095 metric counts @code{return} statements and raise statements in case when the
16096 raised exception is not handled in the same body. In case of a function this
16097 metric subtracts 1 from the number of exit points, because a function body
16098 must contain at least one @code{return} statement.
16099
16100 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
16101 Do not report the extra exit points for subprogram bodies
16102 @end table
16103
16104
16105 @node Coupling Metrics Control
16106 @subsubsection Coupling Metrics Control
16107 @cindex Coupling metrics control in @command{gnatmetric}
16108
16109 @noindent
16110 @cindex Coupling metrics (in in @command{gnatmetric})
16111 Coupling metrics measure the dependencies between a given entity and other
16112 entities the program consists of. The goal of these metrics is to estimate the
16113 stability of the whole program considered as the collection of entities
16114 (modules, classes etc.).
16115
16116 Gnatmetric computes the following coupling metrics:
16117
16118 @itemize @bullet
16119
16120 @item
16121 @emph{object-oriented coupling} - for classes in traditional object-oriented
16122 sense;
16123
16124 @item
16125 @emph{unit coupling} - for all the program units making up a program;
16126
16127 @item
16128 @emph{control coupling} - this metric counts dependencies between a unit and
16129 only those units that define subprograms;
16130 @end itemize
16131
16132 @noindent
16133 Two kinds of coupling metrics are computed:
16134
16135 @table @asis
16136 @item fan-out coupling (efferent coupling)
16137 @cindex fan-out coupling
16138 @cindex efferent coupling
16139 the number of entities the given entity depends upon. It
16140 estimates in what extent the given entity depends on the changes in
16141 ``external world''
16142
16143 @item fan-in coupling (afferent coupling)
16144 @cindex fan-in coupling
16145 @cindex afferent coupling
16146 the number of entities that depend on a given entity.
16147 It estimates in what extent the ``external world'' depends on the changes in a
16148 given entity
16149 @end table
16150
16151 @noindent
16152
16153 Object-oriented coupling metrics are metrics that measure the dependencies
16154 between a given class (or a group of classes) and the other classes in the
16155 program. In this subsection the term ``class'' is used in its traditional
16156 object-oriented programming sense (an instantiable module that contains data
16157 and/or method members). A @emph{category} (of classes) is a group of closely
16158 related classes that are reused and/or modified together.
16159
16160 A class @code{K}'s fan-out coupling is the number of classes
16161 that @code{K} depends upon.
16162 A category's fan-out coupling is the number of classes outside the
16163 category that the classes inside the category depend upon.
16164
16165 A class @code{K}'s fan-in coupling is the number of classes
16166 that depend upon @code{K}.
16167 A category's fan-in coupling is the number of classes outside the
16168 category that depend on classes belonging to the category.
16169
16170 Ada's implementation of the object-oriented paradigm does not use the
16171 traditional class notion, so the definition of the coupling
16172 metrics for Ada maps the class and class category notions
16173 onto Ada constructs.
16174
16175 For the coupling metrics, several kinds of modules -- a library package,
16176 a library generic package, and a library generic package instantiation --
16177 that define a tagged type or an interface type are
16178 considered to be a class. A category consists of a library package (or
16179 a library generic package) that defines a tagged or an interface type,
16180 together with all its descendant (generic) packages that define tagged
16181 or interface types. That is a
16182 category is an Ada hierarchy of library-level program units. So class coupling
16183 in case of Ada is called as tagged coupling, and category coupling - as
16184 hierarchy coupling.
16185
16186 For any package counted as a class, its body and subunits (if any) are
16187 considered together with its spec when counting the dependencies, and coupling
16188 metrics are reported for spec units only. For dependencies between classes,
16189 the Ada semantic dependencies are considered. For object-oriented coupling
16190 metrics, only dependencies on units that are considered as classes, are
16191 considered.
16192
16193 For unit and control coupling also not compilation units but program units are
16194 counted. That is, for a package, its spec, its body and its subunits (if any)
16195 are considered as making up one unit, and the dependencies that are counted
16196 are the dependencies of all these compilation units collected together as
16197 the dependencies as a (whole) unit. And metrics are reported for spec
16198 compilation units only (or for a subprogram body unit in case if there is no
16199 separate spec for the given subprogram).
16200
16201 For unit coupling, dependencies between all kinds of program units are
16202 considered. For control coupling, for each unit the dependencies of this unit
16203 upon units that define subprograms are counted, so control fan-out coupling
16204 is reported for all units, but control fan-in coupling - only for the units
16205 that define subprograms.
16206
16207 The following simple example illustrates the difference between unit coupling
16208 and control coupling metrics:
16209
16210 @smallexample @c ada
16211 package Lib_1 is
16212     function F_1 (I : Integer) return Integer;
16213 end Lib_1;
16214
16215 package Lib_2 is
16216     type T_2 is new Integer;
16217 end Lib_2;
16218
16219 package body Lib_1 is
16220     function F_1 (I : Integer) return Integer is
16221     begin
16222        return I + 1;
16223     end F_1;
16224 end Lib_1;
16225
16226 with Lib_2; use Lib_2;
16227 package Pack is
16228     Var : T_2;
16229     function Fun (I : Integer) return Integer;
16230 end Pack;
16231
16232 with Lib_1; use Lib_1;
16233 package body Pack is
16234     function Fun (I : Integer) return Integer is
16235     begin
16236        return F_1 (I);
16237     end Fun;
16238 end Pack;
16239 @end smallexample
16240
16241 @noindent
16242 if we apply @command{gnatmetric} with @code{--coupling-all} option to these
16243 units, the result will be:
16244
16245 @smallexample
16246 Coupling metrics:
16247 =================
16248     Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads)
16249        control fan-out coupling  : 0
16250        control fan-in coupling   : 1
16251        unit fan-out coupling     : 0
16252        unit fan-in coupling      : 1
16253
16254     Unit Pack (C:\customers\662\L406-007\pack.ads)
16255        control fan-out coupling  : 1
16256        control fan-in coupling   : 0
16257        unit fan-out coupling     : 2
16258        unit fan-in coupling      : 0
16259
16260     Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads)
16261        control fan-out coupling  : 0
16262        unit fan-out coupling     : 0
16263        unit fan-in coupling      : 1
16264 @end smallexample
16265
16266 @noindent
16267 The result does not contain values for object-oriented
16268 coupling because none of the argument unit contains a tagged type and
16269 therefore none of these units can be treated as a class.
16270
16271 @code{Pack} (considered as a program unit, that is spec+body) depends on two
16272 units - @code{Lib_1} @code{and Lib_2}, therefore it has unit fan-out coupling
16273 equals to 2. And nothing depend on it, so its unit fan-in coupling is 0 as
16274 well as control fan-in coupling. Only one of the units @code{Pack} depends
16275 upon defines a subprogram, so its control fan-out coupling is 1.
16276
16277 @code{Lib_2} depends on nothing, so fan-out metrics for it are 0. It does
16278 not define a subprogram, so control fan-in metric cannot be applied to it,
16279 and there is one unit that depends on it (@code{Pack}), so it has
16280 unit fan-in coupling equals to 1.
16281
16282 @code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram.
16283 So it has control fan-in coupling equals to 1 (because there is a unit
16284 depending on it).
16285
16286 When computing coupling metrics, @command{gnatmetric} counts only
16287 dependencies between units that are arguments of the @command{gnatmetric}
16288 call. Coupling metrics are program-wide (or project-wide) metrics, so to
16289 get a valid result, you should call @command{gnatmetric} for
16290 the whole set of sources that make up your program. It can be done
16291 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
16292 option (see @ref{The GNAT Driver and Project Files} for details).
16293
16294 By default, all the coupling metrics are disabled. You can use the following
16295 switches to specify the coupling metrics to be computed and reported:
16296
16297 @table @option
16298
16299 @ifclear vms
16300 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
16301 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
16302 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
16303 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
16304 @end ifclear
16305
16306 @ifset vms
16307 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
16308 @end ifset
16309
16310 @item ^--coupling-all^/COUPLING_METRICS=ALL^
16311 Report all the coupling metrics
16312
16313 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
16314 Report tagged (class) fan-out coupling
16315
16316 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
16317 Report tagged (class) fan-in coupling
16318
16319 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
16320 Report hierarchy (category) fan-out coupling
16321
16322 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
16323 Report hierarchy (category) fan-in coupling
16324
16325 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
16326 Report unit fan-out coupling
16327
16328 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
16329 Report unit fan-in coupling
16330
16331 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
16332 Report control fan-out coupling
16333
16334 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
16335 Report control fan-in coupling
16336 @end table
16337
16338 @node Other gnatmetric Switches
16339 @subsection Other @code{gnatmetric} Switches
16340
16341 @noindent
16342 Additional @command{gnatmetric} switches are as follows:
16343
16344 @table @option
16345 @item --version
16346 @cindex @option{--version} @command{gnatmetric}
16347 Display Copyright and version, then exit disregarding all other options.
16348
16349 @item --help
16350 @cindex @option{--help} @command{gnatmetric}
16351 Display usage, then exit disregarding all other options.
16352
16353 @item ^-files @var{filename}^/FILES=@var{filename}^
16354 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
16355 Take the argument source files from the specified file. This file should be an
16356 ordinary text file containing file names separated by spaces or
16357 line breaks. You can use this switch more than once in the same call to
16358 @command{gnatmetric}. You also can combine this switch with
16359 an explicit list of files.
16360
16361 @item ^-v^/VERBOSE^
16362 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
16363 Verbose mode;
16364 @command{gnatmetric} generates version information and then
16365 a trace of sources being processed.
16366
16367 @item ^-q^/QUIET^
16368 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
16369 Quiet mode.
16370 @end table
16371
16372 @node Generate project-wide metrics
16373 @subsection Generate project-wide metrics
16374
16375 In order to compute metrics on all units of a given project, you can use
16376 the @command{gnat} driver along with the @option{-P} option:
16377 @smallexample
16378    gnat metric -Pproj
16379 @end smallexample
16380
16381 @noindent
16382 If the project @code{proj} depends upon other projects, you can compute
16383 the metrics on the project closure using the @option{-U} option:
16384 @smallexample
16385    gnat metric -Pproj -U
16386 @end smallexample
16387
16388 @noindent
16389 Finally, if not all the units are relevant to a particular main
16390 program in the project closure, you can generate metrics for the set
16391 of units needed to create a given main program (unit closure) using
16392 the @option{-U} option followed by the name of the main unit:
16393 @smallexample
16394    gnat metric -Pproj -U main
16395 @end smallexample
16396
16397
16398 @c ***********************************
16399 @node File Name Krunching with gnatkr
16400 @chapter File Name Krunching with @code{gnatkr}
16401 @findex gnatkr
16402
16403 @noindent
16404 This chapter discusses the method used by the compiler to shorten
16405 the default file names chosen for Ada units so that they do not
16406 exceed the maximum length permitted. It also describes the
16407 @code{gnatkr} utility that can be used to determine the result of
16408 applying this shortening.
16409 @menu
16410 * About gnatkr::
16411 * Using gnatkr::
16412 * Krunching Method::
16413 * Examples of gnatkr Usage::
16414 @end menu
16415
16416 @node About gnatkr
16417 @section About @code{gnatkr}
16418
16419 @noindent
16420 The default file naming rule in GNAT
16421 is that the file name must be derived from
16422 the unit name. The exact default rule is as follows:
16423 @itemize @bullet
16424 @item
16425 Take the unit name and replace all dots by hyphens.
16426 @item
16427 If such a replacement occurs in the
16428 second character position of a name, and the first character is
16429 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
16430 then replace the dot by the character
16431 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
16432 instead of a minus.
16433 @end itemize
16434 The reason for this exception is to avoid clashes
16435 with the standard names for children of System, Ada, Interfaces,
16436 and GNAT, which use the prefixes
16437 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
16438 respectively.
16439
16440 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
16441 switch of the compiler activates a ``krunching''
16442 circuit that limits file names to nn characters (where nn is a decimal
16443 integer). For example, using OpenVMS,
16444 where the maximum file name length is
16445 39, the value of nn is usually set to 39, but if you want to generate
16446 a set of files that would be usable if ported to a system with some
16447 different maximum file length, then a different value can be specified.
16448 The default value of 39 for OpenVMS need not be specified.
16449
16450 The @code{gnatkr} utility can be used to determine the krunched name for
16451 a given file, when krunched to a specified maximum length.
16452
16453 @node Using gnatkr
16454 @section Using @code{gnatkr}
16455
16456 @noindent
16457 The @code{gnatkr} command has the form
16458
16459 @ifclear vms
16460 @smallexample
16461 @c $ gnatkr @var{name} @ovar{length}
16462 @c Expanding @ovar macro inline (explanation in macro def comments)
16463 $ gnatkr @var{name} @r{[}@var{length}@r{]}
16464 @end smallexample
16465 @end ifclear
16466
16467 @ifset vms
16468 @smallexample
16469 $ gnatkr @var{name} /COUNT=nn
16470 @end smallexample
16471 @end ifset
16472
16473 @noindent
16474 @var{name} is the uncrunched file name, derived from the name of the unit
16475 in the standard manner described in the previous section (i.e., in particular
16476 all dots are replaced by hyphens). The file name may or may not have an
16477 extension (defined as a suffix of the form period followed by arbitrary
16478 characters other than period). If an extension is present then it will
16479 be preserved in the output. For example, when krunching @file{hellofile.ads}
16480 to eight characters, the result will be hellofil.ads.
16481
16482 Note: for compatibility with previous versions of @code{gnatkr} dots may
16483 appear in the name instead of hyphens, but the last dot will always be
16484 taken as the start of an extension. So if @code{gnatkr} is given an argument
16485 such as @file{Hello.World.adb} it will be treated exactly as if the first
16486 period had been a hyphen, and for example krunching to eight characters
16487 gives the result @file{hellworl.adb}.
16488
16489 Note that the result is always all lower case (except on OpenVMS where it is
16490 all upper case). Characters of the other case are folded as required.
16491
16492 @var{length} represents the length of the krunched name. The default
16493 when no argument is given is ^8^39^ characters. A length of zero stands for
16494 unlimited, in other words do not chop except for system files where the
16495 implied crunching length is always eight characters.
16496
16497 @noindent
16498 The output is the krunched name. The output has an extension only if the
16499 original argument was a file name with an extension.
16500
16501 @node Krunching Method
16502 @section Krunching Method
16503
16504 @noindent
16505 The initial file name is determined by the name of the unit that the file
16506 contains. The name is formed by taking the full expanded name of the
16507 unit and replacing the separating dots with hyphens and
16508 using ^lowercase^uppercase^
16509 for all letters, except that a hyphen in the second character position is
16510 replaced by a ^tilde^dollar sign^ if the first character is
16511 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
16512 The extension is @code{.ads} for a
16513 spec and @code{.adb} for a body.
16514 Krunching does not affect the extension, but the file name is shortened to
16515 the specified length by following these rules:
16516
16517 @itemize @bullet
16518 @item
16519 The name is divided into segments separated by hyphens, tildes or
16520 underscores and all hyphens, tildes, and underscores are
16521 eliminated. If this leaves the name short enough, we are done.
16522
16523 @item
16524 If the name is too long, the longest segment is located (left-most
16525 if there are two of equal length), and shortened by dropping
16526 its last character. This is repeated until the name is short enough.
16527
16528 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16529 to fit the name into 8 characters as required by some operating systems.
16530
16531 @smallexample
16532 our-strings-wide_fixed 22
16533 our strings wide fixed 19
16534 our string  wide fixed 18
16535 our strin   wide fixed 17
16536 our stri    wide fixed 16
16537 our stri    wide fixe  15
16538 our str     wide fixe  14
16539 our str     wid  fixe  13
16540 our str     wid  fix   12
16541 ou  str     wid  fix   11
16542 ou  st      wid  fix   10
16543 ou  st      wi   fix   9
16544 ou  st      wi   fi    8
16545 Final file name: oustwifi.adb
16546 @end smallexample
16547
16548 @item
16549 The file names for all predefined units are always krunched to eight
16550 characters. The krunching of these predefined units uses the following
16551 special prefix replacements:
16552
16553 @table @file
16554 @item ada-
16555 replaced by @file{^a^A^-}
16556
16557 @item gnat-
16558 replaced by @file{^g^G^-}
16559
16560 @item interfaces-
16561 replaced by @file{^i^I^-}
16562
16563 @item system-
16564 replaced by @file{^s^S^-}
16565 @end table
16566
16567 These system files have a hyphen in the second character position. That
16568 is why normal user files replace such a character with a
16569 ^tilde^dollar sign^, to
16570 avoid confusion with system file names.
16571
16572 As an example of this special rule, consider
16573 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16574
16575 @smallexample
16576 ada-strings-wide_fixed 22
16577 a-  strings wide fixed 18
16578 a-  string  wide fixed 17
16579 a-  strin   wide fixed 16
16580 a-  stri    wide fixed 15
16581 a-  stri    wide fixe  14
16582 a-  str     wide fixe  13
16583 a-  str     wid  fixe  12
16584 a-  str     wid  fix   11
16585 a-  st      wid  fix   10
16586 a-  st      wi   fix   9
16587 a-  st      wi   fi    8
16588 Final file name: a-stwifi.adb
16589 @end smallexample
16590 @end itemize
16591
16592 Of course no file shortening algorithm can guarantee uniqueness over all
16593 possible unit names, and if file name krunching is used then it is your
16594 responsibility to ensure that no name clashes occur. The utility
16595 program @code{gnatkr} is supplied for conveniently determining the
16596 krunched name of a file.
16597
16598 @node Examples of gnatkr Usage
16599 @section Examples of @code{gnatkr} Usage
16600
16601 @smallexample
16602 @iftex
16603 @leftskip=0cm
16604 @end iftex
16605 @ifclear vms
16606 $ gnatkr very_long_unit_name.ads      --> velounna.ads
16607 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16608 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16609 $ gnatkr grandparent-parent-child     --> grparchi
16610 @end ifclear
16611 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16612 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16613 @end smallexample
16614
16615 @node Preprocessing with gnatprep
16616 @chapter Preprocessing with @code{gnatprep}
16617 @findex gnatprep
16618
16619 @noindent
16620 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
16621 preprocessing.
16622 Although designed for use with GNAT, @code{gnatprep} does not depend on any
16623 special GNAT features.
16624 For further discussion of conditional compilation in general, see
16625 @ref{Conditional Compilation}.
16626
16627 @menu
16628 * Preprocessing Symbols::
16629 * Using gnatprep::
16630 * Switches for gnatprep::
16631 * Form of Definitions File::
16632 * Form of Input Text for gnatprep::
16633 @end menu
16634
16635 @node Preprocessing Symbols
16636 @section Preprocessing Symbols
16637
16638 @noindent
16639 Preprocessing symbols are defined in definition files and referred to in
16640 sources to be preprocessed. A Preprocessing symbol is an identifier, following
16641 normal Ada (case-insensitive) rules for its syntax, with the restriction that
16642 all characters need to be in the ASCII set (no accented letters).
16643
16644 @node Using gnatprep
16645 @section Using @code{gnatprep}
16646
16647 @noindent
16648 To call @code{gnatprep} use
16649
16650 @smallexample
16651 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
16652 @c Expanding @ovar macro inline (explanation in macro def comments)
16653 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
16654 @end smallexample
16655
16656 @noindent
16657 where
16658 @table @var
16659 @item switches
16660 is an optional sequence of switches as described in the next section.
16661
16662 @item infile
16663 is the full name of the input file, which is an Ada source
16664 file containing preprocessor directives.
16665
16666 @item outfile
16667 is the full name of the output file, which is an Ada source
16668 in standard Ada form. When used with GNAT, this file name will
16669 normally have an ads or adb suffix.
16670
16671 @item deffile
16672 is the full name of a text file containing definitions of
16673 preprocessing symbols to be referenced by the preprocessor. This argument is
16674 optional, and can be replaced by the use of the @option{-D} switch.
16675
16676 @end table
16677
16678 @node Switches for gnatprep
16679 @section Switches for @code{gnatprep}
16680
16681 @table @option
16682 @c !sort!
16683
16684 @item ^-b^/BLANK_LINES^
16685 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16686 Causes both preprocessor lines and the lines deleted by
16687 preprocessing to be replaced by blank lines in the output source file,
16688 preserving line numbers in the output file.
16689
16690 @item ^-c^/COMMENTS^
16691 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16692 Causes both preprocessor lines and the lines deleted
16693 by preprocessing to be retained in the output source as comments marked
16694 with the special string @code{"--! "}. This option will result in line numbers
16695 being preserved in the output file.
16696
16697 @item ^-C^/REPLACE_IN_COMMENTS^
16698 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
16699 Causes comments to be scanned. Normally comments are ignored by gnatprep.
16700 If this option is specified, then comments are scanned and any $symbol
16701 substitutions performed as in program text. This is particularly useful
16702 when structured comments are used (e.g., when writing programs in the
16703 SPARK dialect of Ada). Note that this switch is not available when
16704 doing integrated preprocessing (it would be useless in this context
16705 since comments are ignored by the compiler in any case).
16706
16707 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16708 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16709 Defines a new preprocessing symbol, associated with value. If no value is given
16710 on the command line, then symbol is considered to be @code{True}. This switch
16711 can be used in place of a definition file.
16712
16713 @ifset vms
16714 @item /REMOVE
16715 @cindex @option{/REMOVE} (@command{gnatprep})
16716 This is the default setting which causes lines deleted by preprocessing
16717 to be entirely removed from the output file.
16718 @end ifset
16719
16720 @item ^-r^/REFERENCE^
16721 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16722 Causes a @code{Source_Reference} pragma to be generated that
16723 references the original input file, so that error messages will use
16724 the file name of this original file. The use of this switch implies
16725 that preprocessor lines are not to be removed from the file, so its
16726 use will force @option{^-b^/BLANK_LINES^} mode if
16727 @option{^-c^/COMMENTS^}
16728 has not been specified explicitly.
16729
16730 Note that if the file to be preprocessed contains multiple units, then
16731 it will be necessary to @code{gnatchop} the output file from
16732 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16733 in the preprocessed file, it will be respected by
16734 @code{gnatchop ^-r^/REFERENCE^}
16735 so that the final chopped files will correctly refer to the original
16736 input source file for @code{gnatprep}.
16737
16738 @item ^-s^/SYMBOLS^
16739 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16740 Causes a sorted list of symbol names and values to be
16741 listed on the standard output file.
16742
16743 @item ^-u^/UNDEFINED^
16744 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16745 Causes undefined symbols to be treated as having the value FALSE in the context
16746 of a preprocessor test. In the absence of this option, an undefined symbol in
16747 a @code{#if} or @code{#elsif} test will be treated as an error.
16748
16749 @end table
16750
16751 @ifclear vms
16752 @noindent
16753 Note: if neither @option{-b} nor @option{-c} is present,
16754 then preprocessor lines and
16755 deleted lines are completely removed from the output, unless -r is
16756 specified, in which case -b is assumed.
16757 @end ifclear
16758
16759 @node Form of Definitions File
16760 @section Form of Definitions File
16761
16762 @noindent
16763 The definitions file contains lines of the form
16764
16765 @smallexample
16766 symbol := value
16767 @end smallexample
16768
16769 @noindent
16770 where symbol is a preprocessing symbol, and value is one of the following:
16771
16772 @itemize @bullet
16773 @item
16774 Empty, corresponding to a null substitution
16775 @item
16776 A string literal using normal Ada syntax
16777 @item
16778 Any sequence of characters from the set
16779 (letters, digits, period, underline).
16780 @end itemize
16781
16782 @noindent
16783 Comment lines may also appear in the definitions file, starting with
16784 the usual @code{--},
16785 and comments may be added to the definitions lines.
16786
16787 @node Form of Input Text for gnatprep
16788 @section Form of Input Text for @code{gnatprep}
16789
16790 @noindent
16791 The input text may contain preprocessor conditional inclusion lines,
16792 as well as general symbol substitution sequences.
16793
16794 The preprocessor conditional inclusion commands have the form
16795
16796 @smallexample
16797 @group
16798 @cartouche
16799 #if @i{expression} @r{[}then@r{]}
16800    lines
16801 #elsif @i{expression} @r{[}then@r{]}
16802    lines
16803 #elsif @i{expression} @r{[}then@r{]}
16804    lines
16805 @dots{}
16806 #else
16807    lines
16808 #end if;
16809 @end cartouche
16810 @end group
16811 @end smallexample
16812
16813 @noindent
16814 In this example, @i{expression} is defined by the following grammar:
16815 @smallexample
16816 @i{expression} ::=  <symbol>
16817 @i{expression} ::=  <symbol> = "<value>"
16818 @i{expression} ::=  <symbol> = <symbol>
16819 @i{expression} ::=  <symbol> = <integer>
16820 @i{expression} ::=  <symbol> > <integer>
16821 @i{expression} ::=  <symbol> >= <integer>
16822 @i{expression} ::=  <symbol> < <integer>
16823 @i{expression} ::=  <symbol> <= <integer>
16824 @i{expression} ::=  <symbol> 'Defined
16825 @i{expression} ::=  not @i{expression}
16826 @i{expression} ::=  @i{expression} and @i{expression}
16827 @i{expression} ::=  @i{expression} or @i{expression}
16828 @i{expression} ::=  @i{expression} and then @i{expression}
16829 @i{expression} ::=  @i{expression} or else @i{expression}
16830 @i{expression} ::=  ( @i{expression} )
16831 @end smallexample
16832
16833 The following restriction exists: it is not allowed to have "and" or "or"
16834 following "not" in the same expression without parentheses. For example, this
16835 is not allowed:
16836
16837 @smallexample
16838    not X or Y
16839 @end smallexample
16840
16841 This should be one of the following:
16842
16843 @smallexample
16844    (not X) or Y
16845    not (X or Y)
16846 @end smallexample
16847
16848 @noindent
16849 For the first test (@i{expression} ::= <symbol>) the symbol must have
16850 either the value true or false, that is to say the right-hand of the
16851 symbol definition must be one of the (case-insensitive) literals
16852 @code{True} or @code{False}. If the value is true, then the
16853 corresponding lines are included, and if the value is false, they are
16854 excluded.
16855
16856 When comparing a symbol to an integer, the integer is any non negative
16857 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
16858 2#11#. The symbol value must also be a non negative integer. Integer values
16859 in the range 0 .. 2**31-1 are supported.
16860
16861 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16862 the symbol has been defined in the definition file or by a @option{-D}
16863 switch on the command line. Otherwise, the test is false.
16864
16865 The equality tests are case insensitive, as are all the preprocessor lines.
16866
16867 If the symbol referenced is not defined in the symbol definitions file,
16868 then the effect depends on whether or not switch @option{-u}
16869 is specified. If so, then the symbol is treated as if it had the value
16870 false and the test fails. If this switch is not specified, then
16871 it is an error to reference an undefined symbol. It is also an error to
16872 reference a symbol that is defined with a value other than @code{True}
16873 or @code{False}.
16874
16875 The use of the @code{not} operator inverts the sense of this logical test.
16876 The @code{not} operator cannot be combined with the @code{or} or @code{and}
16877 operators, without parentheses. For example, "if not X or Y then" is not
16878 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
16879
16880 The @code{then} keyword is optional as shown
16881
16882 The @code{#} must be the first non-blank character on a line, but
16883 otherwise the format is free form. Spaces or tabs may appear between
16884 the @code{#} and the keyword. The keywords and the symbols are case
16885 insensitive as in normal Ada code. Comments may be used on a
16886 preprocessor line, but other than that, no other tokens may appear on a
16887 preprocessor line. Any number of @code{elsif} clauses can be present,
16888 including none at all. The @code{else} is optional, as in Ada.
16889
16890 The @code{#} marking the start of a preprocessor line must be the first
16891 non-blank character on the line, i.e., it must be preceded only by
16892 spaces or horizontal tabs.
16893
16894 Symbol substitution outside of preprocessor lines is obtained by using
16895 the sequence
16896
16897 @smallexample
16898 $symbol
16899 @end smallexample
16900
16901 @noindent
16902 anywhere within a source line, except in a comment or within a
16903 string literal. The identifier
16904 following the @code{$} must match one of the symbols defined in the symbol
16905 definition file, and the result is to substitute the value of the
16906 symbol in place of @code{$symbol} in the output file.
16907
16908 Note that although the substitution of strings within a string literal
16909 is not possible, it is possible to have a symbol whose defined value is
16910 a string literal. So instead of setting XYZ to @code{hello} and writing:
16911
16912 @smallexample
16913 Header : String := "$XYZ";
16914 @end smallexample
16915
16916 @noindent
16917 you should set XYZ to @code{"hello"} and write:
16918
16919 @smallexample
16920 Header : String := $XYZ;
16921 @end smallexample
16922
16923 @noindent
16924 and then the substitution will occur as desired.
16925
16926 @node The GNAT Library Browser gnatls
16927 @chapter The GNAT Library Browser @code{gnatls}
16928 @findex gnatls
16929 @cindex Library browser
16930
16931 @noindent
16932 @code{gnatls} is a tool that outputs information about compiled
16933 units. It gives the relationship between objects, unit names and source
16934 files. It can also be used to check the source dependencies of a unit
16935 as well as various characteristics.
16936
16937 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
16938 driver (see @ref{The GNAT Driver and Project Files}).
16939
16940 @menu
16941 * Running gnatls::
16942 * Switches for gnatls::
16943 * Examples of gnatls Usage::
16944 @end menu
16945
16946 @node Running gnatls
16947 @section Running @code{gnatls}
16948
16949 @noindent
16950 The @code{gnatls} command has the form
16951
16952 @smallexample
16953 $ gnatls switches @var{object_or_ali_file}
16954 @end smallexample
16955
16956 @noindent
16957 The main argument is the list of object or @file{ali} files
16958 (@pxref{The Ada Library Information Files})
16959 for which information is requested.
16960
16961 In normal mode, without additional option, @code{gnatls} produces a
16962 four-column listing. Each line represents information for a specific
16963 object. The first column gives the full path of the object, the second
16964 column gives the name of the principal unit in this object, the third
16965 column gives the status of the source and the fourth column gives the
16966 full path of the source representing this unit.
16967 Here is a simple example of use:
16968
16969 @smallexample
16970 $ gnatls *.o
16971 ^./^[]^demo1.o            demo1            DIF demo1.adb
16972 ^./^[]^demo2.o            demo2             OK demo2.adb
16973 ^./^[]^hello.o            h1                OK hello.adb
16974 ^./^[]^instr-child.o      instr.child      MOK instr-child.adb
16975 ^./^[]^instr.o            instr             OK instr.adb
16976 ^./^[]^tef.o              tef              DIF tef.adb
16977 ^./^[]^text_io_example.o  text_io_example   OK text_io_example.adb
16978 ^./^[]^tgef.o             tgef             DIF tgef.adb
16979 @end smallexample
16980
16981 @noindent
16982 The first line can be interpreted as follows: the main unit which is
16983 contained in
16984 object file @file{demo1.o} is demo1, whose main source is in
16985 @file{demo1.adb}. Furthermore, the version of the source used for the
16986 compilation of demo1 has been modified (DIF). Each source file has a status
16987 qualifier which can be:
16988
16989 @table @code
16990 @item OK (unchanged)
16991 The version of the source file used for the compilation of the
16992 specified unit corresponds exactly to the actual source file.
16993
16994 @item MOK (slightly modified)
16995 The version of the source file used for the compilation of the
16996 specified unit differs from the actual source file but not enough to
16997 require recompilation. If you use gnatmake with the qualifier
16998 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
16999 MOK will not be recompiled.
17000
17001 @item DIF (modified)
17002 No version of the source found on the path corresponds to the source
17003 used to build this object.
17004
17005 @item ??? (file not found)
17006 No source file was found for this unit.
17007
17008 @item HID (hidden,  unchanged version not first on PATH)
17009 The version of the source that corresponds exactly to the source used
17010 for compilation has been found on the path but it is hidden by another
17011 version of the same source that has been modified.
17012
17013 @end table
17014
17015 @node Switches for gnatls
17016 @section Switches for @code{gnatls}
17017
17018 @noindent
17019 @code{gnatls} recognizes the following switches:
17020
17021 @table @option
17022 @c !sort!
17023 @cindex @option{--version} @command{gnatls}
17024 Display Copyright and version, then exit disregarding all other options.
17025
17026 @item --help
17027 @cindex @option{--help} @command{gnatls}
17028 If @option{--version} was not used, display usage, then exit disregarding
17029 all other options.
17030
17031 @item ^-a^/ALL_UNITS^
17032 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
17033 Consider all units, including those of the predefined Ada library.
17034 Especially useful with @option{^-d^/DEPENDENCIES^}.
17035
17036 @item ^-d^/DEPENDENCIES^
17037 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
17038 List sources from which specified units depend on.
17039
17040 @item ^-h^/OUTPUT=OPTIONS^
17041 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
17042 Output the list of options.
17043
17044 @item ^-o^/OUTPUT=OBJECTS^
17045 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
17046 Only output information about object files.
17047
17048 @item ^-s^/OUTPUT=SOURCES^
17049 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
17050 Only output information about source files.
17051
17052 @item ^-u^/OUTPUT=UNITS^
17053 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
17054 Only output information about compilation units.
17055
17056 @item ^-files^/FILES^=@var{file}
17057 @cindex @option{^-files^/FILES^} (@code{gnatls})
17058 Take as arguments the files listed in text file @var{file}.
17059 Text file @var{file} may contain empty lines that are ignored.
17060 Each nonempty line should contain the name of an existing file.
17061 Several such switches may be specified simultaneously.
17062
17063 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17064 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
17065 @itemx ^-I^/SEARCH=^@var{dir}
17066 @itemx  ^-I-^/NOCURRENT_DIRECTORY^
17067 @itemx -nostdinc
17068 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
17069 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
17070 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
17071 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
17072 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
17073 flags (@pxref{Switches for gnatmake}).
17074
17075 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^@var{dir}
17076 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (@code{gnatls})
17077 Add @var{dir} at the beginning of the project search dir.
17078
17079 @item --RTS=@var{rts-path}
17080 @cindex @option{--RTS} (@code{gnatls})
17081 Specifies the default location of the runtime library. Same meaning as the
17082 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
17083
17084 @item ^-v^/OUTPUT=VERBOSE^
17085 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
17086 Verbose mode. Output the complete source, object and project paths. Do not use
17087 the default column layout but instead use long format giving as much as
17088 information possible on each requested units, including special
17089 characteristics such as:
17090
17091 @table @code
17092 @item  Preelaborable
17093 The unit is preelaborable in the Ada sense.
17094
17095 @item No_Elab_Code
17096 No elaboration code has been produced by the compiler for this unit.
17097
17098 @item Pure
17099 The unit is pure in the Ada sense.
17100
17101 @item Elaborate_Body
17102 The unit contains a pragma Elaborate_Body.
17103
17104 @item Remote_Types
17105 The unit contains a pragma Remote_Types.
17106
17107 @item Shared_Passive
17108 The unit contains a pragma Shared_Passive.
17109
17110 @item Predefined
17111 This unit is part of the predefined environment and cannot be modified
17112 by the user.
17113
17114 @item Remote_Call_Interface
17115 The unit contains a pragma Remote_Call_Interface.
17116
17117 @end table
17118
17119 @end table
17120
17121 @node Examples of gnatls Usage
17122 @section Example of @code{gnatls} Usage
17123 @ifclear vms
17124
17125 @noindent
17126 Example of using the verbose switch. Note how the source and
17127 object paths are affected by the -I switch.
17128
17129 @smallexample
17130 $ gnatls -v -I.. demo1.o
17131
17132 GNATLS 5.03w (20041123-34)
17133 Copyright 1997-2004 Free Software Foundation, Inc.
17134
17135 Source Search Path:
17136    <Current_Directory>
17137    ../
17138    /home/comar/local/adainclude/
17139
17140 Object Search Path:
17141    <Current_Directory>
17142    ../
17143    /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17144
17145 Project Search Path:
17146    <Current_Directory>
17147    /home/comar/local/lib/gnat/
17148
17149 ./demo1.o
17150    Unit =>
17151      Name   => demo1
17152      Kind   => subprogram body
17153      Flags  => No_Elab_Code
17154      Source => demo1.adb    modified
17155 @end smallexample
17156
17157 @noindent
17158 The following is an example of use of the dependency list.
17159 Note the use of the -s switch
17160 which gives a straight list of source files. This can be useful for
17161 building specialized scripts.
17162
17163 @smallexample
17164 $ gnatls -d demo2.o
17165 ./demo2.o   demo2        OK demo2.adb
17166                          OK gen_list.ads
17167                          OK gen_list.adb
17168                          OK instr.ads
17169                          OK instr-child.ads
17170
17171 $ gnatls -d -s -a demo1.o
17172 demo1.adb
17173 /home/comar/local/adainclude/ada.ads
17174 /home/comar/local/adainclude/a-finali.ads
17175 /home/comar/local/adainclude/a-filico.ads
17176 /home/comar/local/adainclude/a-stream.ads
17177 /home/comar/local/adainclude/a-tags.ads
17178 gen_list.ads
17179 gen_list.adb
17180 /home/comar/local/adainclude/gnat.ads
17181 /home/comar/local/adainclude/g-io.ads
17182 instr.ads
17183 /home/comar/local/adainclude/system.ads
17184 /home/comar/local/adainclude/s-exctab.ads
17185 /home/comar/local/adainclude/s-finimp.ads
17186 /home/comar/local/adainclude/s-finroo.ads
17187 /home/comar/local/adainclude/s-secsta.ads
17188 /home/comar/local/adainclude/s-stalib.ads
17189 /home/comar/local/adainclude/s-stoele.ads
17190 /home/comar/local/adainclude/s-stratt.ads
17191 /home/comar/local/adainclude/s-tasoli.ads
17192 /home/comar/local/adainclude/s-unstyp.ads
17193 /home/comar/local/adainclude/unchconv.ads
17194 @end smallexample
17195 @end ifclear
17196
17197 @ifset vms
17198 @smallexample
17199 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
17200
17201 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
17202 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
17203 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
17204 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
17205 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
17206 demo1.adb
17207 gen_list.ads
17208 gen_list.adb
17209 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
17210 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
17211 instr.ads
17212 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
17213 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
17214 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
17215 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
17216 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
17217 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
17218 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
17219 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
17220 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
17221 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
17222 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
17223 @end smallexample
17224 @end ifset
17225
17226 @node Cleaning Up with gnatclean
17227 @chapter Cleaning Up with @code{gnatclean}
17228 @findex gnatclean
17229 @cindex Cleaning tool
17230
17231 @noindent
17232 @code{gnatclean} is a tool that allows the deletion of files produced by the
17233 compiler, binder and linker, including ALI files, object files, tree files,
17234 expanded source files, library files, interface copy source files, binder
17235 generated files and executable files.
17236
17237 @menu
17238 * Running gnatclean::
17239 * Switches for gnatclean::
17240 @c * Examples of gnatclean Usage::
17241 @end menu
17242
17243 @node Running gnatclean
17244 @section Running @code{gnatclean}
17245
17246 @noindent
17247 The @code{gnatclean} command has the form:
17248
17249 @smallexample
17250 $ gnatclean switches @var{names}
17251 @end smallexample
17252
17253 @noindent
17254 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
17255 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
17256 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
17257
17258 @noindent
17259 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17260 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
17261 the linker. In informative-only mode, specified by switch
17262 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
17263 normal mode is listed, but no file is actually deleted.
17264
17265 @node Switches for gnatclean
17266 @section Switches for @code{gnatclean}
17267
17268 @noindent
17269 @code{gnatclean} recognizes the following switches:
17270
17271 @table @option
17272 @c !sort!
17273 @cindex @option{--version} @command{gnatclean}
17274 Display Copyright and version, then exit disregarding all other options.
17275
17276 @item --help
17277 @cindex @option{--help} @command{gnatclean}
17278 If @option{--version} was not used, display usage, then exit disregarding
17279 all other options.
17280
17281 @item ^--subdirs^/SUBDIRS^=subdir
17282 Actual object directory of each project file is the subdirectory subdir of the
17283 object directory specified or defaulted in the project file.
17284
17285 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
17286 By default, shared library projects are not allowed to import static library
17287 projects. When this switch is used on the command line, this restriction is
17288 relaxed.
17289
17290 @item ^-c^/COMPILER_FILES_ONLY^
17291 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
17292 Only attempt to delete the files produced by the compiler, not those produced
17293 by the binder or the linker. The files that are not to be deleted are library
17294 files, interface copy files, binder generated files and executable files.
17295
17296 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
17297 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17298 Indicate that ALI and object files should normally be found in directory
17299 @var{dir}.
17300
17301 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17302 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17303 When using project files, if some errors or warnings are detected during
17304 parsing and verbose mode is not in effect (no use of switch
17305 ^-v^/VERBOSE^), then error lines start with the full path name of the project
17306 file, rather than its simple file name.
17307
17308 @item ^-h^/HELP^
17309 @cindex @option{^-h^/HELP^} (@code{gnatclean})
17310 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17311
17312 @item ^-n^/NODELETE^
17313 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17314 Informative-only mode. Do not delete any files. Output the list of the files
17315 that would have been deleted if this switch was not specified.
17316
17317 @item ^-P^/PROJECT_FILE=^@var{project}
17318 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17319 Use project file @var{project}. Only one such switch can be used.
17320 When cleaning a project file, the files produced by the compilation of the
17321 immediate sources or inherited sources of the project files are to be
17322 deleted. This is not depending on the presence or not of executable names
17323 on the command line.
17324
17325 @item ^-q^/QUIET^
17326 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
17327 Quiet output. If there are no errors, do not output anything, except in
17328 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17329 (switch ^-n^/NODELETE^).
17330
17331 @item ^-r^/RECURSIVE^
17332 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17333 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17334 clean all imported and extended project files, recursively. If this switch
17335 is not specified, only the files related to the main project file are to be
17336 deleted. This switch has no effect if no project file is specified.
17337
17338 @item ^-v^/VERBOSE^
17339 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17340 Verbose mode.
17341
17342 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17343 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17344 Indicates the verbosity of the parsing of GNAT project files.
17345 @xref{Switches Related to Project Files}.
17346
17347 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17348 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17349 Indicates that external variable @var{name} has the value @var{value}.
17350 The Project Manager will use this value for occurrences of
17351 @code{external(name)} when parsing the project file.
17352 @xref{Switches Related to Project Files}.
17353
17354 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17355 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17356 When searching for ALI and object files, look in directory
17357 @var{dir}.
17358
17359 @item ^-I^/SEARCH=^@var{dir}
17360 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17361 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17362
17363 @item ^-I-^/NOCURRENT_DIRECTORY^
17364 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
17365 @cindex Source files, suppressing search
17366 Do not look for ALI or object files in the directory
17367 where @code{gnatclean} was invoked.
17368
17369 @end table
17370
17371 @c @node Examples of gnatclean Usage
17372 @c @section Examples of @code{gnatclean} Usage
17373
17374 @ifclear vms
17375 @node GNAT and Libraries
17376 @chapter GNAT and Libraries
17377 @cindex Library, building, installing, using
17378
17379 @noindent
17380 This chapter describes how to build and use libraries with GNAT, and also shows
17381 how to recompile the GNAT run-time library. You should be familiar with the
17382 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
17383 chapter.
17384
17385 @menu
17386 * Introduction to Libraries in GNAT::
17387 * General Ada Libraries::
17388 * Stand-alone Ada Libraries::
17389 * Rebuilding the GNAT Run-Time Library::
17390 @end menu
17391
17392 @node Introduction to Libraries in GNAT
17393 @section Introduction to Libraries in GNAT
17394
17395 @noindent
17396 A library is, conceptually, a collection of objects which does not have its
17397 own main thread of execution, but rather provides certain services to the
17398 applications that use it. A library can be either statically linked with the
17399 application, in which case its code is directly included in the application,
17400 or, on platforms that support it, be dynamically linked, in which case
17401 its code is shared by all applications making use of this library.
17402
17403 GNAT supports both types of libraries.
17404 In the static case, the compiled code can be provided in different ways. The
17405 simplest approach is to provide directly the set of objects resulting from
17406 compilation of the library source files. Alternatively, you can group the
17407 objects into an archive using whatever commands are provided by the operating
17408 system. For the latter case, the objects are grouped into a shared library.
17409
17410 In the GNAT environment, a library has three types of components:
17411 @itemize @bullet
17412 @item
17413 Source files.
17414 @item
17415 @file{ALI} files.
17416 @xref{The Ada Library Information Files}.
17417 @item
17418 Object files, an archive or a shared library.
17419 @end itemize
17420
17421 @noindent
17422 A GNAT library may expose all its source files, which is useful for
17423 documentation purposes. Alternatively, it may expose only the units needed by
17424 an external user to make use of the library. That is to say, the specs
17425 reflecting the library services along with all the units needed to compile
17426 those specs, which can include generic bodies or any body implementing an
17427 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17428 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17429
17430 All compilation units comprising an application, including those in a library,
17431 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17432 computes the elaboration order from the @file{ALI} files and this is why they
17433 constitute a mandatory part of GNAT libraries.
17434 @emph{Stand-alone libraries} are the exception to this rule because a specific
17435 library elaboration routine is produced independently of the application(s)
17436 using the library.
17437
17438 @node General Ada Libraries
17439 @section General Ada Libraries
17440
17441 @menu
17442 * Building a library::
17443 * Installing a library::
17444 * Using a library::
17445 @end menu
17446
17447 @node Building a library
17448 @subsection Building a library
17449
17450 @noindent
17451 The easiest way to build a library is to use the Project Manager,
17452 which supports a special type of project called a @emph{Library Project}
17453 (@pxref{Library Projects}).
17454
17455 A project is considered a library project, when two project-level attributes
17456 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17457 control different aspects of library configuration, additional optional
17458 project-level attributes can be specified:
17459 @table @code
17460 @item Library_Kind
17461 This attribute controls whether the library is to be static or dynamic
17462
17463 @item Library_Version
17464 This attribute specifies the library version; this value is used
17465 during dynamic linking of shared libraries to determine if the currently
17466 installed versions of the binaries are compatible.
17467
17468 @item Library_Options
17469 @item Library_GCC
17470 These attributes specify additional low-level options to be used during
17471 library generation, and redefine the actual application used to generate
17472 library.
17473 @end table
17474
17475 @noindent
17476 The GNAT Project Manager takes full care of the library maintenance task,
17477 including recompilation of the source files for which objects do not exist
17478 or are not up to date, assembly of the library archive, and installation of
17479 the library (i.e., copying associated source, object and @file{ALI} files
17480 to the specified location).
17481
17482 Here is a simple library project file:
17483 @smallexample @c ada
17484 project My_Lib is
17485    for Source_Dirs use ("src1", "src2");
17486    for Object_Dir use "obj";
17487    for Library_Name use "mylib";
17488    for Library_Dir use "lib";
17489    for Library_Kind use "dynamic";
17490 end My_lib;
17491 @end smallexample
17492
17493 @noindent
17494 and the compilation command to build and install the library:
17495
17496 @smallexample @c ada
17497   $ gnatmake -Pmy_lib
17498 @end smallexample
17499
17500 @noindent
17501 It is not entirely trivial to perform manually all the steps required to
17502 produce a library. We recommend that you use the GNAT Project Manager
17503 for this task. In special cases where this is not desired, the necessary
17504 steps are discussed below.
17505
17506 There are various possibilities for compiling the units that make up the
17507 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17508 with a conventional script. For simple libraries, it is also possible to create
17509 a dummy main program which depends upon all the packages that comprise the
17510 interface of the library. This dummy main program can then be given to
17511 @command{gnatmake}, which will ensure that all necessary objects are built.
17512
17513 After this task is accomplished, you should follow the standard procedure
17514 of the underlying operating system to produce the static or shared library.
17515
17516 Here is an example of such a dummy program:
17517 @smallexample @c ada
17518 @group
17519 with My_Lib.Service1;
17520 with My_Lib.Service2;
17521 with My_Lib.Service3;
17522 procedure My_Lib_Dummy is
17523 begin
17524    null;
17525 end;
17526 @end group
17527 @end smallexample
17528
17529 @noindent
17530 Here are the generic commands that will build an archive or a shared library.
17531
17532 @smallexample
17533 # compiling the library
17534 $ gnatmake -c my_lib_dummy.adb
17535
17536 # we don't need the dummy object itself
17537 $ rm my_lib_dummy.o my_lib_dummy.ali
17538
17539 # create an archive with the remaining objects
17540 $ ar rc libmy_lib.a *.o
17541 # some systems may require "ranlib" to be run as well
17542
17543 # or create a shared library
17544 $ gcc -shared -o libmy_lib.so *.o
17545 # some systems may require the code to have been compiled with -fPIC
17546
17547 # remove the object files that are now in the library
17548 $ rm *.o
17549
17550 # Make the ALI files read-only so that gnatmake will not try to
17551 # regenerate the objects that are in the library
17552 $ chmod -w *.ali
17553 @end smallexample
17554
17555 @noindent
17556 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
17557 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
17558 be accessed by the directive @option{-l@var{xxx}} at link time.
17559
17560 @node Installing a library
17561 @subsection Installing a library
17562 @cindex @code{ADA_PROJECT_PATH}
17563 @cindex @code{GPR_PROJECT_PATH}
17564
17565 @noindent
17566 If you use project files, library installation is part of the library build
17567 process (@pxref{Installing a library with project files}).
17568
17569 When project files are not an option, it is also possible, but not recommended,
17570 to install the library so that the sources needed to use the library are on the
17571 Ada source path and the ALI files & libraries be on the Ada Object path (see
17572 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17573 administrator can place general-purpose libraries in the default compiler
17574 paths, by specifying the libraries' location in the configuration files
17575 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17576 must be located in the GNAT installation tree at the same place as the gcc spec
17577 file. The location of the gcc spec file can be determined as follows:
17578 @smallexample
17579 $ gcc -v
17580 @end smallexample
17581
17582 @noindent
17583 The configuration files mentioned above have a simple format: each line
17584 must contain one unique directory name.
17585 Those names are added to the corresponding path
17586 in their order of appearance in the file. The names can be either absolute
17587 or relative; in the latter case, they are relative to where theses files
17588 are located.
17589
17590 The files @file{ada_source_path} and @file{ada_object_path} might not be
17591 present in a
17592 GNAT installation, in which case, GNAT will look for its run-time library in
17593 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17594 objects and @file{ALI} files). When the files exist, the compiler does not
17595 look in @file{adainclude} and @file{adalib}, and thus the
17596 @file{ada_source_path} file
17597 must contain the location for the GNAT run-time sources (which can simply
17598 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17599 contain the location for the GNAT run-time objects (which can simply
17600 be @file{adalib}).
17601
17602 You can also specify a new default path to the run-time library at compilation
17603 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17604 the run-time library you want your program to be compiled with. This switch is
17605 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17606 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17607
17608 It is possible to install a library before or after the standard GNAT
17609 library, by reordering the lines in the configuration files. In general, a
17610 library must be installed before the GNAT library if it redefines
17611 any part of it.
17612
17613 @node Using a library
17614 @subsection Using a library
17615
17616 @noindent Once again, the project facility greatly simplifies the use of
17617 libraries. In this context, using a library is just a matter of adding a
17618 @code{with} clause in the user project. For instance, to make use of the
17619 library @code{My_Lib} shown in examples in earlier sections, you can
17620 write:
17621
17622 @smallexample @c projectfile
17623 with "my_lib";
17624 project My_Proj is
17625   @dots{}
17626 end My_Proj;
17627 @end smallexample
17628
17629 Even if you have a third-party, non-Ada library, you can still use GNAT's
17630 Project Manager facility to provide a wrapper for it. For example, the
17631 following project, when @code{with}ed by your main project, will link with the
17632 third-party library @file{liba.a}:
17633
17634 @smallexample @c projectfile
17635 @group
17636 project Liba is
17637    for Externally_Built use "true";
17638    for Source_Files use ();
17639    for Library_Dir use "lib";
17640    for Library_Name use "a";
17641    for Library_Kind use "static";
17642 end Liba;
17643 @end group
17644 @end smallexample
17645 This is an alternative to the use of @code{pragma Linker_Options}. It is
17646 especially interesting in the context of systems with several interdependent
17647 static libraries where finding a proper linker order is not easy and best be
17648 left to the tools having visibility over project dependence information.
17649
17650 @noindent
17651 In order to use an Ada library manually, you need to make sure that this
17652 library is on both your source and object path
17653 (see @ref{Search Paths and the Run-Time Library (RTL)}
17654 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17655 in an archive or a shared library, you need to specify the desired
17656 library at link time.
17657
17658 For example, you can use the library @file{mylib} installed in
17659 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17660
17661 @smallexample
17662 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17663   -largs -lmy_lib
17664 @end smallexample
17665
17666 @noindent
17667 This can be expressed more simply:
17668 @smallexample
17669 $ gnatmake my_appl
17670 @end smallexample
17671 @noindent
17672 when the following conditions are met:
17673 @itemize @bullet
17674 @item
17675 @file{/dir/my_lib_src} has been added by the user to the environment
17676 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
17677 @file{ada_source_path}
17678 @item
17679 @file{/dir/my_lib_obj} has been added by the user to the environment
17680 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
17681 @file{ada_object_path}
17682 @item
17683 a pragma @code{Linker_Options} has been added to one of the sources.
17684 For example:
17685
17686 @smallexample @c ada
17687 pragma Linker_Options ("-lmy_lib");
17688 @end smallexample
17689 @end itemize
17690
17691 @node Stand-alone Ada Libraries
17692 @section Stand-alone Ada Libraries
17693 @cindex Stand-alone library, building, using
17694
17695 @menu
17696 * Introduction to Stand-alone Libraries::
17697 * Building a Stand-alone Library::
17698 * Creating a Stand-alone Library to be used in a non-Ada context::
17699 * Restrictions in Stand-alone Libraries::
17700 @end menu
17701
17702 @node Introduction to Stand-alone Libraries
17703 @subsection Introduction to Stand-alone Libraries
17704
17705 @noindent
17706 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17707 necessary code to
17708 elaborate the Ada units that are included in the library. In contrast with
17709 an ordinary library, which consists of all sources, objects and @file{ALI}
17710 files of the
17711 library, a SAL may specify a restricted subset of compilation units
17712 to serve as a library interface. In this case, the fully
17713 self-sufficient set of files will normally consist of an objects
17714 archive, the sources of interface units' specs, and the @file{ALI}
17715 files of interface units.
17716 If an interface spec contains a generic unit or an inlined subprogram,
17717 the body's
17718 source must also be provided; if the units that must be provided in the source
17719 form depend on other units, the source and @file{ALI} files of those must
17720 also be provided.
17721
17722 The main purpose of a SAL is to minimize the recompilation overhead of client
17723 applications when a new version of the library is installed. Specifically,
17724 if the interface sources have not changed, client applications do not need to
17725 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17726 version, controlled by @code{Library_Version} attribute, is not changed,
17727 then the clients do not need to be relinked.
17728
17729 SALs also allow the library providers to minimize the amount of library source
17730 text exposed to the clients.  Such ``information hiding'' might be useful or
17731 necessary for various reasons.
17732
17733 Stand-alone libraries are also well suited to be used in an executable whose
17734 main routine is not written in Ada.
17735
17736 @node Building a Stand-alone Library
17737 @subsection Building a Stand-alone Library
17738
17739 @noindent
17740 GNAT's Project facility provides a simple way of building and installing
17741 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17742 To be a Stand-alone Library Project, in addition to the two attributes
17743 that make a project a Library Project (@code{Library_Name} and
17744 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17745 @code{Library_Interface} must be defined.  For example:
17746
17747 @smallexample @c projectfile
17748 @group
17749    for Library_Dir use "lib_dir";
17750    for Library_Name use "dummy";
17751    for Library_Interface use ("int1", "int1.child");
17752 @end group
17753 @end smallexample
17754
17755 @noindent
17756 Attribute @code{Library_Interface} has a non-empty string list value,
17757 each string in the list designating a unit contained in an immediate source
17758 of the project file.
17759
17760 When a Stand-alone Library is built, first the binder is invoked to build
17761 a package whose name depends on the library name
17762 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
17763 This binder-generated package includes initialization and
17764 finalization procedures whose
17765 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17766 in the example
17767 above). The object corresponding to this package is included in the library.
17768
17769 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17770 calling of these procedures if a static SAL is built, or if a shared SAL
17771 is built
17772 with the project-level attribute @code{Library_Auto_Init} set to
17773 @code{"false"}.
17774
17775 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17776 (those that are listed in attribute @code{Library_Interface}) are copied to
17777 the Library Directory. As a consequence, only the Interface Units may be
17778 imported from Ada units outside of the library. If other units are imported,
17779 the binding phase will fail.
17780
17781 @noindent
17782 It is also possible to build an encapsulated library where not only
17783 the code to elaborate and finalize the library is embedded but also
17784 ensuring that the library is linked only against static
17785 libraries. So an encapsulated library only depends on system
17786 libraries, all other code, including the GNAT runtime, is embedded. To
17787 build an encapsulated library the attribute
17788 @code{Library_Standalone} must be set to @code{encapsulated}:
17789
17790 @smallexample @c projectfile
17791 @group
17792    for Library_Dir use "lib_dir";
17793    for Library_Name use "dummy";
17794    for Library_Kind use "dynamic";
17795    for Library_Interface use ("int1", "int1.child");
17796    for Library_Standalone use "encapsulated";
17797 @end group
17798 @end smallexample
17799
17800 @noindent
17801 The default value for this attribute is @code{standard} in which case
17802 a stand-alone library is built.
17803
17804 The attribute @code{Library_Src_Dir} may be specified for a
17805 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17806 single string value. Its value must be the path (absolute or relative to the
17807 project directory) of an existing directory. This directory cannot be the
17808 object directory or one of the source directories, but it can be the same as
17809 the library directory. The sources of the Interface
17810 Units of the library that are needed by an Ada client of the library will be
17811 copied to the designated directory, called the Interface Copy directory.
17812 These sources include the specs of the Interface Units, but they may also
17813 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17814 are used, or when there is a generic unit in the spec. Before the sources
17815 are copied to the Interface Copy directory, an attempt is made to delete all
17816 files in the Interface Copy directory.
17817
17818 Building stand-alone libraries by hand is somewhat tedious, but for those
17819 occasions when it is necessary here are the steps that you need to perform:
17820 @itemize @bullet
17821 @item
17822 Compile all library sources.
17823
17824 @item
17825 Invoke the binder with the switch @option{-n} (No Ada main program),
17826 with all the @file{ALI} files of the interfaces, and
17827 with the switch @option{-L} to give specific names to the @code{init}
17828 and @code{final} procedures.  For example:
17829 @smallexample
17830   gnatbind -n int1.ali int2.ali -Lsal1
17831 @end smallexample
17832
17833 @item
17834 Compile the binder generated file:
17835 @smallexample
17836   gcc -c b~int2.adb
17837 @end smallexample
17838
17839 @item
17840 Link the dynamic library with all the necessary object files,
17841 indicating to the linker the names of the @code{init} (and possibly
17842 @code{final}) procedures for automatic initialization (and finalization).
17843 The built library should be placed in a directory different from
17844 the object directory.
17845
17846 @item
17847 Copy the @code{ALI} files of the interface to the library directory,
17848 add in this copy an indication that it is an interface to a SAL
17849 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
17850 with letter ``P'') and make the modified copy of the @file{ALI} file
17851 read-only.
17852 @end itemize
17853
17854 @noindent
17855 Using SALs is not different from using other libraries
17856 (see @ref{Using a library}).
17857
17858 @node Creating a Stand-alone Library to be used in a non-Ada context
17859 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17860
17861 @noindent
17862 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17863 a non-Ada context.
17864
17865 The only extra step required is to ensure that library interface subprograms
17866 are compatible with the main program, by means of @code{pragma Export}
17867 or @code{pragma Convention}.
17868
17869 Here is an example of simple library interface for use with C main program:
17870
17871 @smallexample @c ada
17872 package My_Package is
17873
17874    procedure Do_Something;
17875    pragma Export (C, Do_Something, "do_something");
17876
17877    procedure Do_Something_Else;
17878    pragma Export (C, Do_Something_Else, "do_something_else");
17879
17880 end My_Package;
17881 @end smallexample
17882
17883 @noindent
17884 On the foreign language side, you must provide a ``foreign'' view of the
17885 library interface; remember that it should contain elaboration routines in
17886 addition to interface subprograms.
17887
17888 The example below shows the content of @code{mylib_interface.h} (note
17889 that there is no rule for the naming of this file, any name can be used)
17890 @smallexample
17891 /* the library elaboration procedure */
17892 extern void mylibinit (void);
17893
17894 /* the library finalization procedure */
17895 extern void mylibfinal (void);
17896
17897 /* the interface exported by the library */
17898 extern void do_something (void);
17899 extern void do_something_else (void);
17900 @end smallexample
17901
17902 @noindent
17903 Libraries built as explained above can be used from any program, provided
17904 that the elaboration procedures (named @code{mylibinit} in the previous
17905 example) are called before the library services are used. Any number of
17906 libraries can be used simultaneously, as long as the elaboration
17907 procedure of each library is called.
17908
17909 Below is an example of a C program that uses the @code{mylib} library.
17910
17911 @smallexample
17912 #include "mylib_interface.h"
17913
17914 int
17915 main (void)
17916 @{
17917    /* First, elaborate the library before using it */
17918    mylibinit ();
17919
17920    /* Main program, using the library exported entities */
17921    do_something ();
17922    do_something_else ();
17923
17924    /* Library finalization at the end of the program */
17925    mylibfinal ();
17926    return 0;
17927 @}
17928 @end smallexample
17929
17930 @noindent
17931 Note that invoking any library finalization procedure generated by
17932 @code{gnatbind} shuts down the Ada run-time environment.
17933 Consequently, the
17934 finalization of all Ada libraries must be performed at the end of the program.
17935 No call to these libraries or to the Ada run-time library should be made
17936 after the finalization phase.
17937
17938 @node Restrictions in Stand-alone Libraries
17939 @subsection Restrictions in Stand-alone Libraries
17940
17941 @noindent
17942 The pragmas listed below should be used with caution inside libraries,
17943 as they can create incompatibilities with other Ada libraries:
17944 @itemize @bullet
17945 @item pragma @code{Locking_Policy}
17946 @item pragma @code{Partition_Elaboration_Policy}
17947 @item pragma @code{Queuing_Policy}
17948 @item pragma @code{Task_Dispatching_Policy}
17949 @item pragma @code{Unreserve_All_Interrupts}
17950 @end itemize
17951
17952 @noindent
17953 When using a library that contains such pragmas, the user must make sure
17954 that all libraries use the same pragmas with the same values. Otherwise,
17955 @code{Program_Error} will
17956 be raised during the elaboration of the conflicting
17957 libraries. The usage of these pragmas and its consequences for the user
17958 should therefore be well documented.
17959
17960 Similarly, the traceback in the exception occurrence mechanism should be
17961 enabled or disabled in a consistent manner across all libraries.
17962 Otherwise, Program_Error will be raised during the elaboration of the
17963 conflicting libraries.
17964
17965 If the @code{Version} or @code{Body_Version}
17966 attributes are used inside a library, then you need to
17967 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
17968 libraries, so that version identifiers can be properly computed.
17969 In practice these attributes are rarely used, so this is unlikely
17970 to be a consideration.
17971
17972 @node  Rebuilding the GNAT Run-Time Library
17973 @section Rebuilding the GNAT Run-Time Library
17974 @cindex GNAT Run-Time Library, rebuilding
17975 @cindex Building the GNAT Run-Time Library
17976 @cindex Rebuilding the GNAT Run-Time Library
17977 @cindex Run-Time Library, rebuilding
17978
17979 @noindent
17980 It may be useful to recompile the GNAT library in various contexts, the
17981 most important one being the use of partition-wide configuration pragmas
17982 such as @code{Normalize_Scalars}. A special Makefile called
17983 @code{Makefile.adalib} is provided to that effect and can be found in
17984 the directory containing the GNAT library. The location of this
17985 directory depends on the way the GNAT environment has been installed and can
17986 be determined by means of the command:
17987
17988 @smallexample
17989 $ gnatls -v
17990 @end smallexample
17991
17992 @noindent
17993 The last entry in the object search path usually contains the
17994 gnat library. This Makefile contains its own documentation and in
17995 particular the set of instructions needed to rebuild a new library and
17996 to use it.
17997
17998 @node Using the GNU make Utility
17999 @chapter Using the GNU @code{make} Utility
18000 @findex make
18001
18002 @noindent
18003 This chapter offers some examples of makefiles that solve specific
18004 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
18005 make, make, GNU @code{make}}), nor does it try to replace the
18006 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
18007
18008 All the examples in this section are specific to the GNU version of
18009 make. Although @command{make} is a standard utility, and the basic language
18010 is the same, these examples use some advanced features found only in
18011 @code{GNU make}.
18012
18013 @menu
18014 * Using gnatmake in a Makefile::
18015 * Automatically Creating a List of Directories::
18016 * Generating the Command Line Switches::
18017 * Overcoming Command Line Length Limits::
18018 @end menu
18019
18020 @node Using gnatmake in a Makefile
18021 @section Using gnatmake in a Makefile
18022 @findex makefile
18023 @cindex GNU make
18024
18025 @noindent
18026 Complex project organizations can be handled in a very powerful way by
18027 using GNU make combined with gnatmake. For instance, here is a Makefile
18028 which allows you to build each subsystem of a big project into a separate
18029 shared library. Such a makefile allows you to significantly reduce the link
18030 time of very big applications while maintaining full coherence at
18031 each step of the build process.
18032
18033 The list of dependencies are handled automatically by
18034 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
18035 the appropriate directories.
18036
18037 Note that you should also read the example on how to automatically
18038 create the list of directories
18039 (@pxref{Automatically Creating a List of Directories})
18040 which might help you in case your project has a lot of subdirectories.
18041
18042 @smallexample
18043 @iftex
18044 @leftskip=0cm
18045 @font@heightrm=cmr8
18046 @heightrm
18047 @end iftex
18048 ## This Makefile is intended to be used with the following directory
18049 ## configuration:
18050 ##  - The sources are split into a series of csc (computer software components)
18051 ##    Each of these csc is put in its own directory.
18052 ##    Their name are referenced by the directory names.
18053 ##    They will be compiled into shared library (although this would also work
18054 ##    with static libraries
18055 ##  - The main program (and possibly other packages that do not belong to any
18056 ##    csc is put in the top level directory (where the Makefile is).
18057 ##       toplevel_dir __ first_csc  (sources) __ lib (will contain the library)
18058 ##                    \_ second_csc (sources) __ lib (will contain the library)
18059 ##                    \_ @dots{}
18060 ## Although this Makefile is build for shared library, it is easy to modify
18061 ## to build partial link objects instead (modify the lines with -shared and
18062 ## gnatlink below)
18063 ##
18064 ## With this makefile, you can change any file in the system or add any new
18065 ## file, and everything will be recompiled correctly (only the relevant shared
18066 ## objects will be recompiled, and the main program will be re-linked).
18067
18068 # The list of computer software component for your project. This might be
18069 # generated automatically.
18070 CSC_LIST=aa bb cc
18071
18072 # Name of the main program (no extension)
18073 MAIN=main
18074
18075 # If we need to build objects with -fPIC, uncomment the following line
18076 #NEED_FPIC=-fPIC
18077
18078 # The following variable should give the directory containing libgnat.so
18079 # You can get this directory through 'gnatls -v'. This is usually the last
18080 # directory in the Object_Path.
18081 GLIB=@dots{}
18082
18083 # The directories for the libraries
18084 # (This macro expands the list of CSC to the list of shared libraries, you
18085 # could simply use the expanded form:
18086 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
18087 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
18088
18089 $@{MAIN@}: objects $@{LIB_DIR@}
18090     gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
18091     gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
18092
18093 objects::
18094     # recompile the sources
18095     gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
18096
18097 # Note: In a future version of GNAT, the following commands will be simplified
18098 # by a new tool, gnatmlib
18099 $@{LIB_DIR@}:
18100     mkdir -p $@{dir $@@ @}
18101     cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
18102     cd $@{dir $@@ @} && cp -f ../*.ali .
18103
18104 # The dependencies for the modules
18105 # Note that we have to force the expansion of *.o, since in some cases
18106 # make won't be able to do it itself.
18107 aa/lib/libaa.so: $@{wildcard aa/*.o@}
18108 bb/lib/libbb.so: $@{wildcard bb/*.o@}
18109 cc/lib/libcc.so: $@{wildcard cc/*.o@}
18110
18111 # Make sure all of the shared libraries are in the path before starting the
18112 # program
18113 run::
18114     LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
18115
18116 clean::
18117     $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
18118     $@{RM@} $@{CSC_LIST:%=%/*.ali@}
18119     $@{RM@} $@{CSC_LIST:%=%/*.o@}
18120     $@{RM@} *.o *.ali $@{MAIN@}
18121 @end smallexample
18122
18123 @node Automatically Creating a List of Directories
18124 @section Automatically Creating a List of Directories
18125
18126 @noindent
18127 In most makefiles, you will have to specify a list of directories, and
18128 store it in a variable. For small projects, it is often easier to
18129 specify each of them by hand, since you then have full control over what
18130 is the proper order for these directories, which ones should be
18131 included.
18132
18133 However, in larger projects, which might involve hundreds of
18134 subdirectories, it might be more convenient to generate this list
18135 automatically.
18136
18137 The example below presents two methods. The first one, although less
18138 general, gives you more control over the list. It involves wildcard
18139 characters, that are automatically expanded by @command{make}. Its
18140 shortcoming is that you need to explicitly specify some of the
18141 organization of your project, such as for instance the directory tree
18142 depth, whether some directories are found in a separate tree, @enddots{}
18143
18144 The second method is the most general one. It requires an external
18145 program, called @command{find}, which is standard on all Unix systems. All
18146 the directories found under a given root directory will be added to the
18147 list.
18148
18149 @smallexample
18150 @iftex
18151 @leftskip=0cm
18152 @font@heightrm=cmr8
18153 @heightrm
18154 @end iftex
18155 # The examples below are based on the following directory hierarchy:
18156 # All the directories can contain any number of files
18157 # ROOT_DIRECTORY ->  a  ->  aa  ->  aaa
18158 #                       ->  ab
18159 #                       ->  ac
18160 #                ->  b  ->  ba  ->  baa
18161 #                       ->  bb
18162 #                       ->  bc
18163 # This Makefile creates a variable called DIRS, that can be reused any time
18164 # you need this list (see the other examples in this section)
18165
18166 # The root of your project's directory hierarchy
18167 ROOT_DIRECTORY=.
18168
18169 ####
18170 # First method: specify explicitly the list of directories
18171 # This allows you to specify any subset of all the directories you need.
18172 ####
18173
18174 DIRS := a/aa/ a/ab/ b/ba/
18175
18176 ####
18177 # Second method: use wildcards
18178 # Note that the argument(s) to wildcard below should end with a '/'.
18179 # Since wildcards also return file names, we have to filter them out
18180 # to avoid duplicate directory names.
18181 # We thus use make's @code{dir} and @code{sort} functions.
18182 # It sets DIRs to the following value (note that the directories aaa and baa
18183 # are not given, unless you change the arguments to wildcard).
18184 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
18185 ####
18186
18187 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
18188                     $@{ROOT_DIRECTORY@}/*/*/@}@}@}
18189
18190 ####
18191 # Third method: use an external program
18192 # This command is much faster if run on local disks, avoiding NFS slowdowns.
18193 # This is the most complete command: it sets DIRs to the following value:
18194 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
18195 ####
18196
18197 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
18198
18199 @end smallexample
18200
18201 @node Generating the Command Line Switches
18202 @section Generating the Command Line Switches
18203
18204 @noindent
18205 Once you have created the list of directories as explained in the
18206 previous section (@pxref{Automatically Creating a List of Directories}),
18207 you can easily generate the command line arguments to pass to gnatmake.
18208
18209 For the sake of completeness, this example assumes that the source path
18210 is not the same as the object path, and that you have two separate lists
18211 of directories.
18212
18213 @smallexample
18214 # see "Automatically creating a list of directories" to create
18215 # these variables
18216 SOURCE_DIRS=
18217 OBJECT_DIRS=
18218
18219 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
18220 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
18221
18222 all:
18223         gnatmake $@{GNATMAKE_SWITCHES@} main_unit
18224 @end smallexample
18225
18226 @node Overcoming Command Line Length Limits
18227 @section Overcoming Command Line Length Limits
18228
18229 @noindent
18230 One problem that might be encountered on big projects is that many
18231 operating systems limit the length of the command line. It is thus hard to give
18232 gnatmake the list of source and object directories.
18233
18234 This example shows how you can set up environment variables, which will
18235 make @command{gnatmake} behave exactly as if the directories had been
18236 specified on the command line, but have a much higher length limit (or
18237 even none on most systems).
18238
18239 It assumes that you have created a list of directories in your Makefile,
18240 using one of the methods presented in
18241 @ref{Automatically Creating a List of Directories}.
18242 For the sake of completeness, we assume that the object
18243 path (where the ALI files are found) is different from the sources patch.
18244
18245 Note a small trick in the Makefile below: for efficiency reasons, we
18246 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
18247 expanded immediately by @code{make}. This way we overcome the standard
18248 make behavior which is to expand the variables only when they are
18249 actually used.
18250
18251 On Windows, if you are using the standard Windows command shell, you must
18252 replace colons with semicolons in the assignments to these variables.
18253
18254 @smallexample
18255 @iftex
18256 @leftskip=0cm
18257 @font@heightrm=cmr8
18258 @heightrm
18259 @end iftex
18260 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
18261 # This is the same thing as putting the -I arguments on the command line.
18262 # (the equivalent of using -aI on the command line would be to define
18263 #  only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
18264 # You can of course have different values for these variables.
18265 #
18266 # Note also that we need to keep the previous values of these variables, since
18267 # they might have been set before running 'make' to specify where the GNAT
18268 # library is installed.
18269
18270 # see "Automatically creating a list of directories" to create these
18271 # variables
18272 SOURCE_DIRS=
18273 OBJECT_DIRS=
18274
18275 empty:=
18276 space:=$@{empty@} $@{empty@}
18277 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
18278 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
18279 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
18280 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
18281 export ADA_INCLUDE_PATH
18282 export ADA_OBJECTS_PATH
18283
18284 all:
18285         gnatmake main_unit
18286 @end smallexample
18287 @end ifclear
18288
18289 @node Memory Management Issues
18290 @chapter Memory Management Issues
18291
18292 @noindent
18293 This chapter describes some useful memory pools provided in the GNAT library
18294 and in particular the GNAT Debug Pool facility, which can be used to detect
18295 incorrect uses of access values (including ``dangling references'').
18296 @ifclear vms
18297 It also describes the @command{gnatmem} tool, which can be used to track down
18298 ``memory leaks''.
18299 @end ifclear
18300
18301 @menu
18302 * Some Useful Memory Pools::
18303 * The GNAT Debug Pool Facility::
18304 @ifclear vms
18305 * The gnatmem Tool::
18306 @end ifclear
18307 @end menu
18308
18309 @node Some Useful Memory Pools
18310 @section Some Useful Memory Pools
18311 @findex Memory Pool
18312 @cindex storage, pool
18313
18314 @noindent
18315 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18316 storage pool. Allocations use the standard system call @code{malloc} while
18317 deallocations use the standard system call @code{free}. No reclamation is
18318 performed when the pool goes out of scope. For performance reasons, the
18319 standard default Ada allocators/deallocators do not use any explicit storage
18320 pools but if they did, they could use this storage pool without any change in
18321 behavior. That is why this storage pool is used  when the user
18322 manages to make the default implicit allocator explicit as in this example:
18323 @smallexample @c ada
18324    type T1 is access Something;
18325     -- no Storage pool is defined for T2
18326    type T2 is access Something_Else;
18327    for T2'Storage_Pool use T1'Storage_Pool;
18328    -- the above is equivalent to
18329    for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18330 @end smallexample
18331
18332 @noindent
18333 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18334 pool. The allocation strategy is similar to @code{Pool_Local}'s
18335 except that the all
18336 storage allocated with this pool is reclaimed when the pool object goes out of
18337 scope. This pool provides a explicit mechanism similar to the implicit one
18338 provided by several Ada 83 compilers for allocations performed through a local
18339 access type and whose purpose was to reclaim memory when exiting the
18340 scope of a given local access. As an example, the following program does not
18341 leak memory even though it does not perform explicit deallocation:
18342
18343 @smallexample @c ada
18344 with System.Pool_Local;
18345 procedure Pooloc1 is
18346    procedure Internal is
18347       type A is access Integer;
18348       X : System.Pool_Local.Unbounded_Reclaim_Pool;
18349       for A'Storage_Pool use X;
18350       v : A;
18351    begin
18352       for I in  1 .. 50 loop
18353          v := new Integer;
18354       end loop;
18355    end Internal;
18356 begin
18357    for I in  1 .. 100 loop
18358       Internal;
18359    end loop;
18360 end Pooloc1;
18361 @end smallexample
18362
18363 @noindent
18364 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
18365 @code{Storage_Size} is specified for an access type.
18366 The whole storage for the pool is
18367 allocated at once, usually on the stack at the point where the access type is
18368 elaborated. It is automatically reclaimed when exiting the scope where the
18369 access type is defined. This package is not intended to be used directly by the
18370 user and it is implicitly used for each such declaration:
18371
18372 @smallexample @c ada
18373    type T1 is access Something;
18374    for T1'Storage_Size use 10_000;
18375 @end smallexample
18376
18377 @node The GNAT Debug Pool Facility
18378 @section The GNAT Debug Pool Facility
18379 @findex Debug Pool
18380 @cindex storage, pool, memory corruption
18381
18382 @noindent
18383 The use of unchecked deallocation and unchecked conversion can easily
18384 lead to incorrect memory references. The problems generated by such
18385 references are usually difficult to tackle because the symptoms can be
18386 very remote from the origin of the problem. In such cases, it is
18387 very helpful to detect the problem as early as possible. This is the
18388 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
18389
18390 In order to use the GNAT specific debugging pool, the user must
18391 associate a debug pool object with each of the access types that may be
18392 related to suspected memory problems. See Ada Reference Manual 13.11.
18393 @smallexample @c ada
18394 type Ptr is access Some_Type;
18395 Pool : GNAT.Debug_Pools.Debug_Pool;
18396 for Ptr'Storage_Pool use Pool;
18397 @end smallexample
18398
18399 @noindent
18400 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18401 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18402 allow the user to redefine allocation and deallocation strategies. They
18403 also provide a checkpoint for each dereference, through the use of
18404 the primitive operation @code{Dereference} which is implicitly called at
18405 each dereference of an access value.
18406
18407 Once an access type has been associated with a debug pool, operations on
18408 values of the type may raise four distinct exceptions,
18409 which correspond to four potential kinds of memory corruption:
18410 @itemize @bullet
18411 @item
18412 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18413 @item
18414 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18415 @item
18416 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18417 @item
18418 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18419 @end itemize
18420
18421 @noindent
18422 For types associated with a Debug_Pool, dynamic allocation is performed using
18423 the standard GNAT allocation routine. References to all allocated chunks of
18424 memory are kept in an internal dictionary. Several deallocation strategies are
18425 provided, whereupon the user can choose to release the memory to the system,
18426 keep it allocated for further invalid access checks, or fill it with an easily
18427 recognizable pattern for debug sessions. The memory pattern is the old IBM
18428 hexadecimal convention: @code{16#DEADBEEF#}.
18429
18430 See the documentation in the file g-debpoo.ads for more information on the
18431 various strategies.
18432
18433 Upon each dereference, a check is made that the access value denotes a
18434 properly allocated memory location. Here is a complete example of use of
18435 @code{Debug_Pools}, that includes typical instances of  memory corruption:
18436 @smallexample @c ada
18437 @iftex
18438 @leftskip=0cm
18439 @end iftex
18440 with Gnat.Io; use Gnat.Io;
18441 with Unchecked_Deallocation;
18442 with Unchecked_Conversion;
18443 with GNAT.Debug_Pools;
18444 with System.Storage_Elements;
18445 with Ada.Exceptions; use Ada.Exceptions;
18446 procedure Debug_Pool_Test is
18447
18448    type T is access Integer;
18449    type U is access all T;
18450
18451    P : GNAT.Debug_Pools.Debug_Pool;
18452    for T'Storage_Pool use P;
18453
18454    procedure Free is new Unchecked_Deallocation (Integer, T);
18455    function UC is new Unchecked_Conversion (U, T);
18456    A, B : aliased T;
18457
18458    procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
18459
18460 begin
18461    Info (P);
18462    A := new Integer;
18463    B := new Integer;
18464    B := A;
18465    Info (P);
18466    Free (A);
18467    begin
18468       Put_Line (Integer'Image(B.all));
18469    exception
18470       when E : others => Put_Line ("raised: " & Exception_Name (E));
18471    end;
18472    begin
18473       Free (B);
18474    exception
18475       when E : others => Put_Line ("raised: " & Exception_Name (E));
18476    end;
18477    B := UC(A'Access);
18478    begin
18479       Put_Line (Integer'Image(B.all));
18480    exception
18481       when E : others => Put_Line ("raised: " & Exception_Name (E));
18482    end;
18483    begin
18484       Free (B);
18485    exception
18486       when E : others => Put_Line ("raised: " & Exception_Name (E));
18487    end;
18488    Info (P);
18489 end Debug_Pool_Test;
18490 @end smallexample
18491
18492 @noindent
18493 The debug pool mechanism provides the following precise diagnostics on the
18494 execution of this erroneous program:
18495 @smallexample
18496 Debug Pool info:
18497   Total allocated bytes :  0
18498   Total deallocated bytes :  0
18499   Current Water Mark:  0
18500   High Water Mark:  0
18501
18502 Debug Pool info:
18503   Total allocated bytes :  8
18504   Total deallocated bytes :  0
18505   Current Water Mark:  8
18506   High Water Mark:  8
18507
18508 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18509 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18510 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18511 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18512 Debug Pool info:
18513   Total allocated bytes :  8
18514   Total deallocated bytes :  4
18515   Current Water Mark:  4
18516   High Water Mark:  8
18517 @end smallexample
18518
18519 @ifclear vms
18520 @node The gnatmem Tool
18521 @section The @command{gnatmem} Tool
18522 @findex gnatmem
18523
18524 @noindent
18525 The @code{gnatmem} utility monitors dynamic allocation and
18526 deallocation activity in a program, and displays information about
18527 incorrect deallocations and possible sources of memory leaks.
18528 It is designed to work in association with a static runtime library
18529 only and in this context provides three types of information:
18530 @itemize @bullet
18531 @item
18532 General information concerning memory management, such as the total
18533 number of allocations and deallocations, the amount of allocated
18534 memory and the high water mark, i.e.@: the largest amount of allocated
18535 memory in the course of program execution.
18536
18537 @item
18538 Backtraces for all incorrect deallocations, that is to say deallocations
18539 which do not correspond to a valid allocation.
18540
18541 @item
18542 Information on each allocation that is potentially the origin of a memory
18543 leak.
18544 @end itemize
18545
18546 @menu
18547 * Running gnatmem::
18548 * Switches for gnatmem::
18549 * Example of gnatmem Usage::
18550 @end menu
18551
18552 @node Running gnatmem
18553 @subsection Running @code{gnatmem}
18554
18555 @noindent
18556 @code{gnatmem} makes use of the output created by the special version of
18557 allocation and deallocation routines that record call information. This
18558 allows to obtain accurate dynamic memory usage history at a minimal cost to
18559 the execution speed. Note however, that @code{gnatmem} is not supported on
18560 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
18561 Solaris and Windows NT/2000/XP (x86).
18562
18563 @noindent
18564 The @code{gnatmem} command has the form
18565
18566 @smallexample
18567 @c    $ gnatmem @ovar{switches} user_program
18568 @c Expanding @ovar macro inline (explanation in macro def comments)
18569       $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
18570 @end smallexample
18571
18572 @noindent
18573 The program must have been linked with the instrumented version of the
18574 allocation and deallocation routines. This is done by linking with the
18575 @file{libgmem.a} library. For correct symbolic backtrace information,
18576 the user program should be compiled with debugging options
18577 (see @ref{Switches for gcc}). For example to build @file{my_program}:
18578
18579 @smallexample
18580 $ gnatmake -g my_program -largs -lgmem
18581 @end smallexample
18582
18583 @noindent
18584 As library @file{libgmem.a} contains an alternate body for package
18585 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
18586 when an executable is linked with library @file{libgmem.a}. It is then not
18587 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
18588
18589 @noindent
18590 When @file{my_program} is executed, the file @file{gmem.out} is produced.
18591 This file contains information about all allocations and deallocations
18592 performed by the program. It is produced by the instrumented allocations and
18593 deallocations routines and will be used by @code{gnatmem}.
18594
18595 In order to produce symbolic backtrace information for allocations and
18596 deallocations performed by the GNAT run-time library, you need to use a
18597 version of that library that has been compiled with the @option{-g} switch
18598 (see @ref{Rebuilding the GNAT Run-Time Library}).
18599
18600 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18601 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18602 @option{-i} switch, gnatmem will assume that this file can be found in the
18603 current directory. For example, after you have executed @file{my_program},
18604 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18605
18606 @smallexample
18607 $ gnatmem my_program
18608 @end smallexample
18609
18610 @noindent
18611 This will produce the output with the following format:
18612
18613 *************** debut cc
18614 @smallexample
18615 $ gnatmem my_program
18616
18617 Global information
18618 ------------------
18619    Total number of allocations        :  45
18620    Total number of deallocations      :   6
18621    Final Water Mark (non freed mem)   :  11.29 Kilobytes
18622    High Water Mark                    :  11.40 Kilobytes
18623
18624 .
18625 .
18626 .
18627 Allocation Root # 2
18628 -------------------
18629  Number of non freed allocations    :  11
18630  Final Water Mark (non freed mem)   :   1.16 Kilobytes
18631  High Water Mark                    :   1.27 Kilobytes
18632  Backtrace                          :
18633    my_program.adb:23 my_program.alloc
18634 .
18635 .
18636 .
18637 @end smallexample
18638
18639 The first block of output gives general information. In this case, the
18640 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18641 Unchecked_Deallocation routine occurred.
18642
18643 @noindent
18644 Subsequent paragraphs display  information on all allocation roots.
18645 An allocation root is a specific point in the execution of the program
18646 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18647 construct. This root is represented by an execution backtrace (or subprogram
18648 call stack). By default the backtrace depth for allocations roots is 1, so
18649 that a root corresponds exactly to a source location. The backtrace can
18650 be made deeper, to make the root more specific.
18651
18652 @node Switches for gnatmem
18653 @subsection Switches for @code{gnatmem}
18654
18655 @noindent
18656 @code{gnatmem} recognizes the following switches:
18657
18658 @table @option
18659
18660 @item -q
18661 @cindex @option{-q} (@code{gnatmem})
18662 Quiet. Gives the minimum output needed to identify the origin of the
18663 memory leaks. Omits statistical information.
18664
18665 @item @var{N}
18666 @cindex @var{N} (@code{gnatmem})
18667 N is an integer literal (usually between 1 and 10) which controls the
18668 depth of the backtraces defining allocation root. The default value for
18669 N is 1. The deeper the backtrace, the more precise the localization of
18670 the root. Note that the total number of roots can depend on this
18671 parameter. This parameter must be specified @emph{before} the name of the
18672 executable to be analyzed, to avoid ambiguity.
18673
18674 @item -b n
18675 @cindex @option{-b} (@code{gnatmem})
18676 This switch has the same effect as just depth parameter.
18677
18678 @item -i @var{file}
18679 @cindex @option{-i} (@code{gnatmem})
18680 Do the @code{gnatmem} processing starting from @file{file}, rather than
18681 @file{gmem.out} in the current directory.
18682
18683 @item -m n
18684 @cindex @option{-m} (@code{gnatmem})
18685 This switch causes @code{gnatmem} to mask the allocation roots that have less
18686 than n leaks. The default value is 1. Specifying the value of 0 will allow to
18687 examine even the roots that didn't result in leaks.
18688
18689 @item -s order
18690 @cindex @option{-s} (@code{gnatmem})
18691 This switch causes @code{gnatmem} to sort the allocation roots according to the
18692 specified order of sort criteria, each identified by a single letter. The
18693 currently supported criteria are @code{n, h, w} standing respectively for
18694 number of unfreed allocations, high watermark, and final watermark
18695 corresponding to a specific root. The default order is @code{nwh}.
18696
18697 @end table
18698
18699 @node Example of gnatmem Usage
18700 @subsection Example of @code{gnatmem} Usage
18701
18702 @noindent
18703 The following example shows the use of @code{gnatmem}
18704 on a simple memory-leaking program.
18705 Suppose that we have the following Ada program:
18706
18707 @smallexample @c ada
18708 @group
18709 @cartouche
18710 with Unchecked_Deallocation;
18711 procedure Test_Gm is
18712
18713    type T is array (1..1000) of Integer;
18714    type Ptr is access T;
18715    procedure Free is new Unchecked_Deallocation (T, Ptr);
18716    A : Ptr;
18717
18718    procedure My_Alloc is
18719    begin
18720       A := new T;
18721    end My_Alloc;
18722
18723    procedure My_DeAlloc is
18724       B : Ptr := A;
18725    begin
18726       Free (B);
18727    end My_DeAlloc;
18728
18729 begin
18730    My_Alloc;
18731    for I in 1 .. 5 loop
18732       for J in I .. 5 loop
18733          My_Alloc;
18734       end loop;
18735       My_Dealloc;
18736    end loop;
18737 end;
18738 @end cartouche
18739 @end group
18740 @end smallexample
18741
18742 @noindent
18743 The program needs to be compiled with debugging option and linked with
18744 @code{gmem} library:
18745
18746 @smallexample
18747 $ gnatmake -g test_gm -largs -lgmem
18748 @end smallexample
18749
18750 @noindent
18751 Then we execute the program as usual:
18752
18753 @smallexample
18754 $ test_gm
18755 @end smallexample
18756
18757 @noindent
18758 Then @code{gnatmem} is invoked simply with
18759 @smallexample
18760 $ gnatmem test_gm
18761 @end smallexample
18762
18763 @noindent
18764 which produces the following output (result may vary on different platforms):
18765
18766 @smallexample
18767 Global information
18768 ------------------
18769    Total number of allocations        :  18
18770    Total number of deallocations      :   5
18771    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18772    High Water Mark                    :  56.90 Kilobytes
18773
18774 Allocation Root # 1
18775 -------------------
18776  Number of non freed allocations    :  11
18777  Final Water Mark (non freed mem)   :  42.97 Kilobytes
18778  High Water Mark                    :  46.88 Kilobytes
18779  Backtrace                          :
18780    test_gm.adb:11 test_gm.my_alloc
18781
18782 Allocation Root # 2
18783 -------------------
18784  Number of non freed allocations    :   1
18785  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18786  High Water Mark                    :  10.02 Kilobytes
18787  Backtrace                          :
18788    s-secsta.adb:81 system.secondary_stack.ss_init
18789
18790 Allocation Root # 3
18791 -------------------
18792  Number of non freed allocations    :   1
18793  Final Water Mark (non freed mem)   :  12 Bytes
18794  High Water Mark                    :  12 Bytes
18795  Backtrace                          :
18796    s-secsta.adb:181 system.secondary_stack.ss_init
18797 @end smallexample
18798
18799 @noindent
18800 Note that the GNAT run time contains itself a certain number of
18801 allocations that have no  corresponding deallocation,
18802 as shown here for root #2 and root
18803 #3. This is a normal behavior when the number of non-freed allocations
18804 is one, it allocates dynamic data structures that the run time needs for
18805 the complete lifetime of the program. Note also that there is only one
18806 allocation root in the user program with a single line back trace:
18807 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18808 program shows that 'My_Alloc' is called at 2 different points in the
18809 source (line 21 and line 24). If those two allocation roots need to be
18810 distinguished, the backtrace depth parameter can be used:
18811
18812 @smallexample
18813 $ gnatmem 3 test_gm
18814 @end smallexample
18815
18816 @noindent
18817 which will give the following output:
18818
18819 @smallexample
18820 Global information
18821 ------------------
18822    Total number of allocations        :  18
18823    Total number of deallocations      :   5
18824    Final Water Mark (non freed mem)   :  53.00 Kilobytes
18825    High Water Mark                    :  56.90 Kilobytes
18826
18827 Allocation Root # 1
18828 -------------------
18829  Number of non freed allocations    :  10
18830  Final Water Mark (non freed mem)   :  39.06 Kilobytes
18831  High Water Mark                    :  42.97 Kilobytes
18832  Backtrace                          :
18833    test_gm.adb:11 test_gm.my_alloc
18834    test_gm.adb:24 test_gm
18835    b_test_gm.c:52 main
18836
18837 Allocation Root # 2
18838 -------------------
18839  Number of non freed allocations    :   1
18840  Final Water Mark (non freed mem)   :  10.02 Kilobytes
18841  High Water Mark                    :  10.02 Kilobytes
18842  Backtrace                          :
18843    s-secsta.adb:81  system.secondary_stack.ss_init
18844    s-secsta.adb:283 <system__secondary_stack___elabb>
18845    b_test_gm.c:33   adainit
18846
18847 Allocation Root # 3
18848 -------------------
18849  Number of non freed allocations    :   1
18850  Final Water Mark (non freed mem)   :   3.91 Kilobytes
18851  High Water Mark                    :   3.91 Kilobytes
18852  Backtrace                          :
18853    test_gm.adb:11 test_gm.my_alloc
18854    test_gm.adb:21 test_gm
18855    b_test_gm.c:52 main
18856
18857 Allocation Root # 4
18858 -------------------
18859  Number of non freed allocations    :   1
18860  Final Water Mark (non freed mem)   :  12 Bytes
18861  High Water Mark                    :  12 Bytes
18862  Backtrace                          :
18863    s-secsta.adb:181 system.secondary_stack.ss_init
18864    s-secsta.adb:283 <system__secondary_stack___elabb>
18865    b_test_gm.c:33   adainit
18866 @end smallexample
18867
18868 @noindent
18869 The allocation root #1 of the first example has been split in 2 roots #1
18870 and #3 thanks to the more precise associated backtrace.
18871
18872 @end ifclear
18873
18874 @node Stack Related Facilities
18875 @chapter Stack Related Facilities
18876
18877 @noindent
18878 This chapter describes some useful tools associated with stack
18879 checking and analysis. In
18880 particular, it deals with dynamic and static stack usage measurements.
18881
18882 @menu
18883 * Stack Overflow Checking::
18884 * Static Stack Usage Analysis::
18885 * Dynamic Stack Usage Analysis::
18886 @end menu
18887
18888 @node Stack Overflow Checking
18889 @section Stack Overflow Checking
18890 @cindex Stack Overflow Checking
18891 @cindex -fstack-check
18892
18893 @noindent
18894 For most operating systems, @command{gcc} does not perform stack overflow
18895 checking by default. This means that if the main environment task or
18896 some other task exceeds the available stack space, then unpredictable
18897 behavior will occur. Most native systems offer some level of protection by
18898 adding a guard page at the end of each task stack. This mechanism is usually
18899 not enough for dealing properly with stack overflow situations because
18900 a large local variable could ``jump'' above the guard page.
18901 Furthermore, when the
18902 guard page is hit, there may not be any space left on the stack for executing
18903 the exception propagation code. Enabling stack checking avoids
18904 such situations.
18905
18906 To activate stack checking, compile all units with the gcc option
18907 @option{-fstack-check}. For example:
18908
18909 @smallexample
18910 gcc -c -fstack-check package1.adb
18911 @end smallexample
18912
18913 @noindent
18914 Units compiled with this option will generate extra instructions to check
18915 that any use of the stack (for procedure calls or for declaring local
18916 variables in declare blocks) does not exceed the available stack space.
18917 If the space is exceeded, then a @code{Storage_Error} exception is raised.
18918
18919 For declared tasks, the stack size is controlled by the size
18920 given in an applicable @code{Storage_Size} pragma or by the value specified
18921 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
18922 the default size as defined in the GNAT runtime otherwise.
18923
18924 For the environment task, the stack size depends on
18925 system defaults and is unknown to the compiler. Stack checking
18926 may still work correctly if a fixed
18927 size stack is allocated, but this cannot be guaranteed.
18928 @ifclear vms
18929 To ensure that a clean exception is signalled for stack
18930 overflow, set the environment variable
18931 @env{GNAT_STACK_LIMIT} to indicate the maximum
18932 stack area that can be used, as in:
18933 @cindex GNAT_STACK_LIMIT
18934
18935 @smallexample
18936 SET GNAT_STACK_LIMIT 1600
18937 @end smallexample
18938
18939 @noindent
18940 The limit is given in kilobytes, so the above declaration would
18941 set the stack limit of the environment task to 1.6 megabytes.
18942 Note that the only purpose of this usage is to limit the amount
18943 of stack used by the environment task. If it is necessary to
18944 increase the amount of stack for the environment task, then this
18945 is an operating systems issue, and must be addressed with the
18946 appropriate operating systems commands.
18947 @end ifclear
18948 @ifset vms
18949 To have a fixed size stack in the environment task, the stack must be put
18950 in the P0 address space and its size specified.  Use these switches to
18951 create a p0 image:
18952
18953 @smallexample
18954 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
18955 @end smallexample
18956
18957 @noindent
18958 The quotes are required to keep case.  The number after @samp{STACK=} is the
18959 size of the environmental task stack in pagelets (512 bytes).  In this example
18960 the stack size is about 2 megabytes.
18961
18962 @noindent
18963 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
18964 be placed in P0 space.  Refer to @cite{HP OpenVMS Linker Utility Manual} for
18965 more details about the @option{/p0image} qualifier and the @option{stack}
18966 option.
18967
18968 @noindent
18969 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
18970 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
18971 stack in kilobytes.  For example:
18972
18973 @smallexample
18974 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
18975 @end smallexample
18976 @end ifset
18977
18978 @node Static Stack Usage Analysis
18979 @section Static Stack Usage Analysis
18980 @cindex Static Stack Usage Analysis
18981 @cindex -fstack-usage
18982
18983 @noindent
18984 A unit compiled with @option{-fstack-usage} will generate an extra file
18985 that specifies
18986 the maximum amount of stack used, on a per-function basis.
18987 The file has the same
18988 basename as the target object file with a @file{.su} extension.
18989 Each line of this file is made up of three fields:
18990
18991 @itemize
18992 @item
18993 The name of the function.
18994 @item
18995 A number of bytes.
18996 @item
18997 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
18998 @end itemize
18999
19000 The second field corresponds to the size of the known part of the function
19001 frame.
19002
19003 The qualifier @code{static} means that the function frame size
19004 is purely static.
19005 It usually means that all local variables have a static size.
19006 In this case, the second field is a reliable measure of the function stack
19007 utilization.
19008
19009 The qualifier @code{dynamic} means that the function frame size is not static.
19010 It happens mainly when some local variables have a dynamic size. When this
19011 qualifier appears alone, the second field is not a reliable measure
19012 of the function stack analysis. When it is qualified with  @code{bounded}, it
19013 means that the second field is a reliable maximum of the function stack
19014 utilization.
19015
19016 A unit compiled with @option{-Wstack-usage} will issue a warning for each
19017 subprogram whose stack usage might be larger than the specified amount of
19018 bytes.  The wording is in keeping with the qualifier documented above.
19019
19020 @node Dynamic Stack Usage Analysis
19021 @section Dynamic Stack Usage Analysis
19022
19023 @noindent
19024 It is possible to measure the maximum amount of stack used by a task, by
19025 adding a switch to @command{gnatbind}, as:
19026
19027 @smallexample
19028 $ gnatbind -u0 file
19029 @end smallexample
19030
19031 @noindent
19032 With this option, at each task termination, its stack usage is  output on
19033 @file{stderr}.
19034 It is not always convenient to output the stack usage when the program
19035 is still running. Hence, it is possible to delay this output until program
19036 termination. for a given number of tasks specified as the argument of the
19037 @option{-u} option. For instance:
19038
19039 @smallexample
19040 $ gnatbind -u100 file
19041 @end smallexample
19042
19043 @noindent
19044 will buffer the stack usage information of the first 100 tasks to terminate and
19045 output this info at program termination. Results are displayed in four
19046 columns:
19047
19048 @noindent
19049 Index | Task Name | Stack Size | Stack Usage
19050
19051 @noindent
19052 where:
19053
19054 @table @emph
19055 @item Index
19056 is a number associated with each task.
19057
19058 @item Task Name
19059 is the name of the task analyzed.
19060
19061 @item Stack Size
19062 is the maximum size for the stack.
19063
19064 @item Stack Usage
19065 is the measure done by the stack analyzer. In order to prevent overflow, the stack
19066 is not entirely analyzed, and it's not possible to know exactly how
19067 much has actually been used.
19068
19069 @end table
19070
19071 @noindent
19072 The environment task stack, e.g., the stack that contains the main unit, is
19073 only processed when the environment variable GNAT_STACK_LIMIT is set.
19074
19075 @noindent
19076 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
19077 stack usage reports at run-time. See its body for the details.
19078
19079 @c *********************************
19080 @c *            GNATCHECK          *
19081 @c *********************************
19082 @node Verifying Properties with gnatcheck
19083 @chapter Verifying Properties with @command{gnatcheck}
19084 @findex gnatcheck
19085 @cindex @command{gnatcheck}
19086
19087 @noindent
19088 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
19089 of Ada source files according to a given set of semantic rules.
19090 @cindex ASIS
19091
19092 In order to check compliance with a given rule, @command{gnatcheck} has to
19093 semantically analyze the Ada sources.
19094 Therefore, checks can only be performed on
19095 legal Ada units. Moreover, when a unit depends semantically upon units located
19096 outside the current directory, the source search path has to be provided when
19097 calling @command{gnatcheck}, either through a specified project file or
19098 through @command{gnatcheck} switches.
19099
19100 For full details, refer to @cite{GNATcheck Reference Manual} document.
19101
19102
19103 @c *********************************
19104 @node Creating Sample Bodies with gnatstub
19105 @chapter Creating Sample Bodies with @command{gnatstub}
19106 @findex gnatstub
19107
19108 @noindent
19109 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
19110 for library unit declarations.
19111
19112 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
19113 driver (see @ref{The GNAT Driver and Project Files}).
19114
19115 To create a body stub, @command{gnatstub} has to compile the library
19116 unit declaration. Therefore, bodies can be created only for legal
19117 library units. Moreover, if a library unit depends semantically upon
19118 units located outside the current directory, you have to provide
19119 the source search path when calling @command{gnatstub}, see the description
19120 of @command{gnatstub} switches below.
19121
19122 By default, all the program unit body stubs generated by @code{gnatstub}
19123 raise the predefined @code{Program_Error} exception, which will catch
19124 accidental calls of generated stubs. This behavior can be changed with
19125 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
19126
19127 @menu
19128 * Running gnatstub::
19129 * Switches for gnatstub::
19130 @end menu
19131
19132 @node Running gnatstub
19133 @section Running @command{gnatstub}
19134
19135 @noindent
19136 @command{gnatstub} has a command-line interface of the form:
19137
19138 @smallexample
19139 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
19140 @c Expanding @ovar macro inline (explanation in macro def comments)
19141 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19142 @end smallexample
19143
19144 @noindent
19145 where
19146 @table @var
19147 @item filename
19148 is the name of the source file that contains a library unit declaration
19149 for which a body must be created. The file name may contain the path
19150 information.
19151 The file name does not have to follow the GNAT file name conventions. If the
19152 name
19153 does not follow GNAT file naming conventions, the name of the body file must
19154 be provided
19155 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
19156 If the file name follows the GNAT file naming
19157 conventions and the name of the body file is not provided,
19158 @command{gnatstub}
19159 creates the name
19160 of the body file from the argument file name by replacing the @file{.ads}
19161 suffix
19162 with the @file{.adb} suffix.
19163
19164 @item directory
19165 indicates the directory in which the body stub is to be placed (the default
19166 is the
19167 current directory)
19168
19169 @item @samp{@var{gcc_switches}} is a list of switches for
19170 @command{gcc}. They will be passed on to all compiler invocations made by
19171 @command{gnatstub} to generate the ASIS trees. Here you can provide
19172 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19173 use the @option{-gnatec} switch to set the configuration file,
19174 use the @option{-gnat05} switch if sources should be compiled in
19175 Ada 2005 mode etc.
19176
19177 @item switches
19178 is an optional sequence of switches as described in the next section
19179 @end table
19180
19181 @node Switches for gnatstub
19182 @section Switches for @command{gnatstub}
19183
19184 @table @option
19185 @c !sort!
19186
19187 @item --version
19188 @cindex @option{--version} @command{gnatstub}
19189 Display Copyright and version, then exit disregarding all other options.
19190
19191 @item --help
19192 @cindex @option{--help} @command{gnatstub}
19193 Display usage, then exit disregarding all other options.
19194
19195 @item ^-f^/FULL^
19196 @cindex @option{^-f^/FULL^} (@command{gnatstub})
19197 If the destination directory already contains a file with the name of the
19198 body file
19199 for the argument spec file, replace it with the generated body stub.
19200
19201 @item ^-hs^/HEADER=SPEC^
19202 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
19203 Put the comment header (i.e., all the comments preceding the
19204 compilation unit) from the source of the library unit declaration
19205 into the body stub.
19206
19207 @item ^-hg^/HEADER=GENERAL^
19208 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
19209 Put a sample comment header into the body stub.
19210
19211 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
19212 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
19213 Use the content of the file as the comment header for a generated body stub.
19214
19215 @ifclear vms
19216 @item -IDIR
19217 @cindex @option{-IDIR} (@command{gnatstub})
19218 @itemx -I-
19219 @cindex @option{-I-} (@command{gnatstub})
19220 @end ifclear
19221 @ifset vms
19222 @item /NOCURRENT_DIRECTORY
19223 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
19224 @end ifset
19225 ^These switches have ^This switch has^ the same meaning as in calls to
19226 @command{gcc}.
19227 ^They define ^It defines ^ the source search path in the call to
19228 @command{gcc} issued
19229 by @command{gnatstub} to compile an argument source file.
19230
19231 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
19232 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
19233 This switch has the same meaning as in calls to @command{gcc}.
19234 It defines the additional configuration file to be passed to the call to
19235 @command{gcc} issued
19236 by @command{gnatstub} to compile an argument source file.
19237
19238 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
19239 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
19240 (@var{n} is a non-negative integer). Set the maximum line length that is
19241 allowed in a source file. The default is 79. The maximum value that can be
19242 specified is 32767. Note that in the special case of configuration
19243 pragma files, the maximum is always 32767 regardless of whether or
19244 not this switch appears.
19245
19246 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
19247 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
19248 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
19249 the generated body sample to @var{n}.
19250 The default indentation is 3.
19251
19252 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
19253 @cindex @option{^-gnatyo^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
19254 Order local bodies alphabetically. (By default local bodies are ordered
19255 in the same way as the corresponding local specs in the argument spec file.)
19256
19257 @item ^-i^/INDENTATION=^@var{n}
19258 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
19259 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
19260
19261 @item ^-k^/TREE_FILE=SAVE^
19262 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
19263 Do not remove the tree file (i.e., the snapshot of the compiler internal
19264 structures used by @command{gnatstub}) after creating the body stub.
19265
19266 @item ^-l^/LINE_LENGTH=^@var{n}
19267 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
19268 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
19269
19270 @item ^--no-exception^/NO_EXCEPTION^
19271 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
19272 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
19273 This is not always possible for function stubs.
19274
19275 @item ^--no-local-header^/NO_LOCAL_HEADER^
19276 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
19277 Do not place local comment header with unit name before body stub for a
19278 unit.
19279
19280 @item ^-o ^/BODY=^@var{body-name}
19281 @cindex @option{^-o^/BODY^} (@command{gnatstub})
19282 Body file name.  This should be set if the argument file name does not
19283 follow
19284 the GNAT file naming
19285 conventions. If this switch is omitted the default name for the body will be
19286 obtained
19287 from the argument file name according to the GNAT file naming conventions.
19288
19289 @item ^-q^/QUIET^
19290 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
19291 Quiet mode: do not generate a confirmation when a body is
19292 successfully created, and do not generate a message when a body is not
19293 required for an
19294 argument unit.
19295
19296 @item ^-r^/TREE_FILE=REUSE^
19297 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
19298 Reuse the tree file (if it exists) instead of creating it.  Instead of
19299 creating the tree file for the library unit declaration, @command{gnatstub}
19300 tries to find it in the current directory and use it for creating
19301 a body. If the tree file is not found, no body is created. This option
19302 also implies @option{^-k^/SAVE^}, whether or not
19303 the latter is set explicitly.
19304
19305 @item ^-t^/TREE_FILE=OVERWRITE^
19306 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
19307 Overwrite the existing tree file.  If the current directory already
19308 contains the file which, according to the GNAT file naming rules should
19309 be considered as a tree file for the argument source file,
19310 @command{gnatstub}
19311 will refuse to create the tree file needed to create a sample body
19312 unless this option is set.
19313
19314 @item ^-v^/VERBOSE^
19315 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
19316 Verbose mode: generate version information.
19317
19318 @end table
19319
19320 @c *********************************
19321 @node Creating Unit Tests with gnattest
19322 @chapter Creating Unit Tests with @command{gnattest}
19323 @findex gnattest
19324
19325 @noindent
19326 @command{gnattest} is an ASIS-based utility that creates unit-test skeletons
19327 as well as a test driver infrastructure (harness). @command{gnattest} creates
19328 a skeleton for each visible subprogram in the packages under consideration when
19329 they do not exist already.
19330
19331 In order to process source files from a project, @command{gnattest} has to
19332 semantically analyze the sources. Therefore, test skeletons can only be
19333 generated for legal Ada units. If a unit is dependent on other units,
19334 those units should be among the source files of the project or of other projects
19335 imported by this one.
19336
19337 Generated skeletons and harnesses are based on the AUnit testing framework.
19338 AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit
19339 for Java or CppUnit for C++. While it is advised that gnattest users read
19340 the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest.
19341 For correct operation of @command{gnattest}, AUnit should be installed and
19342 aunit.gpr must be on the project path. This happens automatically when Aunit
19343 is installed at its default location.
19344 @menu
19345 * Running gnattest::
19346 * Switches for gnattest::
19347 * Project Attributes for gnattest::
19348 * Simple Example::
19349 * Setting Up and Tearing Down the Testing Environment::
19350 * Regenerating Tests::
19351 * Default Test Behavior::
19352 * Testing Primitive Operations of Tagged Types::
19353 * Testing Inheritance::
19354 * Tagged Types Substitutability Testing::
19355 * Testing with Contracts::
19356 * Additional Tests::
19357 @ifclear vms
19358 * Support for other platforms/run-times::
19359 @end ifclear
19360 * Current Limitations::
19361 @end menu
19362
19363 @node Running gnattest
19364 @section Running @command{gnattest}
19365
19366 @noindent
19367 @command{gnattest} has a command-line interface of the form
19368
19369 @smallexample
19370 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
19371 @c Expanding @ovar macro inline (explanation in macro def comments)
19372 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19373 @end smallexample
19374
19375 @noindent
19376 where
19377 @table @var
19378
19379 @item -Pprojname
19380 specifies the project defining the location of source files. When no
19381 file names are provided on the command line, all sources in the project
19382 are used as input. This switch is required.
19383
19384 @item filename
19385 is the name of the source file containing the library unit package declaration
19386 for which a test package will be created. The file name may be given with a
19387 path.
19388
19389 @item @samp{@var{gcc_switches}}
19390 is a list of switches for
19391 @command{gcc}. These switches will be passed on to all compiler invocations
19392 made by @command{gnattest} to generate a set of ASIS trees. Here you can provide
19393 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19394 use the @option{-gnatec} switch to set the configuration file,
19395 use the @option{-gnat05} switch if sources should be compiled in
19396 Ada 2005 mode, etc.
19397
19398 @item switches
19399 is an optional sequence of switches as described in the next section.
19400
19401 @end table
19402
19403 @command{gnattest} results can be found in two different places.
19404
19405 @itemize @bullet
19406 @item automatic harness:
19407 the harness code, which is located by default in "gnattest/harness" directory
19408 that is created in the object directory of corresponding project file. All of
19409 this code is generated completely automatically and can be destroyed and
19410 regenerated at will. It is not recommended to modify this code manually, since
19411 it could easily be overridden by mistake. The entry point in the harness code is
19412 the project file named @command{test_driver.gpr}. Tests can be compiled and run
19413 using a command such as:
19414
19415 @smallexample
19416 gnatmake -P<harness-dir>/test_driver
19417 test_runner
19418 @end smallexample
19419
19420 Note that you might need to specify the necessary values of scenario variables
19421 when you are not using the AUnit defaults.
19422
19423 @item actual unit test skeletons:
19424 a test skeleton for each visible subprogram is created in a separate file, if it
19425 doesn't exist already. By default, those separate test files are located in a
19426 "gnattest/tests" directory that is created in the object directory of
19427 corresponding project file. For example, if a source file my_unit.ads in
19428 directory src contains a visible subprogram Proc, then the corresponding unit
19429 test will be found in file src/tests/my_unit-test_data-tests-proc_<code>.adb.
19430 <code> is a signature encoding used to differentiate test names in case of
19431 overloading.
19432
19433 Note that if the project already has both my_unit.ads and my_unit-test_data.ads,
19434 this will cause a name conflict with the generated test package.
19435 @end itemize
19436
19437 @node Switches for gnattest
19438 @section Switches for @command{gnattest}
19439
19440 @table @option
19441 @c !sort!
19442
19443 @item --harness-only
19444 @cindex @option{--harness-only} (@command{gnattest})
19445 When this option is given, @command{gnattest} creates a harness for all
19446 sources, treating them as test packages.
19447
19448 @item --additional-tests=@var{projname}
19449 @cindex @option{--additional-tests} (@command{gnattest})
19450 Sources described in @var{projname} are considered potential additional
19451 manual tests to be added to the test suite.
19452
19453 @item -r
19454 @cindex @option{-r} (@command{gnattest})
19455 Recursively consider all sources from all projects.
19456
19457 @item -X@var{name=value}
19458 @cindex @option{-X} (@command{gnattest})
19459 Indicate that external variable @var{name} has the value @var{value}.
19460
19461 @item -q
19462 @cindex @option{-q} (@command{gnattest})
19463 Suppresses noncritical output messages.
19464
19465 @item -v
19466 @cindex @option{-v} (@command{gnattest})
19467 Verbose mode: generates version information.
19468
19469 @item --validate-type-extensions
19470 @cindex @option{--validate-type-extensions} (@command{gnattest})
19471 Enables substitution check: run all tests from all parents in order
19472 to check substitutability.
19473
19474 @item --skeleton-default=@var{val}
19475 @cindex @option{--skeleton-default} (@command{gnattest})
19476 Specifies the default behavior of generated skeletons. @var{val} can be either
19477 "fail" or "pass", "fail" being the default.
19478
19479 @item --tests-root=@var{dirname}
19480 @cindex @option{--tests-root} (@command{gnattest})
19481 The directory hierarchy of tested sources is recreated in the @var{dirname}
19482 directory, and test packages are placed in corresponding directories.
19483 If the @var{dirname} is a relative path, it is considered relative to the object
19484 directory of the project file. When all sources from all projects are taken
19485 recursively from all projects, directory hierarchies of tested sources are
19486 recreated for each project in their object directories and test packages are
19487 placed accordingly.
19488
19489 @item --subdir=@var{dirname}
19490 @cindex @option{--subdir} (@command{gnattest})
19491 Test packages are placed in subdirectories.
19492
19493 @item --tests-dir=@var{dirname}
19494 @cindex @option{--tests-dir} (@command{gnattest})
19495 All test packages are placed in the @var{dirname} directory.
19496 If the @var{dirname} is a relative path, it is considered relative to the object
19497 directory of the project file. When all sources from all projects are taken
19498 recursively from all projects, @var{dirname} directories are created for each
19499 project in their object directories and test packages are placed accordingly.
19500
19501 @item --harness-dir=@var{dirname}
19502 @cindex @option{--harness-dir} (@command{gnattest})
19503 specifies the directory that will hold the harness packages and project file
19504 for the test driver. If the @var{dirname} is a relative path, it is considered
19505 relative to the object directory of the project file.
19506
19507 @item --separates
19508 @cindex @option{--separates} (@command{gnattest})
19509 Bodies of all test routines are generated as separates. Note that this mode is
19510 kept for compatibility reasons only and it is not advised to use it due to
19511 possible problems with hash in names of test skeletons when using an
19512 inconsistent casing. Separate test skeletons can be incorporated to monolith
19513 test package with improved hash being used by using @option{--transition}
19514 switch.
19515
19516
19517 @item --transition
19518 @cindex @option{--transition} (@command{gnattest})
19519 This allows transition from separate test routines to monolith test packages.
19520 All matching test routines are overwritten with contents of corresponding
19521 separates. Note that if separate test routines had any manually added with
19522 clauses they will be moved to the test package body as is and have to be moved
19523 by hand.
19524
19525 @end table
19526
19527 @option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are
19528 mutually exclusive.
19529
19530 @node Project Attributes for gnattest
19531 @section Project Attributes for @command{gnattest}
19532
19533 @noindent
19534
19535 Most of the command-line options can also be passed to the tool by adding
19536 special attributes to the project file. Those attributes should be put in
19537 package gnattest. Here is the list of attributes:
19538
19539 @itemize @bullet
19540
19541 @item Tests_Root
19542 is used to select the same output mode as with the --tests-root option.
19543 This attribute cannot be used together with Subdir or Tests_Dir.
19544
19545 @item Subdir
19546 is used to select the same output mode as with the --subdir option.
19547 This attribute cannot be used together with Tests_Root or Tests_Dir.
19548
19549 @item Tests_Dir
19550 is used to select the same output mode as with the --tests-dir option.
19551 This attribute cannot be used together with Subdir or Tests_Root.
19552
19553 @item Harness_Dir
19554 is used to specify the directory in which to place harness packages and project
19555 file for the test driver, otherwise specified by --harness-dir.
19556
19557 @item Additional_Tests
19558 is used to specify the project file, otherwise given by
19559 --additional-tests switch.
19560
19561 @item Skeletons_Default
19562 is used to specify the default behaviour of test skeletons, otherwise
19563 specified by --skeleton-default option. The value of this attribute
19564 should be either "pass" or "fail".
19565
19566 @end itemize
19567
19568 Each of those attributes can be overridden from the command line if needed.
19569 Other @command{gnattest} switches can also be passed via the project
19570 file as an attribute list called GNATtest_Switches.
19571
19572 @node Simple Example
19573 @section Simple Example
19574
19575 @noindent
19576
19577 Let's take a very simple example using the first @command{gnattest} example
19578 located in:
19579
19580 @smallexample
19581 <install_prefix>/share/examples/gnattest/simple
19582 @end smallexample
19583
19584 This project contains a simple package containing one subprogram. By running gnattest:
19585
19586 @smallexample
19587 $ gnattest --harness-dir=driver -Psimple.gpr
19588 @end smallexample
19589
19590 a test driver is created in directory "driver". It can be compiled and run:
19591
19592 @smallexample
19593 $ cd obj/driver
19594 $ gnatmake -Ptest_driver
19595 $ test_runner
19596 @end smallexample
19597
19598 One failed test with diagnosis "test not implemented" is reported.
19599 Since no special output option was specified, the test package Simple.Tests
19600 is located in:
19601
19602 @smallexample
19603 <install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
19604 @end smallexample
19605
19606 For each package containing visible subprograms, a child test package is
19607 generated. It contains one test routine per tested subprogram. Each
19608 declaration of a test subprogram has a comment specifying which tested
19609 subprogram it corresponds to. Bodies of test routines are placed in test package
19610 bodies and are surrounded by special comment sections. Those comment sections
19611 should not be removed or modified in order for gnattest to be able to regenerate
19612 test packages and keep already written tests in place.
19613 The test routine Test_Inc_5eaee3 located at simple-test_data-tests.adb contains
19614 a single statement: a call to procedure Assert. It has two arguments:
19615 the Boolean expression we want to check and the diagnosis message to display if
19616 the condition is false.
19617
19618 That is where actual testing code should be written after a proper setup.
19619 An actual check can be performed by replacing the Assert call with:
19620
19621 @smallexample @c ada
19622 Assert (Inc (1) = 2, "wrong incrementation");
19623 @end smallexample
19624
19625 After recompiling and running the test driver, one successfully passed test
19626 is reported.
19627
19628 @node Setting Up and Tearing Down the Testing Environment
19629 @section Setting Up and Tearing Down the Testing Environment
19630
19631 @noindent
19632
19633 Besides test routines themselves, each test package has a parent package
19634 Test_Data that has two procedures: Set_Up and Tear_Down. This package is never
19635 overwritten by the tool. Set_Up is called before each test routine of the
19636 package and Tear_Down is called after each test routine. Those two procedures
19637 can be used to perform necessary initialization and finalization,
19638 memory allocation, etc. Test type declared in Test_Data package is parent type
19639 for the test type of test package and can have user-defined components whose
19640 values can be set by Set_Up routine and used in test routines afterwards.
19641
19642 @node Regenerating Tests
19643 @section Regenerating Tests
19644
19645 @noindent
19646
19647 Bodies of test routines and test_data packages are never overridden after they
19648 have been created once. As long as the name of the subprogram, full expanded Ada
19649 names, and the order of its parameters is the same, and comment sections are
19650 intact the old test routine will fit in its place and no test skeleton will be
19651 generated for the subprogram.
19652
19653 This can be demonstrated with the previous example. By uncommenting declaration
19654 and body of function Dec in simple.ads and simple.adb, running
19655 @command{gnattest} on the project, and then running the test driver:
19656
19657 @smallexample
19658 gnattest --harness-dir=driver -Psimple.gpr
19659 cd obj/driver
19660 gnatmake -Ptest_driver
19661 test_runner
19662 @end smallexample
19663
19664 the old test is not replaced with a stub, nor is it lost, but a new test
19665 skeleton is created for function Dec.
19666
19667 The only way of regenerating tests skeletons is to remove the previously created
19668 tests together with corresponding comment sections.
19669
19670 @node Default Test Behavior
19671 @section Default Test Behavior
19672
19673 @noindent
19674
19675 The generated test driver can treat unimplemented tests in two ways:
19676 either count them all as failed (this is useful to see which tests are still
19677 left to implement) or as passed (to sort out unimplemented ones from those
19678 actually failing).
19679
19680 The test driver accepts a switch to specify this behavior:
19681 --skeleton-default=val, where val is either "pass" or "fail" (exactly as for
19682 @command{gnattest}).
19683
19684 The default behavior of the test driver is set with the same switch
19685 as passed to gnattest when generating the test driver.
19686
19687 Passing it to the driver generated on the first example:
19688
19689 @smallexample
19690 test_runner --skeleton-default=pass
19691 @end smallexample
19692
19693 makes both tests pass, even the unimplemented one.
19694
19695 @node Testing Primitive Operations of Tagged Types
19696 @section Testing Primitive Operations of Tagged Types
19697
19698 @noindent
19699
19700 Creation of test skeletons for primitive operations of tagged types entails
19701 a number of features. Test routines for all primitives of a given tagged type
19702 are placed in a separate child package named according to the tagged type. For
19703 example, if you have tagged type T in package P, all tests for primitives
19704 of T will be in P.T_Test_Data.T_Tests.
19705
19706 Consider running gnattest on the second example (note: actual tests for this
19707 example already exist, so there's no need to worry if the tool reports that
19708 no new stubs were generated):
19709
19710 @smallexample
19711 cd <install_prefix>/share/examples/gnattest/tagged_rec
19712 gnattest --harness-dir=driver -Ptagged_rec.gpr
19713 @end smallexample
19714
19715 Taking a closer look at the test type declared in the test package
19716 Speed1.Controller_Test_Data is necessary. It is declared in:
19717
19718 @smallexample
19719 <install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
19720 @end smallexample
19721
19722 Test types are direct or indirect descendants of
19723 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
19724 subprograms, the user doesn't need to be concerned with them. However,
19725 when generating test packages for primitive operations, there are some things
19726 the user needs to know.
19727
19728 Type Test_Controller has components that allow assignment of various
19729 derivations of type Controller. And if you look at the specification of
19730 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
19731 actually derives from Test_Controller rather than AUnit type Test_Fixture.
19732 Thus, test types mirror the hierarchy of tested types.
19733
19734 The Set_Up procedure of Test_Data package corresponding to a test package
19735 of primitive operations of type T assigns to Fixture a reference to an
19736 object of that exact type T. Notice, however, that if the tagged type has
19737 discriminants, the Set_Up only has a commented template for setting
19738 up the fixture, since filling the discriminant with actual value is up
19739 to the user.
19740
19741 The knowledge of the structure of test types allows additional testing
19742 without additional effort. Those possibilities are described below.
19743
19744 @node Testing Inheritance
19745 @section Testing Inheritance
19746
19747 @noindent
19748
19749 Since the test type hierarchy mimics the hierarchy of tested types, the
19750 inheritance of tests takes place. An example of such inheritance can be
19751 seen by running the test driver generated for the second example. As previously
19752 mentioned, actual tests are already written for this example.
19753
19754 @smallexample
19755 cd obj/driver
19756 gnatmake -Ptest_driver
19757 test_runner
19758 @end smallexample
19759
19760 There are 6 passed tests while there are only 5 testable subprograms. The test
19761 routine for function Speed has been inherited and run against objects of the
19762 derived type.
19763
19764 @node Tagged Types Substitutability Testing
19765 @section Tagged Types Substitutability Testing
19766
19767 @noindent
19768
19769 Tagged Types Substitutability Testing is a way of verifying the global type
19770 consistency by testing. Global type consistency is a principle stating that if
19771 S is a subtype of T (in Ada, S is a derived type of tagged type T),
19772 then objects of type T may be replaced with objects of type S (that is,
19773 objects of type S may be substituted for objects of type T), without
19774 altering any of the desirable properties of the program. When the properties
19775 of the program are expressed in the form of subprogram preconditions and
19776 postconditions (let's call them pre and post), the principle is formulated as
19777 relations between the pre and post of primitive operations and the pre and post
19778 of their derived operations. The pre of a derived operation should not be
19779 stronger than the original pre, and the post of the derived operation should
19780 not be weaker than the original post. Those relations ensure that verifying if
19781 a dispatching call is safe can be done just by using the pre and post of the
19782 root operation.
19783
19784 Verifying global type consistency by testing consists of running all the unit
19785 tests associated with the primitives of a given tagged type with objects of its
19786 derived types.
19787
19788 In the example used in the previous section, there was clearly a violation of
19789 type consistency. The overriding primitive Adjust_Speed in package Speed2
19790 removes the functionality of the overridden primitive and thus doesn't respect
19791 the consistency principle.
19792 Gnattest has a special option to run overridden parent tests against objects
19793 of the type which have overriding primitives:
19794
19795 @smallexample
19796 gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr
19797 cd obj/driver
19798 gnatmake -Ptest_driver
19799 test_runner
19800 @end smallexample
19801
19802 While all the tests pass by themselves, the parent test for Adjust_Speed fails
19803 against objects of the derived type.
19804
19805 Non-overridden tests are already inherited for derived test types, so the
19806 --validate-type-extensions enables the application of overriden tests to objects
19807 of derived types.
19808
19809 @node Testing with Contracts
19810 @section Testing with Contracts
19811
19812 @noindent
19813
19814 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case,
19815 as well as corresponding aspects.
19816 Test routines are generated, one per each Test_Case associated with a tested
19817 subprogram. Those test routines have special wrappers for tested functions
19818 that have composition of pre- and postcondition of the subprogram with
19819 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
19820 either count for Nominal mode or do not count for Robustness mode).
19821
19822 The third example demonstrates how this works:
19823
19824 @smallexample
19825 cd <install_prefix>/share/examples/gnattest/contracts
19826 gnattest --harness-dir=driver -Pcontracts.gpr
19827 @end smallexample
19828
19829 Putting actual checks within the range of the contract does not cause any
19830 error reports. For example, for the test routine which corresponds to
19831 test case 1:
19832
19833 @smallexample @c ada
19834 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
19835 @end smallexample
19836
19837 and for the test routine corresponding to test case 2:
19838
19839 @smallexample @c ada
19840 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
19841 @end smallexample
19842
19843 are acceptable:
19844
19845 @smallexample
19846 cd obj/driver
19847 gnatmake -Ptest_driver
19848 test_runner
19849 @end smallexample
19850
19851 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
19852 a precondition violation for test case one. Also, by using any otherwise
19853 correct but positive pair of numbers in the second test routine, you can also
19854 get a precondition violation. Postconditions are checked and reported
19855 the same way.
19856
19857 @node Additional Tests
19858 @section Additional Tests
19859
19860 @noindent
19861 @command{gnattest} can add user-written tests to the main suite of the test
19862 driver. @command{gnattest} traverses the given packages and searches for test
19863 routines. All procedures with a single in out parameter of a type which is
19864 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
19865 specifications are added to the suites and are then executed by the test driver.
19866 (Set_Up and Tear_Down are filtered out.)
19867
19868 An example illustrates two ways of creating test harnesses for user-written
19869 tests. Directory additional_tests contains an AUnit-based test driver written
19870 by hand.
19871
19872 @smallexample
19873 <install_prefix>/share/examples/gnattest/additional_tests/
19874 @end smallexample
19875
19876 To create a test driver for already-written tests, use the --harness-only
19877 option:
19878
19879 @smallexample
19880 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
19881   --harness-only
19882 gnatmake -Pharness_only/test_driver.gpr
19883 harness_only/test_runner
19884 @end smallexample
19885
19886 Additional tests can also be executed together with generated tests:
19887
19888 @smallexample
19889 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
19890   --harness-dir=mixing
19891 gnatmake -Pmixing/test_driver.gpr
19892 mixing/test_runner
19893 @end smallexample
19894
19895 @ifclear vms
19896 @node Support for other platforms/run-times
19897 @section Support for other platforms/run-times
19898
19899 @noindent
19900 @command{gnattest} can be used to generate the test harness for platforms
19901 and run-time libraries others than the default native target with the
19902 default full run-time. For example, when using a limited run-time library
19903 such as Zero FootPrint (ZFP), a simplified harness is generated.
19904
19905 Two variables are used to tell the underlying AUnit framework how to generate
19906 the test harness: @code{PLATFORM}, which identifies the target, and
19907 @code{RUNTIME}, used to determine the run-time library for which the harness
19908 is generated. Corresponding prefix should also be used when calling
19909 @command{gnattest} for non-native targets. For example, the following options
19910 are used to generate the AUnit test harness for a PowerPC ELF target using
19911 the ZFP run-time library:
19912
19913 @smallexample
19914 powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
19915 @end smallexample
19916 @end ifclear
19917
19918 @node Current Limitations
19919 @section Current Limitations
19920
19921 @noindent
19922
19923 The tool currently does not support following features:
19924
19925 @itemize @bullet
19926 @item generic tests for generic packages and package instantiations
19927 @item tests for protected subprograms and entries
19928
19929 @end itemize
19930
19931 @c *********************************
19932 @node Performing Dimensionality Analysis in GNAT
19933 @chapter Performing Dimensionality Analysis in GNAT
19934 @noindent
19935 The GNAT compiler now supports dimensionality checking. The user can
19936 specify physical units for objects, and the compiler will verify that uses
19937 of these objects are compatible with their dimensions, in a fashion that is
19938 familiar to engineering practice. The dimensions of algebraic expressions
19939 (including powers with static exponents) are computed from their consistuents.
19940
19941 This feature depends on Ada 2012 aspect specifications, and is available from
19942 version 7.0.1 of GNAT onwards. The GNAT-specific aspect Dimension_System allows
19943 you to define a system of units; the aspect Dimension then allows the user
19944 to declare dimensioned quantities within a given system.
19945
19946 The major advantage of this model is that it does not require the declaration of
19947 multiple operators for all possible combinations of types: it is only necessary
19948 to use the proper subtypes in object declarations.
19949
19950 The simplest way to impose dimensionality checking on a computation is to make
19951 use of the package System.Dim.Mks, which is part of the GNAT library. This
19952 package defines a floating-point type MKS_Type, for which a sequence of
19953 dimension names are specified, together with their conventional abbreviations.
19954 The following should be read together with the full specification of the
19955 package, in file s-dimmks.ads.
19956
19957 @smallexample @c ada
19958    type Mks_Type is new Long_Long_Float
19959      with
19960       Dimension_System => (
19961         (Unit_Name => Meter,    Unit_Symbol => 'm',   Dim_Symbol => 'L'),
19962         (Unit_Name => Kilogram, Unit_Symbol => "kg",  Dim_Symbol => 'M'),
19963         (Unit_Name => Second,   Unit_Symbol => 's',   Dim_Symbol => 'T'),
19964         (Unit_Name => Ampere,   Unit_Symbol => 'A',   Dim_Symbol => 'I'),
19965         (Unit_Name => Kelvin,   Unit_Symbol => 'K',   Dim_Symbol => "Theta"),
19966         (Unit_Name => Mole,     Unit_Symbol => "mol", Dim_Symbol => 'N'),
19967         (Unit_Name => Candela,  Unit_Symbol => "cd",  Dim_Symbol => 'J'));
19968 @end smallexample
19969
19970 @noindent
19971 The package then defines a series of subtypes that correspond to these
19972 conventional units. For example:
19973 @smallexample @c ada
19974    subtype Length is Mks_Type
19975      with
19976       Dimension => (Symbol => 'm', Meter  => 1, others => 0);
19977 @end smallexample
19978 @noindent
19979 and similarly for Mass, Time, Electric_Current, Thermodynamic_Temperature,
19980 Amount_Of_Substance, and Luminous_Intensity (the standard set of units of
19981 the SI system).
19982
19983 The package also defines conventional names for values of each unit, for
19984 example:
19985
19986 @smallexample @c ada
19987    m   : constant Length           := 1.0;
19988    kg  : constant Mass             := 1.0;
19989    s   : constant Time             := 1.0;
19990    A   : constant Electric_Current := 1.0;
19991 @end smallexample
19992
19993 @noindent
19994 as well as useful multiples of these units:
19995
19996 @smallexample @c ada
19997    cm  : constant Length := 1.0E-02;
19998    g   : constant Mass   := 1.0E-03;
19999    min : constant Time   := 60.0;
20000    day : constant TIme   := 60.0 * 24.0 * min;
20001   ...
20002 @end smallexample
20003
20004 @noindent
20005 Using this package, you can then define a derived unit by
20006 providing the aspect that
20007 specifies its dimensions within the MKS system, as well as the string to
20008 be used for output of a value of that unit:
20009
20010 @smallexample @c ada
20011   subtype Acceleration is Mks_Type
20012     with Dimension => ("m/sec^^^2",
20013                        Meter => 1,
20014                        Second => -2,
20015                        others => 0);
20016 @end smallexample
20017
20018 @noindent
20019 Here is a complete example of use:
20020
20021 @smallexample @c ada
20022 with System.Dim.MKS; use System.Dim.Mks;
20023 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
20024 with Text_IO; use Text_IO;
20025 procedure Free_Fall is
20026   subtype Acceleration is Mks_Type
20027     with Dimension => ("m/sec^^^2", 1, 0, -2, others => 0);
20028   G : constant acceleration := 9.81 * m / (s ** 2);
20029   T : Time := 10.0*s;
20030   Distance : Length;
20031 begin
20032   Put ("Gravitational constant: ");
20033   Put (G, Aft => 2, Exp => 0); Put_Line ("");
20034   Distance := 0.5 * G * T ** 2;
20035   Put ("distance travelled in 10 seconds of free fall ");
20036   Put (Distance, Aft => 2, Exp => 0);
20037   Put_Line ("");
20038 end Free_Fall;
20039 @end smallexample
20040
20041 @noindent
20042 Execution of this program yields:
20043 @smallexample
20044 Gravitational constant:  9.81 m/sec^^^2
20045 distance travelled in 10 seconds of free fall 490.50 m
20046 @end smallexample
20047
20048 @noindent
20049 However, incorrect assignments such as:
20050
20051 @smallexample @c ada
20052    Distance := 5.0;
20053    Distance := 5.0 * kg:
20054 @end smallexample
20055
20056 @noindent
20057 are rejected with the following diagnoses:
20058
20059 @smallexample
20060    Distance := 5.0;
20061       >>> dimensions mismatch in assignment
20062       >>> left-hand side has dimension [L]
20063       >>> right-hand side is dimensionless
20064
20065    Distance := 5.0 * kg:
20066       >>> dimensions mismatch in assignment
20067       >>> left-hand side has dimension [L]
20068       >>> right-hand side has dimension [M]
20069 @end smallexample
20070
20071 @noindent
20072 The dimensions of an expression are properly displayed, even if there is
20073 no explicit subtype for it. If we add to the program:
20074
20075 @smallexample @c ada
20076       Put ("Final velocity: ");
20077       Put (G * T, Aft =>2, Exp =>0);
20078       Put_Line ("");
20079 @end smallexample
20080
20081 @noindent
20082 then the output includes:
20083 @smallexample
20084      Final velocity: 98.10 m.s**(-1)
20085 @end smallexample
20086
20087 @c *********************************
20088 @node Generating Ada Bindings for C and C++ headers
20089 @chapter Generating Ada Bindings for C and C++ headers
20090 @findex binding
20091
20092 @noindent
20093 GNAT now comes with a binding generator for C and C++ headers which is
20094 intended to do 95% of the tedious work of generating Ada specs from C
20095 or C++ header files.
20096
20097 Note that this capability is not intended to generate 100% correct Ada specs,
20098 and will is some cases require manual adjustments, although it can often
20099 be used out of the box in practice.
20100
20101 Some of the known limitations include:
20102
20103 @itemize @bullet
20104 @item only very simple character constant macros are translated into Ada
20105 constants. Function macros (macros with arguments) are partially translated
20106 as comments, to be completed manually if needed.
20107 @item some extensions (e.g. vector types) are not supported
20108 @item pointers to pointers or complex structures are mapped to System.Address
20109 @item identifiers with identical name (except casing) will generate compilation
20110       errors (e.g. @code{shm_get} vs @code{SHM_GET}).
20111 @end itemize
20112
20113 The code generated is using the Ada 2005 syntax, which makes it
20114 easier to interface with other languages than previous versions of Ada.
20115
20116 @menu
20117 * Running the binding generator::
20118 * Generating bindings for C++ headers::
20119 * Switches::
20120 @end menu
20121
20122 @node Running the binding generator
20123 @section Running the binding generator
20124
20125 @noindent
20126 The binding generator is part of the @command{gcc} compiler and can be
20127 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
20128 spec files for the header files specified on the command line, and all
20129 header files needed by these files transitively. For example:
20130
20131 @smallexample
20132 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
20133 $ gcc -c -gnat05 *.ads
20134 @end smallexample
20135
20136 will generate, under GNU/Linux, the following files: @file{time_h.ads},
20137 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
20138 correspond to the files @file{/usr/include/time.h},
20139 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
20140 mode these Ada specs.
20141
20142 The @code{-C} switch tells @command{gcc} to extract comments from headers,
20143 and will attempt to generate corresponding Ada comments.
20144
20145 If you want to generate a single Ada file and not the transitive closure, you
20146 can use instead the @option{-fdump-ada-spec-slim} switch.
20147
20148 You can optionally specify a parent unit, of which all generated units will
20149 be children, using @code{-fada-spec-parent=}@var{unit}.
20150
20151 Note that we recommend when possible to use the @command{g++} driver to
20152 generate bindings, even for most C headers, since this will in general
20153 generate better Ada specs. For generating bindings for C++ headers, it is
20154 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
20155 is equivalent in this case. If @command{g++} cannot work on your C headers
20156 because of incompatibilities between C and C++, then you can fallback to
20157 @command{gcc} instead.
20158
20159 For an example of better bindings generated from the C++ front-end,
20160 the name of the parameters (when available) are actually ignored by the C
20161 front-end. Consider the following C header:
20162
20163 @smallexample
20164 extern void foo (int variable);
20165 @end smallexample
20166
20167 with the C front-end, @code{variable} is ignored, and the above is handled as:
20168
20169 @smallexample
20170 extern void foo (int);
20171 @end smallexample
20172
20173 generating a generic:
20174
20175 @smallexample
20176 procedure foo (param1 : int);
20177 @end smallexample
20178
20179 with the C++ front-end, the name is available, and we generate:
20180
20181 @smallexample
20182 procedure foo (variable : int);
20183 @end smallexample
20184
20185 In some cases, the generated bindings will be more complete or more meaningful
20186 when defining some macros, which you can do via the @option{-D} switch. This
20187 is for example the case with @file{Xlib.h} under GNU/Linux:
20188
20189 @smallexample
20190 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
20191 @end smallexample
20192
20193 The above will generate more complete bindings than a straight call without
20194 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
20195
20196 In other cases, it is not possible to parse a header file in a stand-alone
20197 manner, because other include files need to be included first. In this
20198 case, the solution is to create a small header file including the needed
20199 @code{#include} and possible @code{#define} directives. For example, to
20200 generate Ada bindings for @file{readline/readline.h}, you need to first
20201 include @file{stdio.h}, so you can create a file with the following two
20202 lines in e.g. @file{readline1.h}:
20203
20204 @smallexample
20205 #include <stdio.h>
20206 #include <readline/readline.h>
20207 @end smallexample
20208
20209 and then generate Ada bindings from this file:
20210
20211 @smallexample
20212 $ g++ -c -fdump-ada-spec readline1.h
20213 @end smallexample
20214
20215 @node Generating bindings for C++ headers
20216 @section Generating bindings for C++ headers
20217
20218 @noindent
20219 Generating bindings for C++ headers is done using the same options, always
20220 with the @command{g++} compiler.
20221
20222 In this mode, C++ classes will be mapped to Ada tagged types, constructors
20223 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
20224 multiple inheritance of abstract classes will be mapped to Ada interfaces
20225 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
20226 information on interfacing to C++).
20227
20228 For example, given the following C++ header file:
20229
20230 @smallexample
20231 @group
20232 @cartouche
20233 class Carnivore @{
20234 public:
20235    virtual int Number_Of_Teeth () = 0;
20236 @};
20237
20238 class Domestic @{
20239 public:
20240    virtual void Set_Owner (char* Name) = 0;
20241 @};
20242
20243 class Animal @{
20244 public:
20245   int Age_Count;
20246   virtual void Set_Age (int New_Age);
20247 @};
20248
20249 class Dog : Animal, Carnivore, Domestic @{
20250  public:
20251   int  Tooth_Count;
20252   char *Owner;
20253
20254   virtual int  Number_Of_Teeth ();
20255   virtual void Set_Owner (char* Name);
20256
20257   Dog();
20258 @};
20259 @end cartouche
20260 @end group
20261 @end smallexample
20262
20263 The corresponding Ada code is generated:
20264
20265 @smallexample @c ada
20266 @group
20267 @cartouche
20268   package Class_Carnivore is
20269     type Carnivore is limited interface;
20270     pragma Import (CPP, Carnivore);
20271
20272     function Number_Of_Teeth (this : access Carnivore) return int is abstract;
20273   end;
20274   use Class_Carnivore;
20275
20276   package Class_Domestic is
20277     type Domestic is limited interface;
20278     pragma Import (CPP, Domestic);
20279
20280     procedure Set_Owner
20281       (this : access Domestic;
20282        Name : Interfaces.C.Strings.chars_ptr) is abstract;
20283   end;
20284   use Class_Domestic;
20285
20286   package Class_Animal is
20287     type Animal is tagged limited record
20288       Age_Count : aliased int;
20289     end record;
20290     pragma Import (CPP, Animal);
20291
20292     procedure Set_Age (this : access Animal; New_Age : int);
20293     pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
20294   end;
20295   use Class_Animal;
20296
20297   package Class_Dog is
20298     type Dog is new Animal and Carnivore and Domestic with record
20299       Tooth_Count : aliased int;
20300       Owner : Interfaces.C.Strings.chars_ptr;
20301     end record;
20302     pragma Import (CPP, Dog);
20303
20304     function Number_Of_Teeth (this : access Dog) return int;
20305     pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
20306
20307     procedure Set_Owner
20308       (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
20309     pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
20310
20311     function New_Dog return Dog;
20312     pragma CPP_Constructor (New_Dog);
20313     pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
20314   end;
20315   use Class_Dog;
20316 @end cartouche
20317 @end group
20318 @end smallexample
20319
20320 @node Switches
20321 @section Switches
20322
20323 @table @option
20324 @item -fdump-ada-spec
20325 @cindex @option{-fdump-ada-spec} (@command{gcc})
20326 Generate Ada spec files for the given header files transitively (including
20327 all header files that these headers depend upon).
20328
20329 @item -fdump-ada-spec-slim
20330 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
20331 Generate Ada spec files for the header files specified on the command line
20332 only.
20333
20334 @item -fada-spec-parent=@var{unit}
20335 @cindex -fada-spec-parent (@command{gcc})
20336 Specifies that all files generated by @option{-fdump-ada-spec*} are
20337 to be child units of the specified parent unit.
20338
20339 @item -C
20340 @cindex @option{-C} (@command{gcc})
20341 Extract comments from headers and generate Ada comments in the Ada spec files.
20342 @end table
20343
20344 @node Other Utility Programs
20345 @chapter Other Utility Programs
20346
20347 @noindent
20348 This chapter discusses some other utility programs available in the Ada
20349 environment.
20350
20351 @menu
20352 * Using Other Utility Programs with GNAT::
20353 * The External Symbol Naming Scheme of GNAT::
20354 * Converting Ada Files to html with gnathtml::
20355 * Installing gnathtml::
20356 @ifset vms
20357 * LSE::
20358 * Profiling::
20359 @end ifset
20360 @end menu
20361
20362 @node Using Other Utility Programs with GNAT
20363 @section Using Other Utility Programs with GNAT
20364
20365 @noindent
20366 The object files generated by GNAT are in standard system format and in
20367 particular the debugging information uses this format. This means
20368 programs generated by GNAT can be used with existing utilities that
20369 depend on these formats.
20370
20371 @ifclear vms
20372 In general, any utility program that works with C will also often work with
20373 Ada programs generated by GNAT. This includes software utilities such as
20374 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
20375 as Purify.
20376 @end ifclear
20377
20378 @node The External Symbol Naming Scheme of GNAT
20379 @section The External Symbol Naming Scheme of GNAT
20380
20381 @noindent
20382 In order to interpret the output from GNAT, when using tools that are
20383 originally intended for use with other languages, it is useful to
20384 understand the conventions used to generate link names from the Ada
20385 entity names.
20386
20387 All link names are in all lowercase letters. With the exception of library
20388 procedure names, the mechanism used is simply to use the full expanded
20389 Ada name with dots replaced by double underscores. For example, suppose
20390 we have the following package spec:
20391
20392 @smallexample @c ada
20393 @group
20394 @cartouche
20395 package QRS is
20396    MN : Integer;
20397 end QRS;
20398 @end cartouche
20399 @end group
20400 @end smallexample
20401
20402 @noindent
20403 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
20404 the corresponding link name is @code{qrs__mn}.
20405 @findex Export
20406 Of course if a @code{pragma Export} is used this may be overridden:
20407
20408 @smallexample @c ada
20409 @group
20410 @cartouche
20411 package Exports is
20412    Var1 : Integer;
20413    pragma Export (Var1, C, External_Name => "var1_name");
20414    Var2 : Integer;
20415    pragma Export (Var2, C, Link_Name => "var2_link_name");
20416 end Exports;
20417 @end cartouche
20418 @end group
20419 @end smallexample
20420
20421 @noindent
20422 In this case, the link name for @var{Var1} is whatever link name the
20423 C compiler would assign for the C function @var{var1_name}. This typically
20424 would be either @var{var1_name} or @var{_var1_name}, depending on operating
20425 system conventions, but other possibilities exist. The link name for
20426 @var{Var2} is @var{var2_link_name}, and this is not operating system
20427 dependent.
20428
20429 @findex _main
20430 One exception occurs for library level procedures. A potential ambiguity
20431 arises between the required name @code{_main} for the C main program,
20432 and the name we would otherwise assign to an Ada library level procedure
20433 called @code{Main} (which might well not be the main program).
20434
20435 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
20436 names. So if we have a library level procedure such as
20437
20438 @smallexample @c ada
20439 @group
20440 @cartouche
20441 procedure Hello (S : String);
20442 @end cartouche
20443 @end group
20444 @end smallexample
20445
20446 @noindent
20447 the external name of this procedure will be @var{_ada_hello}.
20448
20449
20450 @node Converting Ada Files to html with gnathtml
20451 @section Converting Ada Files to HTML with @code{gnathtml}
20452
20453 @noindent
20454 This @code{Perl} script allows Ada source files to be browsed using
20455 standard Web browsers. For installation procedure, see the section
20456 @xref{Installing gnathtml}.
20457
20458 Ada reserved keywords are highlighted in a bold font and Ada comments in
20459 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
20460 switch to suppress the generation of cross-referencing information, user
20461 defined variables and types will appear in a different color; you will
20462 be able to click on any identifier and go to its declaration.
20463
20464 The command line is as follow:
20465 @smallexample
20466 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
20467 @c Expanding @ovar macro inline (explanation in macro def comments)
20468 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
20469 @end smallexample
20470
20471 @noindent
20472 You can pass it as many Ada files as you want. @code{gnathtml} will generate
20473 an html file for every ada file, and a global file called @file{index.htm}.
20474 This file is an index of every identifier defined in the files.
20475
20476 The available ^switches^options^ are the following ones:
20477
20478 @table @option
20479 @item -83
20480 @cindex @option{-83} (@code{gnathtml})
20481 Only the Ada 83 subset of keywords will be highlighted.
20482
20483 @item -cc @var{color}
20484 @cindex @option{-cc} (@code{gnathtml})
20485 This option allows you to change the color used for comments. The default
20486 value is green. The color argument can be any name accepted by html.
20487
20488 @item -d
20489 @cindex @option{-d} (@code{gnathtml})
20490 If the Ada files depend on some other files (for instance through
20491 @code{with} clauses, the latter files will also be converted to html.
20492 Only the files in the user project will be converted to html, not the files
20493 in the run-time library itself.
20494
20495 @item -D
20496 @cindex @option{-D} (@code{gnathtml})
20497 This command is the same as @option{-d} above, but @command{gnathtml} will
20498 also look for files in the run-time library, and generate html files for them.
20499
20500 @item -ext @var{extension}
20501 @cindex @option{-ext} (@code{gnathtml})
20502 This option allows you to change the extension of the generated HTML files.
20503 If you do not specify an extension, it will default to @file{htm}.
20504
20505 @item -f
20506 @cindex @option{-f} (@code{gnathtml})
20507 By default, gnathtml will generate html links only for global entities
20508 ('with'ed units, global variables and types,@dots{}).  If you specify
20509 @option{-f} on the command line, then links will be generated for local
20510 entities too.
20511
20512 @item -l @var{number}
20513 @cindex @option{-l} (@code{gnathtml})
20514 If this ^switch^option^ is provided and @var{number} is not 0, then
20515 @code{gnathtml} will number the html files every @var{number} line.
20516
20517 @item -I @var{dir}
20518 @cindex @option{-I} (@code{gnathtml})
20519 Specify a directory to search for library files (@file{.ALI} files) and
20520 source files. You can provide several -I switches on the command line,
20521 and the directories will be parsed in the order of the command line.
20522
20523 @item -o @var{dir}
20524 @cindex @option{-o} (@code{gnathtml})
20525 Specify the output directory for html files. By default, gnathtml will
20526 saved the generated html files in a subdirectory named @file{html/}.
20527
20528 @item -p @var{file}
20529 @cindex @option{-p} (@code{gnathtml})
20530 If you are using Emacs and the most recent Emacs Ada mode, which provides
20531 a full Integrated Development Environment for compiling, checking,
20532 running and debugging applications, you may use @file{.gpr} files
20533 to give the directories where Emacs can find sources and object files.
20534
20535 Using this ^switch^option^, you can tell gnathtml to use these files.
20536 This allows you to get an html version of your application, even if it
20537 is spread over multiple directories.
20538
20539 @item -sc @var{color}
20540 @cindex @option{-sc} (@code{gnathtml})
20541 This ^switch^option^ allows you to change the color used for symbol
20542 definitions.
20543 The default value is red. The color argument can be any name accepted by html.
20544
20545 @item -t @var{file}
20546 @cindex @option{-t} (@code{gnathtml})
20547 This ^switch^option^ provides the name of a file. This file contains a list of
20548 file names to be converted, and the effect is exactly as though they had
20549 appeared explicitly on the command line. This
20550 is the recommended way to work around the command line length limit on some
20551 systems.
20552
20553 @end table
20554
20555 @node Installing gnathtml
20556 @section Installing @code{gnathtml}
20557
20558 @noindent
20559 @code{Perl} needs to be installed on your machine to run this script.
20560 @code{Perl} is freely available for almost every architecture and
20561 Operating System via the Internet.
20562
20563 On Unix systems, you  may want to modify  the  first line of  the script
20564 @code{gnathtml},  to explicitly  tell  the Operating  system  where Perl
20565 is. The syntax of this line is:
20566 @smallexample
20567 #!full_path_name_to_perl
20568 @end smallexample
20569
20570 @noindent
20571 Alternatively, you may run the script using the following command line:
20572
20573 @smallexample
20574 @c $ perl gnathtml.pl @ovar{switches} @var{files}
20575 @c Expanding @ovar macro inline (explanation in macro def comments)
20576 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
20577 @end smallexample
20578
20579 @ifset vms
20580 @node LSE
20581 @section LSE
20582 @findex LSE
20583
20584 @noindent
20585 The GNAT distribution provides an Ada 95 template for the HP Language
20586 Sensitive Editor (LSE), a component of DECset. In order to
20587 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
20588
20589 @node Profiling
20590 @section Profiling
20591 @findex PCA
20592
20593 @noindent
20594 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
20595 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
20596 the collection phase with the /DEBUG qualifier.
20597
20598 @smallexample
20599 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
20600 $ DEFINE LIB$DEBUG PCA$COLLECTOR
20601 $ RUN/DEBUG <PROGRAM_NAME>
20602 @end smallexample
20603 @noindent
20604 @end ifset
20605
20606 @ifclear vms
20607 @c ******************************
20608 @node Code Coverage and Profiling
20609 @chapter Code Coverage and Profiling
20610 @cindex Code Coverage
20611 @cindex Profiling
20612
20613 @noindent
20614 This chapter describes how to use @code{gcov} - coverage testing tool - and
20615 @code{gprof} - profiler tool - on your Ada programs.
20616
20617 @menu
20618 * Code Coverage of Ada Programs with gcov::
20619 * Profiling an Ada Program with gprof::
20620 @end menu
20621
20622 @node Code Coverage of Ada Programs with gcov
20623 @section Code Coverage of Ada Programs with gcov
20624 @cindex gcov
20625 @cindex -fprofile-arcs
20626 @cindex -ftest-coverage
20627 @cindex -coverage
20628 @cindex Code Coverage
20629
20630 @noindent
20631 @code{gcov} is a test coverage program: it analyzes the execution of a given
20632 program on selected tests, to help you determine the portions of the program
20633 that are still untested.
20634
20635 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
20636 User's Guide. You can refer to this documentation for a more complete
20637 description.
20638
20639 This chapter provides a quick startup guide, and
20640 details some Gnat-specific features.
20641
20642 @menu
20643 * Quick startup guide::
20644 * Gnat specifics::
20645 @end menu
20646
20647 @node Quick startup guide
20648 @subsection Quick startup guide
20649
20650 In order to perform coverage analysis of a program using @code{gcov}, 3
20651 steps are needed:
20652
20653 @itemize @bullet
20654 @item
20655 Code instrumentation during the compilation process
20656 @item
20657 Execution of the instrumented program
20658 @item
20659 Execution of the @code{gcov} tool to generate the result.
20660 @end itemize
20661
20662 The code instrumentation needed by gcov is created at the object level:
20663 The source code is not modified in any way, because the instrumentation code is
20664 inserted by gcc during the compilation process. To compile your code with code
20665 coverage activated, you need to recompile your whole project using the
20666 switches
20667 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
20668 @code{-fprofile-arcs}.
20669
20670 @smallexample
20671 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
20672    -largs -fprofile-arcs
20673 @end smallexample
20674
20675 This compilation process will create @file{.gcno} files together with
20676 the usual object files.
20677
20678 Once the program is compiled with coverage instrumentation, you can
20679 run it as many times as needed - on portions of a test suite for
20680 example. The first execution will produce @file{.gcda} files at the
20681 same location as the @file{.gcno} files.  The following executions
20682 will update those files, so that a cumulative result of the covered
20683 portions of the program is generated.
20684
20685 Finally, you need to call the @code{gcov} tool. The different options of
20686 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
20687
20688 This will create annotated source files with a @file{.gcov} extension:
20689 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
20690
20691 @node Gnat specifics
20692 @subsection Gnat specifics
20693
20694 Because Ada semantics, portions of the source code may be shared among
20695 several object files. This is the case for example when generics are
20696 involved, when inlining is active  or when declarations generate  initialisation
20697 calls. In order to take
20698 into account this shared code, you need to call @code{gcov} on all
20699 source files of the tested program at once.
20700
20701 The list of source files might exceed the system's maximum command line
20702 length. In order to bypass this limitation, a new mechanism has been
20703 implemented in @code{gcov}: you can now list all your project's files into a
20704 text file, and provide this file to gcov as a parameter,  preceded by a @@
20705 (e.g. @samp{gcov @@mysrclist.txt}).
20706
20707 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
20708 not supported as there can be unresolved symbols during the final link.
20709
20710 @node Profiling an Ada Program with gprof
20711 @section Profiling an Ada Program with gprof
20712 @cindex gprof
20713 @cindex -pg
20714 @cindex Profiling
20715
20716 @noindent
20717 This section is not meant to be an exhaustive documentation of @code{gprof}.
20718 Full documentation for it can be found in the GNU Profiler User's Guide
20719 documentation that is part of this GNAT distribution.
20720
20721 Profiling a program helps determine the parts of a program that are executed
20722 most often, and are therefore the most time-consuming.
20723
20724 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
20725 better handle Ada programs and multitasking.
20726 It is currently supported on the following platforms
20727 @itemize @bullet
20728 @item
20729 linux x86/x86_64
20730 @item
20731 solaris sparc/sparc64/x86
20732 @item
20733 windows x86
20734 @end itemize
20735
20736 @noindent
20737 In order to profile a program using @code{gprof}, 3 steps are needed:
20738
20739 @itemize @bullet
20740 @item
20741 Code instrumentation, requiring a full recompilation of the project with the
20742 proper switches.
20743 @item
20744 Execution of the program under the analysis conditions, i.e. with the desired
20745 input.
20746 @item
20747 Analysis of the results using the @code{gprof} tool.
20748 @end itemize
20749
20750 @noindent
20751 The following sections detail the different steps, and indicate how
20752 to interpret the results:
20753 @menu
20754 * Compilation for profiling::
20755 * Program execution::
20756 * Running gprof::
20757 * Interpretation of profiling results::
20758 @end menu
20759
20760 @node Compilation for profiling
20761 @subsection Compilation for profiling
20762 @cindex -pg
20763 @cindex Profiling
20764
20765 In order to profile a program the first step is to tell the compiler
20766 to generate the necessary profiling information. The compiler switch to be used
20767 is @code{-pg}, which must be added to other compilation switches. This
20768 switch needs to be specified both during compilation and link stages, and can
20769 be specified once when using gnatmake:
20770
20771 @smallexample
20772 gnatmake -f -pg -P my_project
20773 @end smallexample
20774
20775 @noindent
20776 Note that only the objects that were compiled with the @samp{-pg} switch will
20777 be profiled; if you need to profile your whole project, use the @samp{-f}
20778 gnatmake switch to force full recompilation.
20779
20780 @node Program execution
20781 @subsection Program execution
20782
20783 @noindent
20784 Once the program has been compiled for profiling, you can run it as usual.
20785
20786 The only constraint imposed by profiling is that the program must terminate
20787 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20788 properly analyzed.
20789
20790 Once the program completes execution, a data file called @file{gmon.out} is
20791 generated in the directory where the program was launched from. If this file
20792 already exists, it will be overwritten.
20793
20794 @node Running gprof
20795 @subsection Running gprof
20796
20797 @noindent
20798 The @code{gprof} tool is called as follow:
20799
20800 @smallexample
20801 gprof my_prog gmon.out
20802 @end smallexample
20803
20804 @noindent
20805 or simpler:
20806
20807 @smallexample
20808 gprof my_prog
20809 @end smallexample
20810
20811 @noindent
20812 The complete form of the gprof command line is the following:
20813
20814 @smallexample
20815 gprof [^switches^options^] [executable [data-file]]
20816 @end smallexample
20817
20818 @noindent
20819 @code{gprof} supports numerous ^switch^options^. The order of these
20820 ^switch^options^ does not matter. The full list of options can be found in
20821 the GNU Profiler User's Guide documentation that comes with this documentation.
20822
20823 The following is the subset of those switches that is most relevant:
20824
20825 @table @option
20826
20827 @item --demangle[=@var{style}]
20828 @itemx --no-demangle
20829 @cindex @option{--demangle} (@code{gprof})
20830 These options control whether symbol names should be demangled when
20831 printing output.  The default is to demangle C++ symbols.  The
20832 @code{--no-demangle} option may be used to turn off demangling. Different
20833 compilers have different mangling styles.  The optional demangling style
20834 argument can be used to choose an appropriate demangling style for your
20835 compiler, in particular Ada symbols generated by GNAT can be demangled using
20836 @code{--demangle=gnat}.
20837
20838 @item -e @var{function_name}
20839 @cindex @option{-e} (@code{gprof})
20840 The @samp{-e @var{function}} option tells @code{gprof} not to print
20841 information about the function @var{function_name} (and its
20842 children@dots{}) in the call graph.  The function will still be listed
20843 as a child of any functions that call it, but its index number will be
20844 shown as @samp{[not printed]}.  More than one @samp{-e} option may be
20845 given; only one @var{function_name} may be indicated with each @samp{-e}
20846 option.
20847
20848 @item -E @var{function_name}
20849 @cindex @option{-E} (@code{gprof})
20850 The @code{-E @var{function}} option works like the @code{-e} option, but
20851 execution time spent in the function (and children who were not called from
20852 anywhere else), will not be used to compute the percentages-of-time for
20853 the call graph.  More than one @samp{-E} option may be given; only one
20854 @var{function_name} may be indicated with each @samp{-E} option.
20855
20856 @item -f @var{function_name}
20857 @cindex @option{-f} (@code{gprof})
20858 The @samp{-f @var{function}} option causes @code{gprof} to limit the
20859 call graph to the function @var{function_name} and its children (and
20860 their children@dots{}).  More than one @samp{-f} option may be given;
20861 only one @var{function_name} may be indicated with each @samp{-f}
20862 option.
20863
20864 @item -F @var{function_name}
20865 @cindex @option{-F} (@code{gprof})
20866 The @samp{-F @var{function}} option works like the @code{-f} option, but
20867 only time spent in the function and its children (and their
20868 children@dots{}) will be used to determine total-time and
20869 percentages-of-time for the call graph.  More than one @samp{-F} option
20870 may be given; only one @var{function_name} may be indicated with each
20871 @samp{-F} option.  The @samp{-F} option overrides the @samp{-E} option.
20872
20873 @end table
20874
20875 @node Interpretation of profiling results
20876 @subsection Interpretation of profiling results
20877
20878 @noindent
20879
20880 The results of the profiling analysis are represented by two arrays: the
20881 'flat profile' and the 'call graph'. Full documentation of those outputs
20882 can be found in the GNU Profiler User's Guide.
20883
20884 The flat profile shows the time spent in each function of the program, and how
20885 many time it has been called. This allows you to locate easily the most
20886 time-consuming functions.
20887
20888 The call graph shows, for each subprogram, the subprograms that call it,
20889 and the subprograms that it calls. It also provides an estimate of the time
20890 spent in each of those callers/called subprograms.
20891 @end ifclear
20892
20893 @c ******************************
20894 @node Running and Debugging Ada Programs
20895 @chapter Running and Debugging Ada Programs
20896 @cindex Debugging
20897
20898 @noindent
20899 This chapter discusses how to debug Ada programs.
20900 @ifset vms
20901 It applies to GNAT on the Alpha OpenVMS platform;
20902 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
20903 since HP has implemented Ada support in the OpenVMS debugger on I64.
20904 @end ifset
20905
20906 An incorrect Ada program may be handled in three ways by the GNAT compiler:
20907
20908 @enumerate
20909 @item
20910 The illegality may be a violation of the static semantics of Ada. In
20911 that case GNAT diagnoses the constructs in the program that are illegal.
20912 It is then a straightforward matter for the user to modify those parts of
20913 the program.
20914
20915 @item
20916 The illegality may be a violation of the dynamic semantics of Ada. In
20917 that case the program compiles and executes, but may generate incorrect
20918 results, or may terminate abnormally with some exception.
20919
20920 @item
20921 When presented with a program that contains convoluted errors, GNAT
20922 itself may terminate abnormally without providing full diagnostics on
20923 the incorrect user program.
20924 @end enumerate
20925
20926 @menu
20927 * The GNAT Debugger GDB::
20928 * Running GDB::
20929 * Introduction to GDB Commands::
20930 * Using Ada Expressions::
20931 * Calling User-Defined Subprograms::
20932 * Using the Next Command in a Function::
20933 * Ada Exceptions::
20934 * Ada Tasks::
20935 * Debugging Generic Units::
20936 * Remote Debugging with gdbserver::
20937 * GNAT Abnormal Termination or Failure to Terminate::
20938 * Naming Conventions for GNAT Source Files::
20939 * Getting Internal Debugging Information::
20940 * Stack Traceback::
20941 @end menu
20942
20943 @cindex Debugger
20944 @findex gdb
20945
20946 @node The GNAT Debugger GDB
20947 @section The GNAT Debugger GDB
20948
20949 @noindent
20950 @code{GDB} is a general purpose, platform-independent debugger that
20951 can be used to debug mixed-language programs compiled with @command{gcc},
20952 and in particular is capable of debugging Ada programs compiled with
20953 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
20954 complex Ada data structures.
20955
20956 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
20957 @ifset vms
20958 located in the GNU:[DOCS] directory,
20959 @end ifset
20960 for full details on the usage of @code{GDB}, including a section on
20961 its usage on programs. This manual should be consulted for full
20962 details. The section that follows is a brief introduction to the
20963 philosophy and use of @code{GDB}.
20964
20965 When GNAT programs are compiled, the compiler optionally writes debugging
20966 information into the generated object file, including information on
20967 line numbers, and on declared types and variables. This information is
20968 separate from the generated code. It makes the object files considerably
20969 larger, but it does not add to the size of the actual executable that
20970 will be loaded into memory, and has no impact on run-time performance. The
20971 generation of debug information is triggered by the use of the
20972 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
20973 used to carry out the compilations. It is important to emphasize that
20974 the use of these options does not change the generated code.
20975
20976 The debugging information is written in standard system formats that
20977 are used by many tools, including debuggers and profilers. The format
20978 of the information is typically designed to describe C types and
20979 semantics, but GNAT implements a translation scheme which allows full
20980 details about Ada types and variables to be encoded into these
20981 standard C formats. Details of this encoding scheme may be found in
20982 the file exp_dbug.ads in the GNAT source distribution. However, the
20983 details of this encoding are, in general, of no interest to a user,
20984 since @code{GDB} automatically performs the necessary decoding.
20985
20986 When a program is bound and linked, the debugging information is
20987 collected from the object files, and stored in the executable image of
20988 the program. Again, this process significantly increases the size of
20989 the generated executable file, but it does not increase the size of
20990 the executable program itself. Furthermore, if this program is run in
20991 the normal manner, it runs exactly as if the debug information were
20992 not present, and takes no more actual memory.
20993
20994 However, if the program is run under control of @code{GDB}, the
20995 debugger is activated.  The image of the program is loaded, at which
20996 point it is ready to run.  If a run command is given, then the program
20997 will run exactly as it would have if @code{GDB} were not present. This
20998 is a crucial part of the @code{GDB} design philosophy.  @code{GDB} is
20999 entirely non-intrusive until a breakpoint is encountered.  If no
21000 breakpoint is ever hit, the program will run exactly as it would if no
21001 debugger were present. When a breakpoint is hit, @code{GDB} accesses
21002 the debugging information and can respond to user commands to inspect
21003 variables, and more generally to report on the state of execution.
21004
21005 @c **************
21006 @node Running GDB
21007 @section Running GDB
21008
21009 @noindent
21010 This section describes how to initiate the debugger.
21011 @c The above sentence is really just filler, but it was otherwise
21012 @c clumsy to get the first paragraph nonindented given the conditional
21013 @c nature of the description
21014
21015 @ifclear vms
21016 The debugger can be launched from a @code{GPS} menu or
21017 directly from the command line. The description below covers the latter use.
21018 All the commands shown can be used in the @code{GPS} debug console window,
21019 but there are usually more GUI-based ways to achieve the same effect.
21020 @end ifclear
21021
21022 The command to run @code{GDB} is
21023
21024 @smallexample
21025 $ ^gdb program^GDB PROGRAM^
21026 @end smallexample
21027
21028 @noindent
21029 where @code{^program^PROGRAM^} is the name of the executable file. This
21030 activates the debugger and results in a prompt for debugger commands.
21031 The simplest command is simply @code{run}, which causes the program to run
21032 exactly as if the debugger were not present. The following section
21033 describes some of the additional commands that can be given to @code{GDB}.
21034
21035 @c *******************************
21036 @node Introduction to GDB Commands
21037 @section Introduction to GDB Commands
21038
21039 @noindent
21040 @code{GDB} contains a large repertoire of commands.  @xref{Top,,
21041 Debugging with GDB, gdb, Debugging with GDB},
21042 @ifset vms
21043 located in the GNU:[DOCS] directory,
21044 @end ifset
21045 for extensive documentation on the use
21046 of these commands, together with examples of their use. Furthermore,
21047 the command @command{help} invoked from within GDB activates a simple help
21048 facility which summarizes the available commands and their options.
21049 In this section we summarize a few of the most commonly
21050 used commands to give an idea of what @code{GDB} is about. You should create
21051 a simple program with debugging information and experiment with the use of
21052 these @code{GDB} commands on the program as you read through the
21053 following section.
21054
21055 @table @code
21056 @item set args @var{arguments}
21057 The @var{arguments} list above is a list of arguments to be passed to
21058 the program on a subsequent run command, just as though the arguments
21059 had been entered on a normal invocation of the program. The @code{set args}
21060 command is not needed if the program does not require arguments.
21061
21062 @item run
21063 The @code{run} command causes execution of the program to start from
21064 the beginning. If the program is already running, that is to say if
21065 you are currently positioned at a breakpoint, then a prompt will ask
21066 for confirmation that you want to abandon the current execution and
21067 restart.
21068
21069 @item breakpoint @var{location}
21070 The breakpoint command sets a breakpoint, that is to say a point at which
21071 execution will halt and @code{GDB} will await further
21072 commands. @var{location} is
21073 either a line number within a file, given in the format @code{file:linenumber},
21074 or it is the name of a subprogram. If you request that a breakpoint be set on
21075 a subprogram that is overloaded, a prompt will ask you to specify on which of
21076 those subprograms you want to breakpoint. You can also
21077 specify that all of them should be breakpointed. If the program is run
21078 and execution encounters the breakpoint, then the program
21079 stops and @code{GDB} signals that the breakpoint was encountered by
21080 printing the line of code before which the program is halted.
21081
21082 @item catch exception @var{name}
21083 This command causes the program execution to stop whenever exception
21084 @var{name} is raised.  If @var{name} is omitted, then the execution is
21085 suspended when any exception is raised.
21086
21087 @item print @var{expression}
21088 This will print the value of the given expression. Most simple
21089 Ada expression formats are properly handled by @code{GDB}, so the expression
21090 can contain function calls, variables, operators, and attribute references.
21091
21092 @item continue
21093 Continues execution following a breakpoint, until the next breakpoint or the
21094 termination of the program.
21095
21096 @item step
21097 Executes a single line after a breakpoint. If the next statement
21098 is a subprogram call, execution continues into (the first statement of)
21099 the called subprogram.
21100
21101 @item next
21102 Executes a single line. If this line is a subprogram call, executes and
21103 returns from the call.
21104
21105 @item list
21106 Lists a few lines around the current source location. In practice, it
21107 is usually more convenient to have a separate edit window open with the
21108 relevant source file displayed. Successive applications of this command
21109 print subsequent lines. The command can be given an argument which is a
21110 line number, in which case it displays a few lines around the specified one.
21111
21112 @item backtrace
21113 Displays a backtrace of the call chain. This command is typically
21114 used after a breakpoint has occurred, to examine the sequence of calls that
21115 leads to the current breakpoint. The display includes one line for each
21116 activation record (frame) corresponding to an active subprogram.
21117
21118 @item up
21119 At a breakpoint, @code{GDB} can display the values of variables local
21120 to the current frame. The command @code{up} can be used to
21121 examine the contents of other active frames, by moving the focus up
21122 the stack, that is to say from callee to caller, one frame at a time.
21123
21124 @item down
21125 Moves the focus of @code{GDB} down from the frame currently being
21126 examined to the frame of its callee (the reverse of the previous command),
21127
21128 @item frame @var{n}
21129 Inspect the frame with the given number. The value 0 denotes the frame
21130 of the current breakpoint, that is to say the top of the call stack.
21131
21132 @end table
21133
21134 @noindent
21135 The above list is a very short introduction to the commands that
21136 @code{GDB} provides. Important additional capabilities, including conditional
21137 breakpoints, the ability to execute command sequences on a breakpoint,
21138 the ability to debug at the machine instruction level and many other
21139 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
21140 Debugging with GDB}.  Note that most commands can be abbreviated
21141 (for example, c for continue, bt for backtrace).
21142
21143 @node Using Ada Expressions
21144 @section Using Ada Expressions
21145 @cindex Ada expressions
21146
21147 @noindent
21148 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
21149 extensions. The philosophy behind the design of this subset is
21150
21151 @itemize @bullet
21152 @item
21153 That @code{GDB} should provide basic literals and access to operations for
21154 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
21155 leaving more sophisticated computations to subprograms written into the
21156 program (which therefore may be called from @code{GDB}).
21157
21158 @item
21159 That type safety and strict adherence to Ada language restrictions
21160 are not particularly important to the @code{GDB} user.
21161
21162 @item
21163 That brevity is important to the @code{GDB} user.
21164 @end itemize
21165
21166 @noindent
21167 Thus, for brevity, the debugger acts as if there were
21168 implicit @code{with} and @code{use} clauses in effect for all user-written
21169 packages, thus making it unnecessary to fully qualify most names with
21170 their packages, regardless of context. Where this causes ambiguity,
21171 @code{GDB} asks the user's intent.
21172
21173 For details on the supported Ada syntax, see @ref{Top,, Debugging with
21174 GDB, gdb, Debugging with GDB}.
21175
21176 @node Calling User-Defined Subprograms
21177 @section Calling User-Defined Subprograms
21178
21179 @noindent
21180 An important capability of @code{GDB} is the ability to call user-defined
21181 subprograms while debugging. This is achieved simply by entering
21182 a subprogram call statement in the form:
21183
21184 @smallexample
21185 call subprogram-name (parameters)
21186 @end smallexample
21187
21188 @noindent
21189 The keyword @code{call} can be omitted in the normal case where the
21190 @code{subprogram-name} does not coincide with any of the predefined
21191 @code{GDB} commands.
21192
21193 The effect is to invoke the given subprogram, passing it the
21194 list of parameters that is supplied. The parameters can be expressions and
21195 can include variables from the program being debugged. The
21196 subprogram must be defined
21197 at the library level within your program, and @code{GDB} will call the
21198 subprogram within the environment of your program execution (which
21199 means that the subprogram is free to access or even modify variables
21200 within your program).
21201
21202 The most important use of this facility is in allowing the inclusion of
21203 debugging routines that are tailored to particular data structures
21204 in your program. Such debugging routines can be written to provide a suitably
21205 high-level description of an abstract type, rather than a low-level dump
21206 of its physical layout. After all, the standard
21207 @code{GDB print} command only knows the physical layout of your
21208 types, not their abstract meaning. Debugging routines can provide information
21209 at the desired semantic level and are thus enormously useful.
21210
21211 For example, when debugging GNAT itself, it is crucial to have access to
21212 the contents of the tree nodes used to represent the program internally.
21213 But tree nodes are represented simply by an integer value (which in turn
21214 is an index into a table of nodes).
21215 Using the @code{print} command on a tree node would simply print this integer
21216 value, which is not very useful. But the PN routine (defined in file
21217 treepr.adb in the GNAT sources) takes a tree node as input, and displays
21218 a useful high level representation of the tree node, which includes the
21219 syntactic category of the node, its position in the source, the integers
21220 that denote descendant nodes and parent node, as well as varied
21221 semantic information. To study this example in more detail, you might want to
21222 look at the body of the PN procedure in the stated file.
21223
21224 @node Using the Next Command in a Function
21225 @section Using the Next Command in a Function
21226
21227 @noindent
21228 When you use the @code{next} command in a function, the current source
21229 location will advance to the next statement as usual. A special case
21230 arises in the case of a @code{return} statement.
21231
21232 Part of the code for a return statement is the ``epilog'' of the function.
21233 This is the code that returns to the caller. There is only one copy of
21234 this epilog code, and it is typically associated with the last return
21235 statement in the function if there is more than one return. In some
21236 implementations, this epilog is associated with the first statement
21237 of the function.
21238
21239 The result is that if you use the @code{next} command from a return
21240 statement that is not the last return statement of the function you
21241 may see a strange apparent jump to the last return statement or to
21242 the start of the function. You should simply ignore this odd jump.
21243 The value returned is always that from the first return statement
21244 that was stepped through.
21245
21246 @node Ada Exceptions
21247 @section Stopping when Ada Exceptions are Raised
21248 @cindex Exceptions
21249
21250 @noindent
21251 You can set catchpoints that stop the program execution when your program
21252 raises selected exceptions.
21253
21254 @table @code
21255 @item catch exception
21256 Set a catchpoint that stops execution whenever (any task in the) program
21257 raises any exception.
21258
21259 @item catch exception @var{name}
21260 Set a catchpoint that stops execution whenever (any task in the) program
21261 raises the exception @var{name}.
21262
21263 @item catch exception unhandled
21264 Set a catchpoint that stops executing whenever (any task in the) program
21265 raises an exception for which there is no handler.
21266
21267 @item info exceptions
21268 @itemx info exceptions @var{regexp}
21269 The @code{info exceptions} command permits the user to examine all defined
21270 exceptions within Ada programs. With a regular expression, @var{regexp}, as
21271 argument, prints out only those exceptions whose name matches @var{regexp}.
21272 @end table
21273
21274 @node Ada Tasks
21275 @section Ada Tasks
21276 @cindex Tasks
21277
21278 @noindent
21279 @code{GDB} allows the following task-related commands:
21280
21281 @table @code
21282 @item info tasks
21283 This command shows a list of current Ada tasks, as in the following example:
21284
21285 @smallexample
21286 @iftex
21287 @leftskip=0cm
21288 @end iftex
21289 (gdb) info tasks
21290   ID       TID P-ID   Thread Pri State                 Name
21291    1   8088000   0   807e000  15 Child Activation Wait main_task
21292    2   80a4000   1   80ae000  15 Accept/Select Wait    b
21293    3   809a800   1   80a4800  15 Child Activation Wait a
21294 *  4   80ae800   3   80b8000  15 Running               c
21295 @end smallexample
21296
21297 @noindent
21298 In this listing, the asterisk before the first task indicates it to be the
21299 currently running task. The first column lists the task ID that is used
21300 to refer to tasks in the following commands.
21301
21302 @item break @var{linespec} task @var{taskid}
21303 @itemx break @var{linespec} task @var{taskid} if @dots{}
21304 @cindex Breakpoints and tasks
21305 These commands are like the @code{break @dots{} thread @dots{}}.
21306 @var{linespec} specifies source lines.
21307
21308 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
21309 to specify that you only want @code{GDB} to stop the program when a
21310 particular Ada task reaches this breakpoint. @var{taskid} is one of the
21311 numeric task identifiers assigned by @code{GDB}, shown in the first
21312 column of the @samp{info tasks} display.
21313
21314 If you do not specify @samp{task @var{taskid}} when you set a
21315 breakpoint, the breakpoint applies to @emph{all} tasks of your
21316 program.
21317
21318 You can use the @code{task} qualifier on conditional breakpoints as
21319 well; in this case, place @samp{task @var{taskid}} before the
21320 breakpoint condition (before the @code{if}).
21321
21322 @item task @var{taskno}
21323 @cindex Task switching
21324
21325 This command allows to switch to the task referred by @var{taskno}. In
21326 particular, This allows to browse the backtrace of the specified
21327 task. It is advised to switch back to the original task before
21328 continuing execution otherwise the scheduling of the program may be
21329 perturbed.
21330 @end table
21331
21332 @noindent
21333 For more detailed information on the tasking support,
21334 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
21335
21336 @node Debugging Generic Units
21337 @section Debugging Generic Units
21338 @cindex Debugging Generic Units
21339 @cindex Generics
21340
21341 @noindent
21342 GNAT always uses code expansion for generic instantiation. This means that
21343 each time an instantiation occurs, a complete copy of the original code is
21344 made, with appropriate substitutions of formals by actuals.
21345
21346 It is not possible to refer to the original generic entities in
21347 @code{GDB}, but it is always possible to debug a particular instance of
21348 a generic, by using the appropriate expanded names. For example, if we have
21349
21350 @smallexample @c ada
21351 @group
21352 @cartouche
21353 procedure g is
21354
21355    generic package k is
21356       procedure kp (v1 : in out integer);
21357    end k;
21358
21359    package body k is
21360       procedure kp (v1 : in out integer) is
21361       begin
21362          v1 := v1 + 1;
21363       end kp;
21364    end k;
21365
21366    package k1 is new k;
21367    package k2 is new k;
21368
21369    var : integer := 1;
21370
21371 begin
21372    k1.kp (var);
21373    k2.kp (var);
21374    k1.kp (var);
21375    k2.kp (var);
21376 end;
21377 @end cartouche
21378 @end group
21379 @end smallexample
21380
21381 @noindent
21382 Then to break on a call to procedure kp in the k2 instance, simply
21383 use the command:
21384
21385 @smallexample
21386 (gdb) break g.k2.kp
21387 @end smallexample
21388
21389 @noindent
21390 When the breakpoint occurs, you can step through the code of the
21391 instance in the normal manner and examine the values of local variables, as for
21392 other units.
21393
21394 @node Remote Debugging with gdbserver
21395 @section Remote Debugging with gdbserver
21396 @cindex Remote Debugging with gdbserver
21397
21398 @noindent
21399 On platforms where gdbserver is supported, it is possible to use this tool
21400 to debug your application remotely.  This can be useful in situations
21401 where the program needs to be run on a target host that is different
21402 from the host used for development, particularly when the target has
21403 a limited amount of resources (either CPU and/or memory).
21404
21405 To do so, start your program using gdbserver on the target machine.
21406 gdbserver then automatically suspends the execution of your program
21407 at its entry point, waiting for a debugger to connect to it.  The
21408 following commands starts an application and tells gdbserver to
21409 wait for a connection with the debugger on localhost port 4444.
21410
21411 @smallexample
21412 $ gdbserver localhost:4444 program
21413 Process program created; pid = 5685
21414 Listening on port 4444
21415 @end smallexample
21416
21417 Once gdbserver has started listening, we can tell the debugger to establish
21418 a connection with this gdbserver, and then start the same debugging session
21419 as if the program was being debugged on the same host, directly under
21420 the control of GDB.
21421
21422 @smallexample
21423 $ gdb program
21424 (gdb) target remote targethost:4444
21425 Remote debugging using targethost:4444
21426 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
21427 (gdb) b foo.adb:3
21428 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
21429 (gdb) continue
21430 Continuing.
21431
21432 Breakpoint 1, foo () at foo.adb:4
21433 4       end foo;
21434 @end smallexample
21435
21436 It is also possible to use gdbserver to attach to an already running
21437 program, in which case the execution of that program is simply suspended
21438 until the connection between the debugger and gdbserver is established.
21439
21440 For more information on how to use gdbserver, @ref{Top, Server, Using
21441 the gdbserver Program, gdb, Debugging with GDB}.  @value{EDITION} provides support
21442 for gdbserver on x86-linux, x86-windows and x86_64-linux.
21443
21444 @node GNAT Abnormal Termination or Failure to Terminate
21445 @section GNAT Abnormal Termination or Failure to Terminate
21446 @cindex GNAT Abnormal Termination or Failure to Terminate
21447
21448 @noindent
21449 When presented with programs that contain serious errors in syntax
21450 or semantics,
21451 GNAT may on rare occasions  experience problems in operation, such
21452 as aborting with a
21453 segmentation fault or illegal memory access, raising an internal
21454 exception, terminating abnormally, or failing to terminate at all.
21455 In such cases, you can activate
21456 various features of GNAT that can help you pinpoint the construct in your
21457 program that is the likely source of the problem.
21458
21459 The following strategies are presented in increasing order of
21460 difficulty, corresponding to your experience in using GNAT and your
21461 familiarity with compiler internals.
21462
21463 @enumerate
21464 @item
21465 Run @command{gcc} with the @option{-gnatf}. This first
21466 switch causes all errors on a given line to be reported. In its absence,
21467 only the first error on a line is displayed.
21468
21469 The @option{-gnatdO} switch causes errors to be displayed as soon as they
21470 are encountered, rather than after compilation is terminated. If GNAT
21471 terminates prematurely or goes into an infinite loop, the last error
21472 message displayed may help to pinpoint the culprit.
21473
21474 @item
21475 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
21476 mode, @command{gcc} produces ongoing information about the progress of the
21477 compilation and provides the name of each procedure as code is
21478 generated. This switch allows you to find which Ada procedure was being
21479 compiled when it encountered a code generation problem.
21480
21481 @item
21482 @cindex @option{-gnatdc} switch
21483 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
21484 switch that does for the front-end what @option{^-v^VERBOSE^} does
21485 for the back end. The system prints the name of each unit,
21486 either a compilation unit or nested unit, as it is being analyzed.
21487 @item
21488 Finally, you can start
21489 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
21490 front-end of GNAT, and can be run independently (normally it is just
21491 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
21492 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
21493 @code{where} command is the first line of attack; the variable
21494 @code{lineno} (seen by @code{print lineno}), used by the second phase of
21495 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
21496 which the execution stopped, and @code{input_file name} indicates the name of
21497 the source file.
21498 @end enumerate
21499
21500 @node Naming Conventions for GNAT Source Files
21501 @section Naming Conventions for GNAT Source Files
21502
21503 @noindent
21504 In order to examine the workings of the GNAT system, the following
21505 brief description of its organization may be helpful:
21506
21507 @itemize @bullet
21508 @item
21509 Files with prefix @file{^sc^SC^} contain the lexical scanner.
21510
21511 @item
21512 All files prefixed with @file{^par^PAR^} are components of the parser. The
21513 numbers correspond to chapters of the Ada Reference Manual. For example,
21514 parsing of select statements can be found in @file{par-ch9.adb}.
21515
21516 @item
21517 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
21518 numbers correspond to chapters of the Ada standard. For example, all
21519 issues involving context clauses can be found in @file{sem_ch10.adb}. In
21520 addition, some features of the language require sufficient special processing
21521 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
21522 dynamic dispatching, etc.
21523
21524 @item
21525 All files prefixed with @file{^exp^EXP^} perform normalization and
21526 expansion of the intermediate representation (abstract syntax tree, or AST).
21527 these files use the same numbering scheme as the parser and semantics files.
21528 For example, the construction of record initialization procedures is done in
21529 @file{exp_ch3.adb}.
21530
21531 @item
21532 The files prefixed with @file{^bind^BIND^} implement the binder, which
21533 verifies the consistency of the compilation, determines an order of
21534 elaboration, and generates the bind file.
21535
21536 @item
21537 The files @file{atree.ads} and @file{atree.adb} detail the low-level
21538 data structures used by the front-end.
21539
21540 @item
21541 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
21542 the abstract syntax tree as produced by the parser.
21543
21544 @item
21545 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
21546 all entities, computed during semantic analysis.
21547
21548 @item
21549 Library management issues are dealt with in files with prefix
21550 @file{^lib^LIB^}.
21551
21552 @item
21553 @findex Ada
21554 @cindex Annex A
21555 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
21556 defined in Annex A.
21557
21558 @item
21559 @findex Interfaces
21560 @cindex Annex B
21561 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
21562 defined in Annex B.
21563
21564 @item
21565 @findex System
21566 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
21567 both language-defined children and GNAT run-time routines.
21568
21569 @item
21570 @findex GNAT
21571 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
21572 general-purpose packages, fully documented in their specs. All
21573 the other @file{.c} files are modifications of common @command{gcc} files.
21574 @end itemize
21575
21576 @node Getting Internal Debugging Information
21577 @section Getting Internal Debugging Information
21578
21579 @noindent
21580 Most compilers have internal debugging switches and modes. GNAT
21581 does also, except GNAT internal debugging switches and modes are not
21582 secret. A summary and full description of all the compiler and binder
21583 debug flags are in the file @file{debug.adb}. You must obtain the
21584 sources of the compiler to see the full detailed effects of these flags.
21585
21586 The switches that print the source of the program (reconstructed from
21587 the internal tree) are of general interest for user programs, as are the
21588 options to print
21589 the full internal tree, and the entity table (the symbol table
21590 information). The reconstructed source provides a readable version of the
21591 program after the front-end has completed analysis and  expansion,
21592 and is useful when studying the performance of specific constructs.
21593 For example, constraint checks are indicated, complex aggregates
21594 are replaced with loops and assignments, and tasking primitives
21595 are replaced with run-time calls.
21596
21597 @node Stack Traceback
21598 @section Stack Traceback
21599 @cindex traceback
21600 @cindex stack traceback
21601 @cindex stack unwinding
21602
21603 @noindent
21604 Traceback is a mechanism to display the sequence of subprogram calls that
21605 leads to a specified execution point in a program. Often (but not always)
21606 the execution point is an instruction at which an exception has been raised.
21607 This mechanism is also known as @i{stack unwinding} because it obtains
21608 its information by scanning the run-time stack and recovering the activation
21609 records of all active subprograms. Stack unwinding is one of the most
21610 important tools for program debugging.
21611
21612 The first entry stored in traceback corresponds to the deepest calling level,
21613 that is to say the subprogram currently executing the instruction
21614 from which we want to obtain the traceback.
21615
21616 Note that there is no runtime performance penalty when stack traceback
21617 is enabled, and no exception is raised during program execution.
21618
21619 @menu
21620 * Non-Symbolic Traceback::
21621 * Symbolic Traceback::
21622 @end menu
21623
21624 @node Non-Symbolic Traceback
21625 @subsection Non-Symbolic Traceback
21626 @cindex traceback, non-symbolic
21627
21628 @noindent
21629 Note: this feature is not supported on all platforms. See
21630 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
21631 platforms.
21632
21633 @menu
21634 * Tracebacks From an Unhandled Exception::
21635 * Tracebacks From Exception Occurrences (non-symbolic)::
21636 * Tracebacks From Anywhere in a Program (non-symbolic)::
21637 @end menu
21638
21639 @node Tracebacks From an Unhandled Exception
21640 @subsubsection Tracebacks From an Unhandled Exception
21641
21642 @noindent
21643 A runtime non-symbolic traceback is a list of addresses of call instructions.
21644 To enable this feature you must use the @option{-E}
21645 @code{gnatbind}'s option. With this option a stack traceback is stored as part
21646 of exception information. You can retrieve this information using the
21647 @code{addr2line} tool.
21648
21649 Here is a simple example:
21650
21651 @smallexample @c ada
21652 @cartouche
21653 procedure STB is
21654
21655    procedure P1 is
21656    begin
21657       raise Constraint_Error;
21658    end P1;
21659
21660    procedure P2 is
21661    begin
21662       P1;
21663    end P2;
21664
21665 begin
21666    P2;
21667 end STB;
21668 @end cartouche
21669 @end smallexample
21670
21671 @smallexample
21672 $ gnatmake stb -bargs -E
21673 $ stb
21674
21675 Execution terminated by unhandled exception
21676 Exception name: CONSTRAINT_ERROR
21677 Message: stb.adb:5
21678 Call stack traceback locations:
21679 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21680 @end smallexample
21681
21682 @noindent
21683 As we see the traceback lists a sequence of addresses for the unhandled
21684 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
21685 guess that this exception come from procedure P1. To translate these
21686 addresses into the source lines where the calls appear, the
21687 @code{addr2line} tool, described below, is invaluable. The use of this tool
21688 requires the program to be compiled with debug information.
21689
21690 @smallexample
21691 $ gnatmake -g stb -bargs -E
21692 $ stb
21693
21694 Execution terminated by unhandled exception
21695 Exception name: CONSTRAINT_ERROR
21696 Message: stb.adb:5
21697 Call stack traceback locations:
21698 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21699
21700 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
21701    0x4011f1 0x77e892a4
21702
21703 00401373 at d:/stb/stb.adb:5
21704 0040138B at d:/stb/stb.adb:10
21705 0040139C at d:/stb/stb.adb:14
21706 00401335 at d:/stb/b~stb.adb:104
21707 004011C4 at /build/@dots{}/crt1.c:200
21708 004011F1 at /build/@dots{}/crt1.c:222
21709 77E892A4 in ?? at ??:0
21710 @end smallexample
21711
21712 @noindent
21713 The @code{addr2line} tool has several other useful options:
21714
21715 @table @code
21716 @item --functions
21717 to get the function name corresponding to any location
21718
21719 @item --demangle=gnat
21720 to use the gnat decoding mode for the function names. Note that
21721 for binutils version 2.9.x the option is simply @option{--demangle}.
21722 @end table
21723
21724 @smallexample
21725 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
21726    0x40139c 0x401335 0x4011c4 0x4011f1
21727
21728 00401373 in stb.p1 at d:/stb/stb.adb:5
21729 0040138B in stb.p2 at d:/stb/stb.adb:10
21730 0040139C in stb at d:/stb/stb.adb:14
21731 00401335 in main at d:/stb/b~stb.adb:104
21732 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
21733 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
21734 @end smallexample
21735
21736 @noindent
21737 From this traceback we can see that the exception was raised in
21738 @file{stb.adb} at line 5, which was reached from a procedure call in
21739 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
21740 which contains the call to the main program.
21741 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
21742 and the output will vary from platform to platform.
21743
21744 It is also possible to use @code{GDB} with these traceback addresses to debug
21745 the program. For example, we can break at a given code location, as reported
21746 in the stack traceback:
21747
21748 @smallexample
21749 $ gdb -nw stb
21750 @ifclear vms
21751 @noindent
21752 Furthermore, this feature is not implemented inside Windows DLL. Only
21753 the non-symbolic traceback is reported in this case.
21754 @end ifclear
21755
21756 (gdb) break *0x401373
21757 Breakpoint 1 at 0x401373: file stb.adb, line 5.
21758 @end smallexample
21759
21760 @noindent
21761 It is important to note that the stack traceback addresses
21762 do not change when debug information is included. This is particularly useful
21763 because it makes it possible to release software without debug information (to
21764 minimize object size), get a field report that includes a stack traceback
21765 whenever an internal bug occurs, and then be able to retrieve the sequence
21766 of calls with the same program compiled with debug information.
21767
21768 @node Tracebacks From Exception Occurrences (non-symbolic)
21769 @subsubsection Tracebacks From Exception Occurrences
21770
21771 @noindent
21772 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
21773 The stack traceback is attached to the exception information string, and can
21774 be retrieved in an exception handler within the Ada program, by means of the
21775 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
21776
21777 @smallexample @c ada
21778 with Ada.Text_IO;
21779 with Ada.Exceptions;
21780
21781 procedure STB is
21782
21783    use Ada;
21784    use Ada.Exceptions;
21785
21786    procedure P1 is
21787       K : Positive := 1;
21788    begin
21789       K := K - 1;
21790    exception
21791       when E : others =>
21792          Text_IO.Put_Line (Exception_Information (E));
21793    end P1;
21794
21795    procedure P2 is
21796    begin
21797       P1;
21798    end P2;
21799
21800 begin
21801    P2;
21802 end STB;
21803 @end smallexample
21804
21805 @noindent
21806 This program will output:
21807
21808 @smallexample
21809 $ stb
21810
21811 Exception name: CONSTRAINT_ERROR
21812 Message: stb.adb:12
21813 Call stack traceback locations:
21814 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
21815 @end smallexample
21816
21817 @node Tracebacks From Anywhere in a Program (non-symbolic)
21818 @subsubsection Tracebacks From Anywhere in a Program
21819
21820 @noindent
21821 It is also possible to retrieve a stack traceback from anywhere in a
21822 program. For this you need to
21823 use the @code{GNAT.Traceback} API. This package includes a procedure called
21824 @code{Call_Chain} that computes a complete stack traceback, as well as useful
21825 display procedures described below. It is not necessary to use the
21826 @option{-E gnatbind} option in this case, because the stack traceback mechanism
21827 is invoked explicitly.
21828
21829 @noindent
21830 In the following example we compute a traceback at a specific location in
21831 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
21832 convert addresses to strings:
21833
21834 @smallexample @c ada
21835 with Ada.Text_IO;
21836 with GNAT.Traceback;
21837 with GNAT.Debug_Utilities;
21838
21839 procedure STB is
21840
21841    use Ada;
21842    use GNAT;
21843    use GNAT.Traceback;
21844
21845    procedure P1 is
21846       TB  : Tracebacks_Array (1 .. 10);
21847       --  We are asking for a maximum of 10 stack frames.
21848       Len : Natural;
21849       --  Len will receive the actual number of stack frames returned.
21850    begin
21851       Call_Chain (TB, Len);
21852
21853       Text_IO.Put ("In STB.P1 : ");
21854
21855       for K in 1 .. Len loop
21856          Text_IO.Put (Debug_Utilities.Image (TB (K)));
21857          Text_IO.Put (' ');
21858       end loop;
21859
21860       Text_IO.New_Line;
21861    end P1;
21862
21863    procedure P2 is
21864    begin
21865       P1;
21866    end P2;
21867
21868 begin
21869    P2;
21870 end STB;
21871 @end smallexample
21872
21873 @smallexample
21874 $ gnatmake -g stb
21875 $ stb
21876
21877 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
21878 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
21879 @end smallexample
21880
21881 @noindent
21882 You can then get further information by invoking the @code{addr2line}
21883 tool as described earlier (note that the hexadecimal addresses
21884 need to be specified in C format, with a leading ``0x'').
21885
21886 @node Symbolic Traceback
21887 @subsection Symbolic Traceback
21888 @cindex traceback, symbolic
21889
21890 @noindent
21891 A symbolic traceback is a stack traceback in which procedure names are
21892 associated with each code location.
21893
21894 @noindent
21895 Note that this feature is not supported on all platforms. See
21896 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
21897 list of currently supported platforms.
21898
21899 @noindent
21900 Note that the symbolic traceback requires that the program be compiled
21901 with debug information. If it is not compiled with debug information
21902 only the non-symbolic information will be valid.
21903
21904 @menu
21905 * Tracebacks From Exception Occurrences (symbolic)::
21906 * Tracebacks From Anywhere in a Program (symbolic)::
21907 @end menu
21908
21909 @node Tracebacks From Exception Occurrences (symbolic)
21910 @subsubsection Tracebacks From Exception Occurrences
21911
21912 @smallexample @c ada
21913 with Ada.Text_IO;
21914 with GNAT.Traceback.Symbolic;
21915
21916 procedure STB is
21917
21918    procedure P1 is
21919    begin
21920       raise Constraint_Error;
21921    end P1;
21922
21923    procedure P2 is
21924    begin
21925       P1;
21926    end P2;
21927
21928    procedure P3 is
21929    begin
21930       P2;
21931    end P3;
21932
21933 begin
21934    P3;
21935 exception
21936    when E : others =>
21937       Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
21938 end STB;
21939 @end smallexample
21940
21941 @smallexample
21942 $ gnatmake -g .\stb -bargs -E
21943 $ stb
21944
21945 0040149F in stb.p1 at stb.adb:8
21946 004014B7 in stb.p2 at stb.adb:13
21947 004014CF in stb.p3 at stb.adb:18
21948 004015DD in ada.stb at stb.adb:22
21949 00401461 in main at b~stb.adb:168
21950 004011C4 in __mingw_CRTStartup at crt1.c:200
21951 004011F1 in mainCRTStartup at crt1.c:222
21952 77E892A4 in ?? at ??:0
21953 @end smallexample
21954
21955 @noindent
21956 In the above example the ``.\'' syntax in the @command{gnatmake} command
21957 is currently required by @command{addr2line} for files that are in
21958 the current working directory.
21959 Moreover, the exact sequence of linker options may vary from platform
21960 to platform.
21961 The above @option{-largs} section is for Windows platforms. By contrast,
21962 under Unix there is no need for the @option{-largs} section.
21963 Differences across platforms are due to details of linker implementation.
21964
21965 @node Tracebacks From Anywhere in a Program (symbolic)
21966 @subsubsection Tracebacks From Anywhere in a Program
21967
21968 @noindent
21969 It is possible to get a symbolic stack traceback
21970 from anywhere in a program, just as for non-symbolic tracebacks.
21971 The first step is to obtain a non-symbolic
21972 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
21973 information. Here is an example:
21974
21975 @smallexample @c ada
21976 with Ada.Text_IO;
21977 with GNAT.Traceback;
21978 with GNAT.Traceback.Symbolic;
21979
21980 procedure STB is
21981
21982    use Ada;
21983    use GNAT.Traceback;
21984    use GNAT.Traceback.Symbolic;
21985
21986    procedure P1 is
21987       TB  : Tracebacks_Array (1 .. 10);
21988       --  We are asking for a maximum of 10 stack frames.
21989       Len : Natural;
21990       --  Len will receive the actual number of stack frames returned.
21991    begin
21992       Call_Chain (TB, Len);
21993       Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
21994    end P1;
21995
21996    procedure P2 is
21997    begin
21998       P1;
21999    end P2;
22000
22001 begin
22002    P2;
22003 end STB;
22004 @end smallexample
22005
22006 @c ******************************
22007 @ifset vms
22008 @node Compatibility with HP Ada
22009 @chapter Compatibility with HP Ada
22010 @cindex Compatibility
22011
22012 @noindent
22013 @cindex DEC Ada
22014 @cindex HP Ada
22015 @cindex Compatibility between GNAT and HP Ada
22016 This chapter compares HP Ada (formerly known as ``DEC Ada'')
22017 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
22018 GNAT is highly compatible
22019 with HP Ada, and it should generally be straightforward to port code
22020 from the HP Ada environment to GNAT. However, there are a few language
22021 and implementation differences of which the user must be aware. These
22022 differences are discussed in this chapter. In
22023 addition, the operating environment and command structure for the
22024 compiler are different, and these differences are also discussed.
22025
22026 For further details on these and other compatibility issues,
22027 see Appendix E of the HP publication
22028 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
22029
22030 Except where otherwise indicated, the description of GNAT for OpenVMS
22031 applies to both the Alpha and I64 platforms.
22032
22033 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
22034 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22035
22036 The discussion in this chapter addresses specifically the implementation
22037 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
22038 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
22039 GNAT always follows the Alpha implementation.
22040
22041 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
22042 attributes are recognized, although only a subset of them can sensibly
22043 be implemented.  The description of pragmas in
22044 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
22045 indicates whether or not they are applicable to non-VMS systems.
22046
22047 @menu
22048 * Ada Language Compatibility::
22049 * Differences in the Definition of Package System::
22050 * Language-Related Features::
22051 * The Package STANDARD::
22052 * The Package SYSTEM::
22053 * Tasking and Task-Related Features::
22054 * Pragmas and Pragma-Related Features::
22055 * Library of Predefined Units::
22056 * Bindings::
22057 * Main Program Definition::
22058 * Implementation-Defined Attributes::
22059 * Compiler and Run-Time Interfacing::
22060 * Program Compilation and Library Management::
22061 * Input-Output::
22062 * Implementation Limits::
22063 * Tools and Utilities::
22064 @end menu
22065
22066 @node Ada Language Compatibility
22067 @section Ada Language Compatibility
22068
22069 @noindent
22070 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
22071 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
22072 with Ada 83, and therefore Ada 83 programs will compile
22073 and run under GNAT with
22074 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
22075 provides details on specific incompatibilities.
22076
22077 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
22078 as well as the pragma @code{ADA_83}, to force the compiler to
22079 operate in Ada 83 mode. This mode does not guarantee complete
22080 conformance to Ada 83, but in practice is sufficient to
22081 eliminate most sources of incompatibilities.
22082 In particular, it eliminates the recognition of the
22083 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
22084 in Ada 83 programs is legal, and handles the cases of packages
22085 with optional bodies, and generics that instantiate unconstrained
22086 types without the use of @code{(<>)}.
22087
22088 @node Differences in the Definition of Package System
22089 @section Differences in the Definition of Package @code{System}
22090
22091 @noindent
22092 An Ada compiler is allowed to add
22093 implementation-dependent declarations to package @code{System}.
22094 In normal mode,
22095 GNAT does not take advantage of this permission, and the version of
22096 @code{System} provided by GNAT exactly matches that defined in the Ada
22097 Reference Manual.
22098
22099 However, HP Ada adds an extensive set of declarations to package
22100 @code{System},
22101 as fully documented in the HP Ada manuals. To minimize changes required
22102 for programs that make use of these extensions, GNAT provides the pragma
22103 @code{Extend_System} for extending the definition of package System. By using:
22104 @cindex pragma @code{Extend_System}
22105 @cindex @code{Extend_System} pragma
22106
22107 @smallexample @c ada
22108 @group
22109 @cartouche
22110 pragma Extend_System (Aux_DEC);
22111 @end cartouche
22112 @end group
22113 @end smallexample
22114
22115 @noindent
22116 the set of definitions in @code{System} is extended to include those in
22117 package @code{System.Aux_DEC}.
22118 @cindex @code{System.Aux_DEC} package
22119 @cindex @code{Aux_DEC} package (child of @code{System})
22120 These definitions are incorporated directly into package @code{System},
22121 as though they had been declared there. For a
22122 list of the declarations added, see the spec of this package,
22123 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
22124 @cindex @file{s-auxdec.ads} file
22125 The pragma @code{Extend_System} is a configuration pragma, which means that
22126 it can be placed in the file @file{gnat.adc}, so that it will automatically
22127 apply to all subsequent compilations. See @ref{Configuration Pragmas},
22128 for further details.
22129
22130 An alternative approach that avoids the use of the non-standard
22131 @code{Extend_System} pragma is to add a context clause to the unit that
22132 references these facilities:
22133
22134 @smallexample @c ada
22135 @cartouche
22136 with System.Aux_DEC;
22137 use  System.Aux_DEC;
22138 @end cartouche
22139 @end smallexample
22140
22141 @noindent
22142 The effect is not quite semantically identical to incorporating
22143 the declarations directly into package @code{System},
22144 but most programs will not notice a difference
22145 unless they use prefix notation (e.g.@: @code{System.Integer_8})
22146 to reference the entities directly in package @code{System}.
22147 For units containing such references,
22148 the prefixes must either be removed, or the pragma @code{Extend_System}
22149 must be used.
22150
22151 @node Language-Related Features
22152 @section Language-Related Features
22153
22154 @noindent
22155 The following sections highlight differences in types,
22156 representations of types, operations, alignment, and
22157 related topics.
22158
22159 @menu
22160 * Integer Types and Representations::
22161 * Floating-Point Types and Representations::
22162 * Pragmas Float_Representation and Long_Float::
22163 * Fixed-Point Types and Representations::
22164 * Record and Array Component Alignment::
22165 * Address Clauses::
22166 * Other Representation Clauses::
22167 @end menu
22168
22169 @node Integer Types and Representations
22170 @subsection Integer Types and Representations
22171
22172 @noindent
22173 The set of predefined integer types is identical in HP Ada and GNAT.
22174 Furthermore the representation of these integer types is also identical,
22175 including the capability of size clauses forcing biased representation.
22176
22177 In addition,
22178 HP Ada for OpenVMS Alpha systems has defined the
22179 following additional integer types in package @code{System}:
22180
22181 @itemize @bullet
22182
22183 @item
22184 @code{INTEGER_8}
22185
22186 @item
22187 @code{INTEGER_16}
22188
22189 @item
22190 @code{INTEGER_32}
22191
22192 @item
22193 @code{INTEGER_64}
22194
22195 @item
22196 @code{LARGEST_INTEGER}
22197 @end itemize
22198
22199 @noindent
22200 In GNAT, the first four of these types may be obtained from the
22201 standard Ada package @code{Interfaces}.
22202 Alternatively, by use of the pragma @code{Extend_System}, identical
22203 declarations can be referenced directly in package @code{System}.
22204 On both GNAT and HP Ada, the maximum integer size is 64 bits.
22205
22206 @node Floating-Point Types and Representations
22207 @subsection Floating-Point Types and Representations
22208 @cindex Floating-Point types
22209
22210 @noindent
22211 The set of predefined floating-point types is identical in HP Ada and GNAT.
22212 Furthermore the representation of these floating-point
22213 types is also identical. One important difference is that the default
22214 representation for HP Ada is @code{VAX_Float}, but the default representation
22215 for GNAT is IEEE.
22216
22217 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
22218 pragma @code{Float_Representation} as described in the HP Ada
22219 documentation.
22220 For example, the declarations:
22221
22222 @smallexample @c ada
22223 @cartouche
22224 type F_Float is digits 6;
22225 pragma Float_Representation (VAX_Float, F_Float);
22226 @end cartouche
22227 @end smallexample
22228
22229 @noindent
22230 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
22231 format.
22232 This set of declarations actually appears in @code{System.Aux_DEC},
22233 which contains
22234 the full set of additional floating-point declarations provided in
22235 the HP Ada version of package @code{System}.
22236 This and similar declarations may be accessed in a user program
22237 by using pragma @code{Extend_System}. The use of this
22238 pragma, and the related pragma @code{Long_Float} is described in further
22239 detail in the following section.
22240
22241 @node Pragmas Float_Representation and Long_Float
22242 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
22243
22244 @noindent
22245 HP Ada provides the pragma @code{Float_Representation}, which
22246 acts as a program library switch to allow control over
22247 the internal representation chosen for the predefined
22248 floating-point types declared in the package @code{Standard}.
22249 The format of this pragma is as follows:
22250
22251 @smallexample @c ada
22252 @cartouche
22253 pragma Float_Representation(VAX_Float | IEEE_Float);
22254 @end cartouche
22255 @end smallexample
22256
22257 @noindent
22258 This pragma controls the representation of floating-point
22259 types as follows:
22260
22261 @itemize @bullet
22262 @item
22263 @code{VAX_Float} specifies that floating-point
22264 types are represented by default with the VAX system hardware types
22265 @code{F-floating}, @code{D-floating}, @code{G-floating}.
22266 Note that the @code{H-floating}
22267 type was available only on VAX systems, and is not available
22268 in either HP Ada or GNAT.
22269
22270 @item
22271 @code{IEEE_Float} specifies that floating-point
22272 types are represented by default with the IEEE single and
22273 double floating-point types.
22274 @end itemize
22275
22276 @noindent
22277 GNAT provides an identical implementation of the pragma
22278 @code{Float_Representation}, except that it functions as a
22279 configuration pragma. Note that the
22280 notion of configuration pragma corresponds closely to the
22281 HP Ada notion of a program library switch.
22282
22283 When no pragma is used in GNAT, the default is @code{IEEE_Float},
22284 which is different
22285 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
22286 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
22287 advisable to change the format of numbers passed to standard library
22288 routines, and if necessary explicit type conversions may be needed.
22289
22290 The use of @code{IEEE_Float} is recommended in GNAT since it is more
22291 efficient, and (given that it conforms to an international standard)
22292 potentially more portable.
22293 The situation in which @code{VAX_Float} may be useful is in interfacing
22294 to existing code and data that expect the use of @code{VAX_Float}.
22295 In such a situation use the predefined @code{VAX_Float}
22296 types in package @code{System}, as extended by
22297 @code{Extend_System}. For example, use @code{System.F_Float}
22298 to specify the 32-bit @code{F-Float} format.
22299
22300 @noindent
22301 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
22302 to allow control over the internal representation chosen
22303 for the predefined type @code{Long_Float} and for floating-point
22304 type declarations with digits specified in the range 7 .. 15.
22305 The format of this pragma is as follows:
22306
22307 @smallexample @c ada
22308 @cartouche
22309 pragma Long_Float (D_FLOAT | G_FLOAT);
22310 @end cartouche
22311 @end smallexample
22312
22313 @node Fixed-Point Types and Representations
22314 @subsection Fixed-Point Types and Representations
22315
22316 @noindent
22317 On HP Ada for OpenVMS Alpha systems, rounding is
22318 away from zero for both positive and negative numbers.
22319 Therefore, @code{+0.5} rounds to @code{1},
22320 and @code{-0.5} rounds to @code{-1}.
22321
22322 On GNAT the results of operations
22323 on fixed-point types are in accordance with the Ada
22324 rules. In particular, results of operations on decimal
22325 fixed-point types are truncated.
22326
22327 @node Record and Array Component Alignment
22328 @subsection Record and Array Component Alignment
22329
22330 @noindent
22331 On HP Ada for OpenVMS Alpha, all non-composite components
22332 are aligned on natural boundaries. For example, 1-byte
22333 components are aligned on byte boundaries, 2-byte
22334 components on 2-byte boundaries, 4-byte components on 4-byte
22335 byte boundaries, and so on. The OpenVMS Alpha hardware
22336 runs more efficiently with naturally aligned data.
22337
22338 On GNAT, alignment rules are compatible
22339 with HP Ada for OpenVMS Alpha.
22340
22341 @node Address Clauses
22342 @subsection Address Clauses
22343
22344 @noindent
22345 In HP Ada and GNAT, address clauses are supported for
22346 objects and imported subprograms.
22347 The predefined type @code{System.Address} is a private type
22348 in both compilers on Alpha OpenVMS, with the same representation
22349 (it is simply a machine pointer). Addition, subtraction, and comparison
22350 operations are available in the standard Ada package
22351 @code{System.Storage_Elements}, or in package @code{System}
22352 if it is extended to include @code{System.Aux_DEC} using a
22353 pragma @code{Extend_System} as previously described.
22354
22355 Note that code that @code{with}'s both this extended package @code{System}
22356 and the package @code{System.Storage_Elements} should not @code{use}
22357 both packages, or ambiguities will result. In general it is better
22358 not to mix these two sets of facilities. The Ada package was
22359 designed specifically to provide the kind of features that HP Ada
22360 adds directly to package @code{System}.
22361
22362 The type @code{System.Address} is a 64-bit integer type in GNAT for
22363 I64 OpenVMS.  For more information,
22364 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22365
22366 GNAT is compatible with HP Ada in its handling of address
22367 clauses, except for some limitations in
22368 the form of address clauses for composite objects with
22369 initialization. Such address clauses are easily replaced
22370 by the use of an explicitly-defined constant as described
22371 in the Ada Reference Manual (13.1(22)). For example, the sequence
22372 of declarations:
22373
22374 @smallexample @c ada
22375 @cartouche
22376 X, Y : Integer := Init_Func;
22377 Q : String (X .. Y) := "abc";
22378 @dots{}
22379 for Q'Address use Compute_Address;
22380 @end cartouche
22381 @end smallexample
22382
22383 @noindent
22384 will be rejected by GNAT, since the address cannot be computed at the time
22385 that @code{Q} is declared. To achieve the intended effect, write instead:
22386
22387 @smallexample @c ada
22388 @group
22389 @cartouche
22390 X, Y : Integer := Init_Func;
22391 Q_Address : constant Address := Compute_Address;
22392 Q : String (X .. Y) := "abc";
22393 @dots{}
22394 for Q'Address use Q_Address;
22395 @end cartouche
22396 @end group
22397 @end smallexample
22398
22399 @noindent
22400 which will be accepted by GNAT (and other Ada compilers), and is also
22401 compatible with Ada 83. A fuller description of the restrictions
22402 on address specifications is found in @ref{Top, GNAT Reference Manual,
22403 About This Guide, gnat_rm, GNAT Reference Manual}.
22404
22405 @node Other Representation Clauses
22406 @subsection Other Representation Clauses
22407
22408 @noindent
22409 GNAT implements in a compatible manner all the representation
22410 clauses supported by HP Ada. In addition, GNAT
22411 implements the representation clause forms that were introduced in Ada 95,
22412 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
22413
22414 @node The Package STANDARD
22415 @section The Package @code{STANDARD}
22416
22417 @noindent
22418 The package @code{STANDARD}, as implemented by HP Ada, is fully
22419 described in the @cite{Ada Reference Manual} and in the
22420 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
22421 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
22422
22423 In addition, HP Ada supports the Latin-1 character set in
22424 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
22425 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
22426 the type @code{WIDE_CHARACTER}.
22427
22428 The floating-point types supported by GNAT are those
22429 supported by HP Ada, but the defaults are different, and are controlled by
22430 pragmas. See @ref{Floating-Point Types and Representations}, for details.
22431
22432 @node The Package SYSTEM
22433 @section The Package @code{SYSTEM}
22434
22435 @noindent
22436 HP Ada provides a specific version of the package
22437 @code{SYSTEM} for each platform on which the language is implemented.
22438 For the complete spec of the package @code{SYSTEM}, see
22439 Appendix F of the @cite{HP Ada Language Reference Manual}.
22440
22441 On HP Ada, the package @code{SYSTEM} includes the following conversion
22442 functions:
22443 @itemize @bullet
22444 @item @code{TO_ADDRESS(INTEGER)}
22445
22446 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
22447
22448 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
22449
22450 @item @code{TO_INTEGER(ADDRESS)}
22451
22452 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
22453
22454 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
22455 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
22456 @end itemize
22457
22458 @noindent
22459 By default, GNAT supplies a version of @code{SYSTEM} that matches
22460 the definition given in the @cite{Ada Reference Manual}.
22461 This
22462 is a subset of the HP system definitions, which is as
22463 close as possible to the original definitions. The only difference
22464 is that the definition of @code{SYSTEM_NAME} is different:
22465
22466 @smallexample @c ada
22467 @cartouche
22468 type Name is (SYSTEM_NAME_GNAT);
22469 System_Name : constant Name := SYSTEM_NAME_GNAT;
22470 @end cartouche
22471 @end smallexample
22472
22473 @noindent
22474 Also, GNAT adds the Ada declarations for
22475 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
22476
22477 However, the use of the following pragma causes GNAT
22478 to extend the definition of package @code{SYSTEM} so that it
22479 encompasses the full set of HP-specific extensions,
22480 including the functions listed above:
22481
22482 @smallexample @c ada
22483 @cartouche
22484 pragma Extend_System (Aux_DEC);
22485 @end cartouche
22486 @end smallexample
22487
22488 @noindent
22489 The pragma @code{Extend_System} is a configuration pragma that
22490 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
22491 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
22492
22493 HP Ada does not allow the recompilation of the package
22494 @code{SYSTEM}. Instead HP Ada provides several pragmas
22495 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
22496 to modify values in the package @code{SYSTEM}.
22497 On OpenVMS Alpha systems, the pragma
22498 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
22499 its single argument.
22500
22501 GNAT does permit the recompilation of package @code{SYSTEM} using
22502 the special switch @option{-gnatg}, and this switch can be used if
22503 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
22504 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
22505 or @code{MEMORY_SIZE} by any other means.
22506
22507 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
22508 enumeration literal @code{SYSTEM_NAME_GNAT}.
22509
22510 The definitions provided by the use of
22511
22512 @smallexample @c ada
22513 pragma Extend_System (AUX_Dec);
22514 @end smallexample
22515
22516 @noindent
22517 are virtually identical to those provided by the HP Ada 83 package
22518 @code{SYSTEM}. One important difference is that the name of the
22519 @code{TO_ADDRESS}
22520 function for type @code{UNSIGNED_LONGWORD} is changed to
22521 @code{TO_ADDRESS_LONG}.
22522 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
22523 discussion of why this change was necessary.
22524
22525 @noindent
22526 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
22527 is in fact
22528 an extension to Ada 83 not strictly compatible with the reference manual.
22529 GNAT, in order to be exactly compatible with the standard,
22530 does not provide this capability. In HP Ada 83, the
22531 point of this definition is to deal with a call like:
22532
22533 @smallexample @c ada
22534 TO_ADDRESS (16#12777#);
22535 @end smallexample
22536
22537 @noindent
22538 Normally, according to Ada 83 semantics, one would expect this to be
22539 ambiguous, since it matches both the @code{INTEGER} and
22540 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
22541 However, in HP Ada 83, there is no ambiguity, since the
22542 definition using @i{universal_integer} takes precedence.
22543
22544 In GNAT, since the version with @i{universal_integer} cannot be supplied,
22545 it is
22546 not possible to be 100% compatible. Since there are many programs using
22547 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
22548 GNAT was
22549 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
22550 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
22551
22552 @smallexample @c ada
22553 function To_Address (X : Integer) return Address;
22554 pragma Pure_Function (To_Address);
22555
22556 function To_Address_Long (X : Unsigned_Longword) return Address;
22557 pragma Pure_Function (To_Address_Long);
22558 @end smallexample
22559
22560 @noindent
22561 This means that programs using @code{TO_ADDRESS} for
22562 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
22563
22564 @node Tasking and Task-Related Features
22565 @section Tasking and Task-Related Features
22566
22567 @noindent
22568 This section compares the treatment of tasking in GNAT
22569 and in HP Ada for OpenVMS Alpha.
22570 The GNAT description applies to both Alpha and I64 OpenVMS.
22571 For detailed information on tasking in
22572 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
22573 relevant run-time reference manual.
22574
22575 @menu
22576 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
22577 * Assigning Task IDs::
22578 * Task IDs and Delays::
22579 * Task-Related Pragmas::
22580 * Scheduling and Task Priority::
22581 * The Task Stack::
22582 * External Interrupts::
22583 @end menu
22584
22585 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22586 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22587
22588 @noindent
22589 On OpenVMS Alpha systems, each Ada task (except a passive
22590 task) is implemented as a single stream of execution
22591 that is created and managed by the kernel. On these
22592 systems, HP Ada tasking support is based on DECthreads,
22593 an implementation of the POSIX standard for threads.
22594
22595 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
22596 code that calls DECthreads routines can be used together.
22597 The interaction between Ada tasks and DECthreads routines
22598 can have some benefits. For example when on OpenVMS Alpha,
22599 HP Ada can call C code that is already threaded.
22600
22601 GNAT uses the facilities of DECthreads,
22602 and Ada tasks are mapped to threads.
22603
22604 @node Assigning Task IDs
22605 @subsection Assigning Task IDs
22606
22607 @noindent
22608 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
22609 the environment task that executes the main program. On
22610 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
22611 that have been created but are not yet activated.
22612
22613 On OpenVMS Alpha systems, task IDs are assigned at
22614 activation. On GNAT systems, task IDs are also assigned at
22615 task creation but do not have the same form or values as
22616 task ID values in HP Ada. There is no null task, and the
22617 environment task does not have a specific task ID value.
22618
22619 @node Task IDs and Delays
22620 @subsection Task IDs and Delays
22621
22622 @noindent
22623 On OpenVMS Alpha systems, tasking delays are implemented
22624 using Timer System Services. The Task ID is used for the
22625 identification of the timer request (the @code{REQIDT} parameter).
22626 If Timers are used in the application take care not to use
22627 @code{0} for the identification, because cancelling such a timer
22628 will cancel all timers and may lead to unpredictable results.
22629
22630 @node Task-Related Pragmas
22631 @subsection Task-Related Pragmas
22632
22633 @noindent
22634 Ada supplies the pragma @code{TASK_STORAGE}, which allows
22635 specification of the size of the guard area for a task
22636 stack. (The guard area forms an area of memory that has no
22637 read or write access and thus helps in the detection of
22638 stack overflow.) On OpenVMS Alpha systems, if the pragma
22639 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
22640 area is created. In the absence of a pragma @code{TASK_STORAGE},
22641 a default guard area is created.
22642
22643 GNAT supplies the following task-related pragmas:
22644
22645 @itemize @bullet
22646 @item  @code{TASK_INFO}
22647
22648 This pragma appears within a task definition and
22649 applies to the task in which it appears. The argument
22650 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
22651
22652 @item  @code{TASK_STORAGE}
22653
22654 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
22655 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
22656 @code{SUPPRESS}, and @code{VOLATILE}.
22657 @end itemize
22658 @node Scheduling and Task Priority
22659 @subsection Scheduling and Task Priority
22660
22661 @noindent
22662 HP Ada implements the Ada language requirement that
22663 when two tasks are eligible for execution and they have
22664 different priorities, the lower priority task does not
22665 execute while the higher priority task is waiting. The HP
22666 Ada Run-Time Library keeps a task running until either the
22667 task is suspended or a higher priority task becomes ready.
22668
22669 On OpenVMS Alpha systems, the default strategy is round-
22670 robin with preemption. Tasks of equal priority take turns
22671 at the processor. A task is run for a certain period of
22672 time and then placed at the tail of the ready queue for
22673 its priority level.
22674
22675 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
22676 which can be used to enable or disable round-robin
22677 scheduling of tasks with the same priority.
22678 See the relevant HP Ada run-time reference manual for
22679 information on using the pragmas to control HP Ada task
22680 scheduling.
22681
22682 GNAT follows the scheduling rules of Annex D (Real-Time
22683 Annex) of the @cite{Ada Reference Manual}. In general, this
22684 scheduling strategy is fully compatible with HP Ada
22685 although it provides some additional constraints (as
22686 fully documented in Annex D).
22687 GNAT implements time slicing control in a manner compatible with
22688 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
22689 are identical to the HP Ada 83 pragma of the same name.
22690 Note that it is not possible to mix GNAT tasking and
22691 HP Ada 83 tasking in the same program, since the two run-time
22692 libraries are not compatible.
22693
22694 @node The Task Stack
22695 @subsection The Task Stack
22696
22697 @noindent
22698 In HP Ada, a task stack is allocated each time a
22699 non-passive task is activated. As soon as the task is
22700 terminated, the storage for the task stack is deallocated.
22701 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
22702 a default stack size is used. Also, regardless of the size
22703 specified, some additional space is allocated for task
22704 management purposes. On OpenVMS Alpha systems, at least
22705 one page is allocated.
22706
22707 GNAT handles task stacks in a similar manner. In accordance with
22708 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
22709 an alternative method for controlling the task stack size.
22710 The specification of the attribute @code{T'STORAGE_SIZE} is also
22711 supported in a manner compatible with HP Ada.
22712
22713 @node External Interrupts
22714 @subsection External Interrupts
22715
22716 @noindent
22717 On HP Ada, external interrupts can be associated with task entries.
22718 GNAT is compatible with HP Ada in its handling of external interrupts.
22719
22720 @node Pragmas and Pragma-Related Features
22721 @section Pragmas and Pragma-Related Features
22722
22723 @noindent
22724 Both HP Ada and GNAT supply all language-defined pragmas
22725 as specified by the Ada 83 standard. GNAT also supplies all
22726 language-defined pragmas introduced by Ada 95 and Ada 2005.
22727 In addition, GNAT implements the implementation-defined pragmas
22728 from HP Ada 83.
22729
22730 @itemize @bullet
22731 @item  @code{AST_ENTRY}
22732
22733 @item  @code{COMMON_OBJECT}
22734
22735 @item  @code{COMPONENT_ALIGNMENT}
22736
22737 @item  @code{EXPORT_EXCEPTION}
22738
22739 @item  @code{EXPORT_FUNCTION}
22740
22741 @item  @code{EXPORT_OBJECT}
22742
22743 @item  @code{EXPORT_PROCEDURE}
22744
22745 @item  @code{EXPORT_VALUED_PROCEDURE}
22746
22747 @item  @code{FLOAT_REPRESENTATION}
22748
22749 @item  @code{IDENT}
22750
22751 @item  @code{IMPORT_EXCEPTION}
22752
22753 @item  @code{IMPORT_FUNCTION}
22754
22755 @item  @code{IMPORT_OBJECT}
22756
22757 @item  @code{IMPORT_PROCEDURE}
22758
22759 @item  @code{IMPORT_VALUED_PROCEDURE}
22760
22761 @item  @code{INLINE_GENERIC}
22762
22763 @item  @code{INTERFACE_NAME}
22764
22765 @item  @code{LONG_FLOAT}
22766
22767 @item  @code{MAIN_STORAGE}
22768
22769 @item  @code{PASSIVE}
22770
22771 @item  @code{PSECT_OBJECT}
22772
22773 @item  @code{SHARE_GENERIC}
22774
22775 @item  @code{SUPPRESS_ALL}
22776
22777 @item  @code{TASK_STORAGE}
22778
22779 @item  @code{TIME_SLICE}
22780
22781 @item  @code{TITLE}
22782 @end itemize
22783
22784 @noindent
22785 These pragmas are all fully implemented, with the exception of @code{TITLE},
22786 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
22787 recognized, but which have no
22788 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
22789 use of Ada protected objects. In GNAT, all generics are inlined.
22790
22791 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
22792 a separate subprogram specification which must appear before the
22793 subprogram body.
22794
22795 GNAT also supplies a number of implementation-defined pragmas including the
22796 following:
22797
22798 @itemize @bullet
22799 @item  @code{ABORT_DEFER}
22800
22801 @item  @code{ADA_83}
22802
22803 @item  @code{ADA_95}
22804
22805 @item  @code{ADA_05}
22806
22807 @item  @code{Ada_2005}
22808
22809 @item  @code{Ada_12}
22810
22811 @item  @code{Ada_2012}
22812
22813 @item  @code{ANNOTATE}
22814
22815 @item  @code{ASSERT}
22816
22817 @item  @code{C_PASS_BY_COPY}
22818
22819 @item  @code{CPP_CLASS}
22820
22821 @item  @code{CPP_CONSTRUCTOR}
22822
22823 @item  @code{CPP_DESTRUCTOR}
22824
22825 @item  @code{DEBUG}
22826
22827 @item  @code{EXTEND_SYSTEM}
22828
22829 @item  @code{LINKER_ALIAS}
22830
22831 @item  @code{LINKER_SECTION}
22832
22833 @item  @code{MACHINE_ATTRIBUTE}
22834
22835 @item  @code{NO_RETURN}
22836
22837 @item  @code{PURE_FUNCTION}
22838
22839 @item  @code{SOURCE_FILE_NAME}
22840
22841 @item  @code{SOURCE_REFERENCE}
22842
22843 @item  @code{TASK_INFO}
22844
22845 @item  @code{UNCHECKED_UNION}
22846
22847 @item  @code{UNIMPLEMENTED_UNIT}
22848
22849 @item  @code{UNIVERSAL_DATA}
22850
22851 @item  @code{UNSUPPRESS}
22852
22853 @item  @code{WARNINGS}
22854
22855 @item  @code{WEAK_EXTERNAL}
22856 @end itemize
22857
22858 @noindent
22859 For full details on these and other GNAT implementation-defined pragmas,
22860 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
22861 Manual}.
22862
22863 @menu
22864 * Restrictions on the Pragma INLINE::
22865 * Restrictions on the Pragma INTERFACE::
22866 * Restrictions on the Pragma SYSTEM_NAME::
22867 @end menu
22868
22869 @node Restrictions on the Pragma INLINE
22870 @subsection Restrictions on Pragma @code{INLINE}
22871
22872 @noindent
22873 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
22874 @itemize @bullet
22875 @item  Parameters cannot have a task type.
22876
22877 @item  Function results cannot be task types, unconstrained
22878 array types, or unconstrained types with discriminants.
22879
22880 @item  Bodies cannot declare the following:
22881 @itemize @bullet
22882 @item  Subprogram body or stub (imported subprogram is allowed)
22883
22884 @item  Tasks
22885
22886 @item  Generic declarations
22887
22888 @item  Instantiations
22889
22890 @item  Exceptions
22891
22892 @item  Access types (types derived from access types allowed)
22893
22894 @item  Array or record types
22895
22896 @item  Dependent tasks
22897
22898 @item  Direct recursive calls of subprogram or containing
22899 subprogram, directly or via a renaming
22900
22901 @end itemize
22902 @end itemize
22903
22904 @noindent
22905 In GNAT, the only restriction on pragma @code{INLINE} is that the
22906 body must occur before the call if both are in the same
22907 unit, and the size must be appropriately small. There are
22908 no other specific restrictions which cause subprograms to
22909 be incapable of being inlined.
22910
22911 @node  Restrictions on the Pragma INTERFACE
22912 @subsection  Restrictions on Pragma @code{INTERFACE}
22913
22914 @noindent
22915 The following restrictions on pragma @code{INTERFACE}
22916 are enforced by both HP Ada and GNAT:
22917 @itemize @bullet
22918 @item  Languages accepted: Ada, Bliss, C, Fortran, Default.
22919 Default is the default on OpenVMS Alpha systems.
22920
22921 @item  Parameter passing: Language specifies default
22922 mechanisms but can be overridden with an @code{EXPORT} pragma.
22923
22924 @itemize @bullet
22925 @item  Ada: Use internal Ada rules.
22926
22927 @item  Bliss, C: Parameters must be mode @code{in}; cannot be
22928 record or task type. Result cannot be a string, an
22929 array, or a record.
22930
22931 @item  Fortran: Parameters cannot have a task type. Result cannot
22932 be a string, an array, or a record.
22933 @end itemize
22934 @end itemize
22935
22936 @noindent
22937 GNAT is entirely upwards compatible with HP Ada, and in addition allows
22938 record parameters for all languages.
22939
22940 @node  Restrictions on the Pragma SYSTEM_NAME
22941 @subsection  Restrictions on Pragma @code{SYSTEM_NAME}
22942
22943 @noindent
22944 For HP Ada for OpenVMS Alpha, the enumeration literal
22945 for the type @code{NAME} is @code{OPENVMS_AXP}.
22946 In GNAT, the enumeration
22947 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
22948
22949 @node  Library of Predefined Units
22950 @section  Library of Predefined Units
22951
22952 @noindent
22953 A library of predefined units is provided as part of the
22954 HP Ada and GNAT implementations. HP Ada does not provide
22955 the package @code{MACHINE_CODE} but instead recommends importing
22956 assembler code.
22957
22958 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
22959 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
22960 version.
22961 The HP Ada Predefined Library units are modified to remove post-Ada 83
22962 incompatibilities and to make them interoperable with GNAT
22963 (@pxref{Changes to DECLIB}, for details).
22964 The units are located in the @file{DECLIB} directory.
22965
22966 The GNAT RTL is contained in
22967 the @file{ADALIB} directory, and
22968 the default search path is set up to find @code{DECLIB} units in preference
22969 to @code{ADALIB} units with the same name (@code{TEXT_IO},
22970 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
22971
22972 @menu
22973 * Changes to DECLIB::
22974 @end menu
22975
22976 @node Changes to DECLIB
22977 @subsection Changes to @code{DECLIB}
22978
22979 @noindent
22980 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
22981 compatibility are minor and include the following:
22982
22983 @itemize @bullet
22984 @item  Adjusting the location of pragmas and record representation
22985 clauses to obey Ada 95 (and thus Ada 2005) rules
22986
22987 @item  Adding the proper notation to generic formal parameters
22988 that take unconstrained types in instantiation
22989
22990 @item  Adding pragma @code{ELABORATE_BODY} to package specs
22991 that have package bodies not otherwise allowed
22992
22993 @item  Replacing occurrences of the identifier ``@code{PROTECTED}'' by
22994 ``@code{PROTECTD}''.
22995 Currently these are found only in the @code{STARLET} package spec.
22996
22997 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
22998 where the address size is constrained to 32 bits.
22999 @end itemize
23000
23001 @noindent
23002 None of the above changes is visible to users.
23003
23004 @node Bindings
23005 @section Bindings
23006
23007 @noindent
23008 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
23009 @itemize @bullet
23010
23011 @item  Command Language Interpreter (CLI interface)
23012
23013 @item  DECtalk Run-Time Library (DTK interface)
23014
23015 @item  Librarian utility routines (LBR interface)
23016
23017 @item  General Purpose Run-Time Library (LIB interface)
23018
23019 @item  Math Run-Time Library (MTH interface)
23020
23021 @item  National Character Set Run-Time Library (NCS interface)
23022
23023 @item  Compiled Code Support Run-Time Library (OTS interface)
23024
23025 @item  Parallel Processing Run-Time Library (PPL interface)
23026
23027 @item  Screen Management Run-Time Library (SMG interface)
23028
23029 @item  Sort Run-Time Library (SOR interface)
23030
23031 @item  String Run-Time Library (STR interface)
23032
23033 @item STARLET System Library
23034 @findex Starlet
23035
23036 @item  X Window System Version 11R4 and 11R5 (X, XLIB interface)
23037
23038 @item  X Windows Toolkit (XT interface)
23039
23040 @item  X/Motif Version 1.1.3 and 1.2 (XM interface)
23041 @end itemize
23042
23043 @noindent
23044 GNAT provides implementations of these HP bindings in the @code{DECLIB}
23045 directory, on both the Alpha and I64 OpenVMS platforms.
23046
23047 The X components of DECLIB compatibility package are located in a separate
23048 library, called XDECGNAT, which is not linked with by default; this library
23049 must be explicitly linked with any application that makes use of any X facilities,
23050 with a command similar to
23051
23052 @code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
23053
23054 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
23055 in the
23056 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
23057 A pragma @code{Linker_Options} has been added to packages @code{Xm},
23058 @code{Xt}, and @code{X_Lib}
23059 causing the default X/Motif sharable image libraries to be linked in. This
23060 is done via options files named @file{xm.opt}, @file{xt.opt}, and
23061 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
23062
23063 It may be necessary to edit these options files to update or correct the
23064 library names if, for example, the newer X/Motif bindings from
23065 @file{ADA$EXAMPLES}
23066 had been (previous to installing GNAT) copied and renamed to supersede the
23067 default @file{ADA$PREDEFINED} versions.
23068
23069 @menu
23070 * Shared Libraries and Options Files::
23071 * Interfaces to C::
23072 @end menu
23073
23074 @node Shared Libraries and Options Files
23075 @subsection Shared Libraries and Options Files
23076
23077 @noindent
23078 When using the HP Ada
23079 predefined X and Motif bindings, the linking with their sharable images is
23080 done automatically by @command{GNAT LINK}.
23081 When using other X and Motif bindings, you need
23082 to add the corresponding sharable images to the command line for
23083 @code{GNAT LINK}. When linking with shared libraries, or with
23084 @file{.OPT} files, you must
23085 also add them to the command line for @command{GNAT LINK}.
23086
23087 A shared library to be used with GNAT is built in the same way as other
23088 libraries under VMS. The VMS Link command can be used in standard fashion.
23089
23090 @node Interfaces to C
23091 @subsection Interfaces to C
23092
23093 @noindent
23094 HP Ada
23095 provides the following Ada types and operations:
23096
23097 @itemize @bullet
23098 @item C types package (@code{C_TYPES})
23099
23100 @item C strings (@code{C_TYPES.NULL_TERMINATED})
23101
23102 @item Other_types (@code{SHORT_INT})
23103 @end itemize
23104
23105 @noindent
23106 Interfacing to C with GNAT, you can use the above approach
23107 described for HP Ada or the facilities of Annex B of
23108 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
23109 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
23110 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
23111
23112 The @option{-gnatF} qualifier forces default and explicit
23113 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
23114 to be uppercased for compatibility with the default behavior
23115 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
23116
23117 @node Main Program Definition
23118 @section Main Program Definition
23119
23120 @noindent
23121 The following section discusses differences in the
23122 definition of main programs on HP Ada and GNAT.
23123 On HP Ada, main programs are defined to meet the
23124 following conditions:
23125 @itemize @bullet
23126 @item  Procedure with no formal parameters (returns @code{0} upon
23127 normal completion)
23128
23129 @item  Procedure with no formal parameters (returns @code{42} when
23130 an unhandled exception is raised)
23131
23132 @item  Function with no formal parameters whose returned value
23133 is of a discrete type
23134
23135 @item  Procedure with one @code{out} formal of a discrete type for
23136 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
23137
23138 @end itemize
23139
23140 @noindent
23141 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
23142 a main function or main procedure returns a discrete
23143 value whose size is less than 64 bits (32 on VAX systems),
23144 the value is zero- or sign-extended as appropriate.
23145 On GNAT, main programs are defined as follows:
23146 @itemize @bullet
23147 @item  Must be a non-generic, parameterless subprogram that
23148 is either a procedure or function returning an Ada
23149 @code{STANDARD.INTEGER} (the predefined type)
23150
23151 @item  Cannot be a generic subprogram or an instantiation of a
23152 generic subprogram
23153 @end itemize
23154
23155 @node Implementation-Defined Attributes
23156 @section Implementation-Defined Attributes
23157
23158 @noindent
23159 GNAT provides all HP Ada implementation-defined
23160 attributes.
23161
23162 @node Compiler and Run-Time Interfacing
23163 @section Compiler and Run-Time Interfacing
23164
23165 @noindent
23166 HP Ada provides the following qualifiers to pass options to the linker
23167 (ACS LINK):
23168 @itemize @bullet
23169 @item  @option{/WAIT} and @option{/SUBMIT}
23170
23171 @item  @option{/COMMAND}
23172
23173 @item  @option{/@r{[}NO@r{]}MAP}
23174
23175 @item  @option{/OUTPUT=@var{file-spec}}
23176
23177 @item  @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
23178 @end itemize
23179
23180 @noindent
23181 To pass options to the linker, GNAT provides the following
23182 switches:
23183
23184 @itemize @bullet
23185 @item   @option{/EXECUTABLE=@var{exec-name}}
23186
23187 @item   @option{/VERBOSE}
23188
23189 @item   @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
23190 @end itemize
23191
23192 @noindent
23193 For more information on these switches, see
23194 @ref{Switches for gnatlink}.
23195 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
23196 to control optimization. HP Ada also supplies the
23197 following pragmas:
23198 @itemize @bullet
23199 @item  @code{OPTIMIZE}
23200
23201 @item  @code{INLINE}
23202
23203 @item  @code{INLINE_GENERIC}
23204
23205 @item  @code{SUPPRESS_ALL}
23206
23207 @item  @code{PASSIVE}
23208 @end itemize
23209
23210 @noindent
23211 In GNAT, optimization is controlled strictly by command
23212 line parameters, as described in the corresponding section of this guide.
23213 The HP pragmas for control of optimization are
23214 recognized but ignored.
23215
23216 Note that in GNAT, the default is optimization off, whereas in HP Ada
23217 the default is that optimization is turned on.
23218
23219 @node Program Compilation and Library Management
23220 @section Program Compilation and Library Management
23221
23222 @noindent
23223 HP Ada and GNAT provide a comparable set of commands to
23224 build programs. HP Ada also provides a program library,
23225 which is a concept that does not exist on GNAT. Instead,
23226 GNAT provides directories of sources that are compiled as
23227 needed.
23228
23229 The following table summarizes
23230 the HP Ada commands and provides
23231 equivalent GNAT commands. In this table, some GNAT
23232 equivalents reflect the fact that GNAT does not use the
23233 concept of a program library. Instead, it uses a model
23234 in which collections of source and object files are used
23235 in a manner consistent with other languages like C and
23236 Fortran. Therefore, standard system file commands are used
23237 to manipulate these elements. Those GNAT commands are marked with
23238 an asterisk.
23239 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
23240
23241 @need 1500
23242 @multitable @columnfractions .35 .65
23243
23244 @item @emph{HP Ada Command}
23245 @tab @emph{GNAT Equivalent / Description}
23246
23247 @item @command{ADA}
23248 @tab @command{GNAT COMPILE}@*
23249 Invokes the compiler to compile one or more Ada source files.
23250
23251 @item @command{ACS ATTACH}@*
23252 @tab [No equivalent]@*
23253 Switches control of terminal from current process running the program
23254 library manager.
23255
23256 @item @command{ACS CHECK}
23257 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
23258 Forms the execution closure of one
23259 or more compiled units and checks completeness and currency.
23260
23261 @item @command{ACS COMPILE}
23262 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23263 Forms the execution closure of one or
23264 more specified units, checks completeness and currency,
23265 identifies units that have revised source files, compiles same,
23266 and recompiles units that are or will become obsolete.
23267 Also completes incomplete generic instantiations.
23268
23269 @item @command{ACS COPY FOREIGN}
23270 @tab Copy (*)@*
23271 Copies a foreign object file into the program library as a
23272 library unit body.
23273
23274 @item @command{ACS COPY UNIT}
23275 @tab Copy (*)@*
23276 Copies a compiled unit from one program library to another.
23277
23278 @item @command{ACS CREATE LIBRARY}
23279 @tab Create /directory (*)@*
23280 Creates a program library.
23281
23282 @item @command{ACS CREATE SUBLIBRARY}
23283 @tab Create /directory (*)@*
23284 Creates a program sublibrary.
23285
23286 @item @command{ACS DELETE LIBRARY}
23287 @tab @*
23288 Deletes a program library and its contents.
23289
23290 @item @command{ACS DELETE SUBLIBRARY}
23291 @tab @*
23292 Deletes a program sublibrary and its contents.
23293
23294 @item @command{ACS DELETE UNIT}
23295 @tab Delete file (*)@*
23296 On OpenVMS systems, deletes one or more compiled units from
23297 the current program library.
23298
23299 @item @command{ACS DIRECTORY}
23300 @tab Directory (*)@*
23301 On OpenVMS systems, lists units contained in the current
23302 program library.
23303
23304 @item @command{ACS ENTER FOREIGN}
23305 @tab Copy (*)@*
23306 Allows the import of a foreign body as an Ada library
23307 spec and enters a reference to a pointer.
23308
23309 @item @command{ACS ENTER UNIT}
23310 @tab Copy (*)@*
23311 Enters a reference (pointer) from the current program library to
23312 a unit compiled into another program library.
23313
23314 @item @command{ACS EXIT}
23315 @tab [No equivalent]@*
23316 Exits from the program library manager.
23317
23318 @item @command{ACS EXPORT}
23319 @tab Copy (*)@*
23320 Creates an object file that contains system-specific object code
23321 for one or more units. With GNAT, object files can simply be copied
23322 into the desired directory.
23323
23324 @item @command{ACS EXTRACT SOURCE}
23325 @tab Copy (*)@*
23326 Allows access to the copied source file for each Ada compilation unit
23327
23328 @item @command{ACS HELP}
23329 @tab @command{HELP GNAT}@*
23330 Provides online help.
23331
23332 @item @command{ACS LINK}
23333 @tab @command{GNAT LINK}@*
23334 Links an object file containing Ada units into an executable file.
23335
23336 @item @command{ACS LOAD}
23337 @tab Copy (*)@*
23338 Loads (partially compiles) Ada units into the program library.
23339 Allows loading a program from a collection of files into a library
23340 without knowing the relationship among units.
23341
23342 @item @command{ACS MERGE}
23343 @tab Copy (*)@*
23344 Merges into the current program library, one or more units from
23345 another library where they were modified.
23346
23347 @item @command{ACS RECOMPILE}
23348 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23349 Recompiles from   external or copied source files any obsolete
23350 unit in the closure. Also, completes any incomplete generic
23351 instantiations.
23352
23353 @item @command{ACS REENTER}
23354 @tab @command{GNAT MAKE}@*
23355 Reenters current references to units compiled after last entered
23356 with the @command{ACS ENTER UNIT} command.
23357
23358 @item @command{ACS SET LIBRARY}
23359 @tab Set default (*)@*
23360 Defines a program library to be the compilation context as well
23361 as the target library for compiler output and commands in general.
23362
23363 @item @command{ACS SET PRAGMA}
23364 @tab Edit @file{gnat.adc} (*)@*
23365 Redefines specified  values of the library characteristics
23366 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
23367 and @code{Float_Representation}.
23368
23369 @item @command{ACS SET SOURCE}
23370 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
23371 Defines the source file search list for the @command{ACS COMPILE} command.
23372
23373 @item @command{ACS SHOW LIBRARY}
23374 @tab Directory (*)@*
23375 Lists information about one or more program libraries.
23376
23377 @item @command{ACS SHOW PROGRAM}
23378 @tab [No equivalent]@*
23379 Lists information about the execution closure of one or
23380 more units in the program library.
23381
23382 @item @command{ACS SHOW SOURCE}
23383 @tab Show logical @code{ADA_INCLUDE_PATH}@*
23384 Shows the source file search used when compiling units.
23385
23386 @item @command{ACS SHOW VERSION}
23387 @tab Compile with @option{VERBOSE} option
23388 Displays the version number of the compiler and program library
23389 manager used.
23390
23391 @item @command{ACS SPAWN}
23392 @tab [No equivalent]@*
23393 Creates a subprocess of the current process (same as @command{DCL SPAWN}
23394 command).
23395
23396 @item @command{ACS VERIFY}
23397 @tab [No equivalent]@*
23398 Performs a series of consistency checks on a program library to
23399 determine whether the library structure and library files are in
23400 valid form.
23401 @end multitable
23402
23403 @noindent
23404
23405 @node Input-Output
23406 @section Input-Output
23407
23408 @noindent
23409 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
23410 Management Services (RMS) to perform operations on
23411 external files.
23412
23413 @noindent
23414 HP Ada and GNAT predefine an identical set of input-
23415 output packages. To make the use of the
23416 generic @code{TEXT_IO} operations more convenient, HP Ada
23417 provides predefined library packages that instantiate the
23418 integer and floating-point operations for the predefined
23419 integer and floating-point types as shown in the following table.
23420
23421 @multitable @columnfractions .45 .55
23422 @item @emph{Package Name} @tab Instantiation
23423
23424 @item @code{INTEGER_TEXT_IO}
23425 @tab @code{INTEGER_IO(INTEGER)}
23426
23427 @item @code{SHORT_INTEGER_TEXT_IO}
23428 @tab @code{INTEGER_IO(SHORT_INTEGER)}
23429
23430 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
23431 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
23432
23433 @item @code{FLOAT_TEXT_IO}
23434 @tab @code{FLOAT_IO(FLOAT)}
23435
23436 @item @code{LONG_FLOAT_TEXT_IO}
23437 @tab @code{FLOAT_IO(LONG_FLOAT)}
23438 @end multitable
23439
23440 @noindent
23441 The HP Ada predefined packages and their operations
23442 are implemented using OpenVMS Alpha files and input-output
23443 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
23444 Familiarity with the following is recommended:
23445 @itemize @bullet
23446 @item  RMS file organizations and access methods
23447
23448 @item  OpenVMS file specifications and directories
23449
23450 @item  OpenVMS File Definition Language (FDL)
23451 @end itemize
23452
23453 @noindent
23454 GNAT provides I/O facilities that are completely
23455 compatible with HP Ada. The distribution includes the
23456 standard HP Ada versions of all I/O packages, operating
23457 in a manner compatible with HP Ada. In particular, the
23458 following packages are by default the HP Ada (Ada 83)
23459 versions of these packages rather than the renamings
23460 suggested in Annex J of the Ada Reference Manual:
23461 @itemize @bullet
23462 @item  @code{TEXT_IO}
23463
23464 @item  @code{SEQUENTIAL_IO}
23465
23466 @item  @code{DIRECT_IO}
23467 @end itemize
23468
23469 @noindent
23470 The use of the standard child package syntax (for
23471 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
23472 packages.
23473 GNAT provides HP-compatible predefined instantiations
23474 of the @code{TEXT_IO} packages, and also
23475 provides the standard predefined instantiations required
23476 by the @cite{Ada Reference Manual}.
23477
23478 For further information on how GNAT interfaces to the file
23479 system or how I/O is implemented in programs written in
23480 mixed languages, see @ref{Implementation of the Standard I/O,,,
23481 gnat_rm, GNAT Reference Manual}.
23482 This chapter covers the following:
23483 @itemize @bullet
23484 @item  Standard I/O packages
23485
23486 @item  @code{FORM} strings
23487
23488 @item  @code{ADA.DIRECT_IO}
23489
23490 @item  @code{ADA.SEQUENTIAL_IO}
23491
23492 @item  @code{ADA.TEXT_IO}
23493
23494 @item  Stream pointer positioning
23495
23496 @item  Reading and writing non-regular files
23497
23498 @item  @code{GET_IMMEDIATE}
23499
23500 @item  Treating @code{TEXT_IO} files as streams
23501
23502 @item  Shared files
23503
23504 @item  Open modes
23505 @end itemize
23506
23507 @node Implementation Limits
23508 @section Implementation Limits
23509
23510 @noindent
23511 The following table lists implementation limits for HP Ada
23512 and GNAT systems.
23513 @multitable @columnfractions .60 .20 .20
23514 @sp 1
23515 @item  @emph{Compilation Parameter}
23516 @tab   @emph{HP Ada}
23517 @tab   @emph{GNAT}
23518 @sp 1
23519
23520 @item  In a subprogram or entry  declaration, maximum number of
23521 formal parameters that are of an unconstrained record type
23522 @tab   32
23523 @tab   No set limit
23524 @sp 1
23525
23526 @item  Maximum identifier length (number of characters)
23527 @tab   255
23528 @tab   32766
23529 @sp 1
23530
23531 @item  Maximum number of characters in a source line
23532 @tab   255
23533 @tab   32766
23534 @sp 1
23535
23536 @item  Maximum collection size   (number of bytes)
23537 @tab   2**31-1
23538 @tab   2**31-1
23539 @sp 1
23540
23541 @item  Maximum number of discriminants for a record type
23542 @tab   245
23543 @tab   No set limit
23544 @sp 1
23545
23546 @item  Maximum number of formal parameters in an entry or
23547 subprogram declaration
23548 @tab   246
23549 @tab    No set limit
23550 @sp 1
23551
23552 @item  Maximum number of dimensions in an array type
23553 @tab   255
23554 @tab   No set limit
23555 @sp 1
23556
23557 @item  Maximum number of library  units and subunits in a compilation.
23558 @tab   4095
23559 @tab   No set limit
23560 @sp 1
23561
23562 @item  Maximum number of library units and subunits in an execution.
23563 @tab   16383
23564 @tab   No set limit
23565 @sp 1
23566
23567 @item  Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
23568 or @code{PSECT_OBJECT}
23569 @tab   32757
23570 @tab   No set limit
23571 @sp 1
23572
23573 @item  Maximum number of enumeration literals in an enumeration type
23574 definition
23575 @tab   65535
23576 @tab   No set limit
23577 @sp 1
23578
23579 @item  Maximum number of lines in a source file
23580 @tab   65534
23581 @tab   No set limit
23582 @sp 1
23583
23584 @item  Maximum number of bits in any object
23585 @tab   2**31-1
23586 @tab   2**31-1
23587 @sp 1
23588
23589 @item  Maximum size of the static portion of a stack frame (approximate)
23590 @tab   2**31-1
23591 @tab   2**31-1
23592 @end multitable
23593
23594 @node Tools and Utilities
23595 @section Tools and Utilities
23596
23597 @noindent
23598 The following table lists some of the OpenVMS development tools
23599 available for HP Ada, and the corresponding tools for
23600 use with @value{EDITION} on Alpha and I64 platforms.
23601 Aside from the debugger, all the OpenVMS tools identified are part
23602 of the DECset package.
23603
23604 @iftex
23605 @c Specify table in TeX since Texinfo does a poor job
23606 @tex
23607 \smallskip
23608 \smallskip
23609 \settabs\+Language-Sensitive Editor\quad
23610    &Product with HP Ada\quad
23611    &\cr
23612 \+\it Tool
23613    &\it Product with HP Ada
23614    & \it Product with @value{EDITION}\cr
23615 \smallskip
23616 \+Code Management System
23617    &HP CMS
23618    & HP CMS\cr
23619 \smallskip
23620 \+Language-Sensitive Editor
23621    &HP LSE
23622    & emacs or HP LSE (Alpha)\cr
23623 \+
23624    &
23625    & HP LSE (I64)\cr
23626 \smallskip
23627 \+Debugger
23628    &OpenVMS Debug
23629    & gdb (Alpha),\cr
23630 \+
23631    &
23632    & OpenVMS Debug (I64)\cr
23633 \smallskip
23634 \+Source Code Analyzer /
23635    &HP SCA
23636    & GNAT XREF\cr
23637 \+Cross Referencer
23638    &
23639    &\cr
23640 \smallskip
23641 \+Test Manager
23642    &HP Digital Test
23643    & HP DTM\cr
23644 \+
23645    &Manager (DTM)
23646    &\cr
23647 \smallskip
23648 \+Performance and
23649    & HP PCA
23650    & HP PCA\cr
23651 \+Coverage Analyzer
23652    &
23653    &\cr
23654 \smallskip
23655 \+Module Management
23656    & HP MMS
23657    & Not applicable\cr
23658 \+ System
23659    &
23660    &\cr
23661 \smallskip
23662 \smallskip
23663 @end tex
23664 @end iftex
23665
23666 @ifnottex
23667 @c This is the Texinfo version of the table.  It renders poorly in pdf, hence
23668 @c the TeX version above for the printed version
23669 @flushleft
23670 @c @multitable @columnfractions .3 .4 .4
23671 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
23672 @item @i{Tool}
23673 @tab @i{Tool with HP Ada}
23674 @tab @i{Tool with @value{EDITION}}
23675 @item Code Management@*System
23676 @tab HP CMS
23677 @tab HP CMS
23678 @item Language-Sensitive@*Editor
23679 @tab HP LSE
23680 @tab emacs or HP LSE (Alpha)
23681 @item
23682 @tab
23683 @tab HP LSE (I64)
23684 @item Debugger
23685 @tab OpenVMS Debug
23686 @tab gdb (Alpha),
23687 @item
23688 @tab
23689 @tab OpenVMS Debug (I64)
23690 @item Source Code Analyzer /@*Cross Referencer
23691 @tab HP SCA
23692 @tab GNAT XREF
23693 @item Test Manager
23694 @tab HP Digital Test@*Manager (DTM)
23695 @tab HP DTM
23696 @item Performance and@*Coverage Analyzer
23697 @tab HP PCA
23698 @tab HP PCA
23699 @item Module Management@*System
23700 @tab HP MMS
23701 @tab Not applicable
23702 @end multitable
23703 @end flushleft
23704 @end ifnottex
23705
23706 @end ifset
23707
23708 @c **************************************
23709 @node Platform-Specific Information for the Run-Time Libraries
23710 @appendix Platform-Specific Information for the Run-Time Libraries
23711 @cindex Tasking and threads libraries
23712 @cindex Threads libraries and tasking
23713 @cindex Run-time libraries (platform-specific information)
23714
23715 @noindent
23716 The GNAT run-time implementation may vary with respect to both the
23717 underlying threads library and the exception handling scheme.
23718 For threads support, one or more of the following are supplied:
23719 @itemize @bullet
23720 @item @b{native threads library}, a binding to the thread package from
23721 the underlying operating system
23722
23723 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
23724 POSIX thread package
23725 @end itemize
23726
23727 @noindent
23728 For exception handling, either or both of two models are supplied:
23729 @itemize @bullet
23730 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
23731 Most programs should experience a substantial speed improvement by
23732 being compiled with a ZCX run-time.
23733 This is especially true for
23734 tasking applications or applications with many exception handlers.}
23735 @cindex Zero-Cost Exceptions
23736 @cindex ZCX (Zero-Cost Exceptions)
23737 which uses binder-generated tables that
23738 are interrogated at run time to locate a handler
23739
23740 @item @b{setjmp / longjmp} (``SJLJ''),
23741 @cindex setjmp/longjmp Exception Model
23742 @cindex SJLJ (setjmp/longjmp Exception Model)
23743 which uses dynamically-set data to establish
23744 the set of handlers
23745 @end itemize
23746
23747 @noindent
23748 This appendix summarizes which combinations of threads and exception support
23749 are supplied on various GNAT platforms.
23750 It then shows how to select a particular library either
23751 permanently or temporarily,
23752 explains the properties of (and tradeoffs among) the various threads
23753 libraries, and provides some additional
23754 information about several specific platforms.
23755
23756 @menu
23757 * Summary of Run-Time Configurations::
23758 * Specifying a Run-Time Library::
23759 * Choosing the Scheduling Policy::
23760 * Solaris-Specific Considerations::
23761 * Linux-Specific Considerations::
23762 * AIX-Specific Considerations::
23763 * RTX-Specific Considerations::
23764 * HP-UX-Specific Considerations::
23765 @end menu
23766
23767 @node Summary of Run-Time Configurations
23768 @section Summary of Run-Time Configurations
23769
23770 @multitable @columnfractions .30 .70
23771 @item @b{alpha-openvms}
23772 @item @code{@ @ }@i{rts-native (default)}
23773 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
23774 @item @code{@ @ @ @ }Exceptions @tab ZCX
23775 @*
23776 @item @code{@ @ }@i{rts-sjlj}
23777 @item @code{@ @ @ @ }Tasking    @tab native TRU64 threads
23778 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23779 @*
23780 @item @b{ia64-hp_linux}
23781 @item @code{@ @ }@i{rts-native (default)}
23782 @item @code{@ @ @ @ }Tasking    @tab pthread library
23783 @item @code{@ @ @ @ }Exceptions @tab ZCX
23784 @*
23785 @item @b{ia64-hpux}
23786 @item @code{@ @ }@i{rts-native (default)}
23787 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
23788 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23789 @*
23790 @item @b{ia64-openvms}
23791 @item @code{@ @ }@i{rts-native (default)}
23792 @item @code{@ @ @ @ }Tasking    @tab native VMS threads
23793 @item @code{@ @ @ @ }Exceptions @tab ZCX
23794 @*
23795 @item @b{ia64-sgi_linux}
23796 @item @code{@ @ }@i{rts-native (default)}
23797 @item @code{@ @ @ @ }Tasking    @tab pthread library
23798 @item @code{@ @ @ @ }Exceptions @tab ZCX
23799 @*
23800 @item @b{pa-hpux}
23801 @item @code{@ @ }@i{rts-native (default)}
23802 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
23803 @item @code{@ @ @ @ }Exceptions @tab ZCX
23804 @*
23805 @item @code{@ @ }@i{rts-sjlj}
23806 @item @code{@ @ @ @ }Tasking    @tab native HP-UX threads
23807 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23808 @*
23809 @item @b{ppc-aix}
23810 @item @code{@ @ }@i{rts-native (default)}
23811 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
23812 @item @code{@ @ @ @ }Exceptions @tab ZCX
23813 @*
23814 @item @code{@ @ }@i{rts-sjlj}
23815 @item @code{@ @ @ @ }Tasking    @tab native AIX threads
23816 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23817 @*
23818 @item @b{ppc-darwin}
23819 @item @code{@ @ }@i{rts-native (default)}
23820 @item @code{@ @ @ @ }Tasking    @tab native MacOS threads
23821 @item @code{@ @ @ @ }Exceptions @tab ZCX
23822 @*
23823 @item @b{sparc-solaris}  @tab
23824 @item @code{@ @ }@i{rts-native (default)}
23825 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
23826 @item @code{@ @ @ @ }Exceptions @tab ZCX
23827 @*
23828 @item @code{@ @ }@i{rts-pthread}
23829 @item @code{@ @ @ @ }Tasking    @tab pthread library
23830 @item @code{@ @ @ @ }Exceptions @tab ZCX
23831 @*
23832 @item @code{@ @ }@i{rts-sjlj}
23833 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
23834 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23835 @*
23836 @item @b{sparc64-solaris}  @tab
23837 @item @code{@ @ }@i{rts-native (default)}
23838 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
23839 @item @code{@ @ @ @ }Exceptions @tab ZCX
23840 @*
23841 @item @b{x86-linux}
23842 @item @code{@ @ }@i{rts-native (default)}
23843 @item @code{@ @ @ @ }Tasking    @tab pthread library
23844 @item @code{@ @ @ @ }Exceptions @tab ZCX
23845 @*
23846 @item @code{@ @ }@i{rts-sjlj}
23847 @item @code{@ @ @ @ }Tasking    @tab pthread library
23848 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23849 @*
23850 @item @b{x86-lynx}
23851 @item @code{@ @ }@i{rts-native (default)}
23852 @item @code{@ @ @ @ }Tasking    @tab native LynxOS threads
23853 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23854 @*
23855 @item @b{x86-solaris}
23856 @item @code{@ @ }@i{rts-native (default)}
23857 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads
23858 @item @code{@ @ @ @ }Exceptions @tab ZCX
23859 @*
23860 @item @code{@ @ }@i{rts-sjlj}
23861 @item @code{@ @ @ @ }Tasking    @tab native Solaris threads library
23862 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23863 @*
23864 @item @b{x86-windows}
23865 @item @code{@ @ }@i{rts-native (default)}
23866 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
23867 @item @code{@ @ @ @ }Exceptions @tab ZCX
23868 @*
23869 @item @code{@ @ }@i{rts-sjlj}
23870 @item @code{@ @ @ @ }Tasking    @tab native Win32 threads
23871 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23872 @*
23873 @item @b{x86-windows-rtx}
23874 @item @code{@ @ }@i{rts-rtx-rtss (default)}
23875 @item @code{@ @ @ @ }Tasking    @tab RTX real-time subsystem RTSS threads (kernel mode)
23876 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23877 @*
23878 @item @code{@ @ }@i{rts-rtx-w32}
23879 @item @code{@ @ @ @ }Tasking    @tab RTX Win32 threads (user mode)
23880 @item @code{@ @ @ @ }Exceptions @tab ZCX
23881 @*
23882 @item @b{x86_64-linux}
23883 @item @code{@ @ }@i{rts-native (default)}
23884 @item @code{@ @ @ @ }Tasking    @tab pthread library
23885 @item @code{@ @ @ @ }Exceptions @tab ZCX
23886 @*
23887 @item @code{@ @ }@i{rts-sjlj}
23888 @item @code{@ @ @ @ }Tasking    @tab pthread library
23889 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23890 @*
23891 @end multitable
23892
23893 @node Specifying a Run-Time Library
23894 @section Specifying a Run-Time Library
23895
23896 @noindent
23897 The @file{adainclude} subdirectory containing the sources of the GNAT
23898 run-time library, and the @file{adalib} subdirectory containing the
23899 @file{ALI} files and the static and/or shared GNAT library, are located
23900 in the gcc target-dependent area:
23901
23902 @smallexample
23903 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
23904 @end smallexample
23905
23906 @noindent
23907 As indicated above, on some platforms several run-time libraries are supplied.
23908 These libraries are installed in the target dependent area and
23909 contain a complete source and binary subdirectory. The detailed description
23910 below explains the differences between the different libraries in terms of
23911 their thread support.
23912
23913 The default run-time library (when GNAT is installed) is @emph{rts-native}.
23914 This default run time is selected by the means of soft links.
23915 For example on x86-linux:
23916
23917 @smallexample
23918 @group
23919  $(target-dir)
23920      |
23921      +--- adainclude----------+
23922      |                        |
23923      +--- adalib-----------+  |
23924      |                     |  |
23925      +--- rts-native       |  |
23926      |    |                |  |
23927      |    +--- adainclude <---+
23928      |    |                |
23929      |    +--- adalib <----+
23930      |
23931      +--- rts-sjlj
23932           |
23933           +--- adainclude
23934           |
23935           +--- adalib
23936 @end group
23937 @end smallexample
23938
23939 @noindent
23940 If the @i{rts-sjlj} library is to be selected on a permanent basis,
23941 these soft links can be modified with the following commands:
23942
23943 @smallexample
23944 $ cd $target
23945 $ rm -f adainclude adalib
23946 $ ln -s rts-sjlj/adainclude adainclude
23947 $ ln -s rts-sjlj/adalib adalib
23948 @end smallexample
23949
23950 @noindent
23951 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
23952 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
23953 @file{$target/ada_object_path}.
23954
23955 Selecting another run-time library temporarily can be
23956 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
23957 @cindex @option{--RTS} option
23958
23959 @node Choosing the Scheduling Policy
23960 @section Choosing the Scheduling Policy
23961
23962 @noindent
23963 When using a POSIX threads implementation, you have a choice of several
23964 scheduling policies: @code{SCHED_FIFO},
23965 @cindex @code{SCHED_FIFO} scheduling policy
23966 @code{SCHED_RR}
23967 @cindex @code{SCHED_RR} scheduling policy
23968 and @code{SCHED_OTHER}.
23969 @cindex @code{SCHED_OTHER} scheduling policy
23970 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
23971 or @code{SCHED_RR} requires special (e.g., root) privileges.
23972
23973 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
23974 @code{SCHED_FIFO},
23975 @cindex @code{SCHED_FIFO} scheduling policy
23976 you can use one of the following:
23977
23978 @itemize @bullet
23979 @item
23980 @code{pragma Time_Slice (0.0)}
23981 @cindex pragma Time_Slice
23982 @item
23983 the corresponding binder option @option{-T0}
23984 @cindex @option{-T0} option
23985 @item
23986 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23987 @cindex pragma Task_Dispatching_Policy
23988 @end itemize
23989
23990 @noindent
23991 To specify @code{SCHED_RR},
23992 @cindex @code{SCHED_RR} scheduling policy
23993 you should use @code{pragma Time_Slice} with a
23994 value greater than @code{0.0}, or else use the corresponding @option{-T}
23995 binder option.
23996
23997 @node Solaris-Specific Considerations
23998 @section Solaris-Specific Considerations
23999 @cindex Solaris Sparc threads libraries
24000
24001 @noindent
24002 This section addresses some topics related to the various threads libraries
24003 on Sparc Solaris.
24004
24005 @menu
24006 * Solaris Threads Issues::
24007 @end menu
24008
24009 @node Solaris Threads Issues
24010 @subsection Solaris Threads Issues
24011
24012 @noindent
24013 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
24014 library based on POSIX threads --- @emph{rts-pthread}.
24015 @cindex rts-pthread threads library
24016 This run-time library has the advantage of being mostly shared across all
24017 POSIX-compliant thread implementations, and it also provides under
24018 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
24019 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
24020 and @code{PTHREAD_PRIO_PROTECT}
24021 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
24022 semantics that can be selected using the predefined pragma
24023 @code{Locking_Policy}
24024 @cindex pragma Locking_Policy (under rts-pthread)
24025 with respectively
24026 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
24027 @cindex @code{Inheritance_Locking} (under rts-pthread)
24028 @cindex @code{Ceiling_Locking} (under rts-pthread)
24029
24030 As explained above, the native run-time library is based on the Solaris thread
24031 library (@code{libthread}) and is the default library.
24032
24033 When the Solaris threads library is used (this is the default), programs
24034 compiled with GNAT can automatically take advantage of
24035 and can thus execute on multiple processors.
24036 The user can alternatively specify a processor on which the program should run
24037 to emulate a single-processor system. The multiprocessor / uniprocessor choice
24038 is made by
24039 setting the environment variable @env{GNAT_PROCESSOR}
24040 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
24041 to one of the following:
24042
24043 @table @code
24044 @item -2
24045 Use the default configuration (run the program on all
24046 available processors) - this is the same as having @code{GNAT_PROCESSOR}
24047 unset
24048
24049 @item -1
24050 Let the run-time implementation choose one processor and run the program on
24051 that processor
24052
24053 @item 0 .. Last_Proc
24054 Run the program on the specified processor.
24055 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
24056 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
24057 @end table
24058
24059 @node Linux-Specific Considerations
24060 @section Linux-Specific Considerations
24061 @cindex Linux threads libraries
24062
24063 @noindent
24064 On GNU/Linux without NPTL support (usually system with GNU C Library
24065 older than 2.3), the signal model is not POSIX compliant, which means
24066 that to send a signal to the process, you need to send the signal to all
24067 threads, e.g.@: by using @code{killpg()}.
24068
24069 @node AIX-Specific Considerations
24070 @section AIX-Specific Considerations
24071 @cindex AIX resolver library
24072
24073 @noindent
24074 On AIX, the resolver library initializes some internal structure on
24075 the first call to @code{get*by*} functions, which are used to implement
24076 @code{GNAT.Sockets.Get_Host_By_Name} and
24077 @code{GNAT.Sockets.Get_Host_By_Address}.
24078 If such initialization occurs within an Ada task, and the stack size for
24079 the task is the default size, a stack overflow may occur.
24080
24081 To avoid this overflow, the user should either ensure that the first call
24082 to @code{GNAT.Sockets.Get_Host_By_Name} or
24083 @code{GNAT.Sockets.Get_Host_By_Addrss}
24084 occurs in the environment task, or use @code{pragma Storage_Size} to
24085 specify a sufficiently large size for the stack of the task that contains
24086 this call.
24087
24088 @node RTX-Specific Considerations
24089 @section RTX-Specific Considerations
24090 @cindex RTX libraries
24091
24092 @noindent
24093 The Real-time Extension (RTX) to Windows is based on the Windows Win32
24094 API. Applications can be built to work in two different modes:
24095
24096 @itemize @bullet
24097 @item
24098 Windows executables that run in Ring 3 to utilize memory protection
24099 (@emph{rts-rtx-w32}).
24100
24101 @item
24102 Real-time subsystem (RTSS) executables that run in Ring 0, where
24103 performance can be optimized with RTSS applications taking precedent
24104 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
24105 the Microsoft linker to handle RTSS libraries.
24106
24107 @end itemize
24108
24109 @node HP-UX-Specific Considerations
24110 @section HP-UX-Specific Considerations
24111 @cindex HP-UX Scheduling
24112
24113 @noindent
24114 On HP-UX, appropriate privileges are required to change the scheduling
24115 parameters of a task. The calling process must have appropriate
24116 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
24117 successfully change the scheduling parameters.
24118
24119 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
24120 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
24121 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
24122
24123 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
24124 one of the following:
24125
24126 @itemize @bullet
24127 @item
24128 @code{pragma Time_Slice (0.0)}
24129 @cindex pragma Time_Slice
24130 @item
24131 the corresponding binder option @option{-T0}
24132 @cindex @option{-T0} option
24133 @item
24134 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
24135 @cindex pragma Task_Dispatching_Policy
24136 @end itemize
24137
24138 @noindent
24139 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
24140 you should use @code{pragma Time_Slice} with a
24141 value greater than @code{0.0}, or use the corresponding @option{-T}
24142 binder option, or set the @code{pragma Task_Dispatching_Policy
24143 (Round_Robin_Within_Priorities)}.
24144
24145 @c *******************************
24146 @node Example of Binder Output File
24147 @appendix Example of Binder Output File
24148
24149 @noindent
24150 This Appendix displays the source code for @command{gnatbind}'s output
24151 file generated for a simple ``Hello World'' program.
24152 Comments have been added for clarification purposes.
24153
24154 @smallexample @c adanocomment
24155 @iftex
24156 @leftskip=0cm
24157 @end iftex
24158 --  The package is called Ada_Main unless this name is actually used
24159 --  as a unit name in the partition, in which case some other unique
24160 --  name is used.
24161
24162 with System;
24163 package ada_main is
24164
24165    Elab_Final_Code : Integer;
24166    pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
24167
24168    --  The main program saves the parameters (argument count,
24169    --  argument values, environment pointer) in global variables
24170    --  for later access by other units including
24171    --  Ada.Command_Line.
24172
24173    gnat_argc : Integer;
24174    gnat_argv : System.Address;
24175    gnat_envp : System.Address;
24176
24177    --  The actual variables are stored in a library routine. This
24178    --  is useful for some shared library situations, where there
24179    --  are problems if variables are not in the library.
24180
24181    pragma Import (C, gnat_argc);
24182    pragma Import (C, gnat_argv);
24183    pragma Import (C, gnat_envp);
24184
24185    --  The exit status is similarly an external location
24186
24187    gnat_exit_status : Integer;
24188    pragma Import (C, gnat_exit_status);
24189
24190    GNAT_Version : constant String :=
24191                     "GNAT Version: 6.0.0w (20061115)";
24192    pragma Export (C, GNAT_Version, "__gnat_version");
24193
24194    --  This is the generated adafinal routine that performs
24195    --  finalization at the end of execution. In the case where
24196    --  Ada is the main program, this main program makes a call
24197    --  to adafinal at program termination.
24198
24199    procedure adafinal;
24200    pragma Export (C, adafinal, "adafinal");
24201
24202    --  This is the generated adainit routine that performs
24203    --  initialization at the start of execution. In the case
24204    --  where Ada is the main program, this main program makes
24205    --  a call to adainit at program startup.
24206
24207    procedure adainit;
24208    pragma Export (C, adainit, "adainit");
24209
24210    --  This routine is called at the start of execution. It is
24211    --  a dummy routine that is used by the debugger to breakpoint
24212    --  at the start of execution.
24213
24214    procedure Break_Start;
24215    pragma Import (C, Break_Start, "__gnat_break_start");
24216
24217    --  This is the actual generated main program (it would be
24218    --  suppressed if the no main program switch were used). As
24219    --  required by standard system conventions, this program has
24220    --  the external name main.
24221
24222    function main
24223      (argc : Integer;
24224       argv : System.Address;
24225       envp : System.Address)
24226       return Integer;
24227    pragma Export (C, main, "main");
24228
24229    --  The following set of constants give the version
24230    --  identification values for every unit in the bound
24231    --  partition. This identification is computed from all
24232    --  dependent semantic units, and corresponds to the
24233    --  string that would be returned by use of the
24234    --  Body_Version or Version attributes.
24235
24236    type Version_32 is mod 2 ** 32;
24237    u00001 : constant Version_32 := 16#7880BEB3#;
24238    u00002 : constant Version_32 := 16#0D24CBD0#;
24239    u00003 : constant Version_32 := 16#3283DBEB#;
24240    u00004 : constant Version_32 := 16#2359F9ED#;
24241    u00005 : constant Version_32 := 16#664FB847#;
24242    u00006 : constant Version_32 := 16#68E803DF#;
24243    u00007 : constant Version_32 := 16#5572E604#;
24244    u00008 : constant Version_32 := 16#46B173D8#;
24245    u00009 : constant Version_32 := 16#156A40CF#;
24246    u00010 : constant Version_32 := 16#033DABE0#;
24247    u00011 : constant Version_32 := 16#6AB38FEA#;
24248    u00012 : constant Version_32 := 16#22B6217D#;
24249    u00013 : constant Version_32 := 16#68A22947#;
24250    u00014 : constant Version_32 := 16#18CC4A56#;
24251    u00015 : constant Version_32 := 16#08258E1B#;
24252    u00016 : constant Version_32 := 16#367D5222#;
24253    u00017 : constant Version_32 := 16#20C9ECA4#;
24254    u00018 : constant Version_32 := 16#50D32CB6#;
24255    u00019 : constant Version_32 := 16#39A8BB77#;
24256    u00020 : constant Version_32 := 16#5CF8FA2B#;
24257    u00021 : constant Version_32 := 16#2F1EB794#;
24258    u00022 : constant Version_32 := 16#31AB6444#;
24259    u00023 : constant Version_32 := 16#1574B6E9#;
24260    u00024 : constant Version_32 := 16#5109C189#;
24261    u00025 : constant Version_32 := 16#56D770CD#;
24262    u00026 : constant Version_32 := 16#02F9DE3D#;
24263    u00027 : constant Version_32 := 16#08AB6B2C#;
24264    u00028 : constant Version_32 := 16#3FA37670#;
24265    u00029 : constant Version_32 := 16#476457A0#;
24266    u00030 : constant Version_32 := 16#731E1B6E#;
24267    u00031 : constant Version_32 := 16#23C2E789#;
24268    u00032 : constant Version_32 := 16#0F1BD6A1#;
24269    u00033 : constant Version_32 := 16#7C25DE96#;
24270    u00034 : constant Version_32 := 16#39ADFFA2#;
24271    u00035 : constant Version_32 := 16#571DE3E7#;
24272    u00036 : constant Version_32 := 16#5EB646AB#;
24273    u00037 : constant Version_32 := 16#4249379B#;
24274    u00038 : constant Version_32 := 16#0357E00A#;
24275    u00039 : constant Version_32 := 16#3784FB72#;
24276    u00040 : constant Version_32 := 16#2E723019#;
24277    u00041 : constant Version_32 := 16#623358EA#;
24278    u00042 : constant Version_32 := 16#107F9465#;
24279    u00043 : constant Version_32 := 16#6843F68A#;
24280    u00044 : constant Version_32 := 16#63305874#;
24281    u00045 : constant Version_32 := 16#31E56CE1#;
24282    u00046 : constant Version_32 := 16#02917970#;
24283    u00047 : constant Version_32 := 16#6CCBA70E#;
24284    u00048 : constant Version_32 := 16#41CD4204#;
24285    u00049 : constant Version_32 := 16#572E3F58#;
24286    u00050 : constant Version_32 := 16#20729FF5#;
24287    u00051 : constant Version_32 := 16#1D4F93E8#;
24288    u00052 : constant Version_32 := 16#30B2EC3D#;
24289    u00053 : constant Version_32 := 16#34054F96#;
24290    u00054 : constant Version_32 := 16#5A199860#;
24291    u00055 : constant Version_32 := 16#0E7F912B#;
24292    u00056 : constant Version_32 := 16#5760634A#;
24293    u00057 : constant Version_32 := 16#5D851835#;
24294
24295    --  The following Export pragmas export the version numbers
24296    --  with symbolic names ending in B (for body) or S
24297    --  (for spec) so that they can be located in a link. The
24298    --  information provided here is sufficient to track down
24299    --  the exact versions of units used in a given build.
24300
24301    pragma Export (C, u00001, "helloB");
24302    pragma Export (C, u00002, "system__standard_libraryB");
24303    pragma Export (C, u00003, "system__standard_libraryS");
24304    pragma Export (C, u00004, "adaS");
24305    pragma Export (C, u00005, "ada__text_ioB");
24306    pragma Export (C, u00006, "ada__text_ioS");
24307    pragma Export (C, u00007, "ada__exceptionsB");
24308    pragma Export (C, u00008, "ada__exceptionsS");
24309    pragma Export (C, u00009, "gnatS");
24310    pragma Export (C, u00010, "gnat__heap_sort_aB");
24311    pragma Export (C, u00011, "gnat__heap_sort_aS");
24312    pragma Export (C, u00012, "systemS");
24313    pragma Export (C, u00013, "system__exception_tableB");
24314    pragma Export (C, u00014, "system__exception_tableS");
24315    pragma Export (C, u00015, "gnat__htableB");
24316    pragma Export (C, u00016, "gnat__htableS");
24317    pragma Export (C, u00017, "system__exceptionsS");
24318    pragma Export (C, u00018, "system__machine_state_operationsB");
24319    pragma Export (C, u00019, "system__machine_state_operationsS");
24320    pragma Export (C, u00020, "system__machine_codeS");
24321    pragma Export (C, u00021, "system__storage_elementsB");
24322    pragma Export (C, u00022, "system__storage_elementsS");
24323    pragma Export (C, u00023, "system__secondary_stackB");
24324    pragma Export (C, u00024, "system__secondary_stackS");
24325    pragma Export (C, u00025, "system__parametersB");
24326    pragma Export (C, u00026, "system__parametersS");
24327    pragma Export (C, u00027, "system__soft_linksB");
24328    pragma Export (C, u00028, "system__soft_linksS");
24329    pragma Export (C, u00029, "system__stack_checkingB");
24330    pragma Export (C, u00030, "system__stack_checkingS");
24331    pragma Export (C, u00031, "system__tracebackB");
24332    pragma Export (C, u00032, "system__tracebackS");
24333    pragma Export (C, u00033, "ada__streamsS");
24334    pragma Export (C, u00034, "ada__tagsB");
24335    pragma Export (C, u00035, "ada__tagsS");
24336    pragma Export (C, u00036, "system__string_opsB");
24337    pragma Export (C, u00037, "system__string_opsS");
24338    pragma Export (C, u00038, "interfacesS");
24339    pragma Export (C, u00039, "interfaces__c_streamsB");
24340    pragma Export (C, u00040, "interfaces__c_streamsS");
24341    pragma Export (C, u00041, "system__file_ioB");
24342    pragma Export (C, u00042, "system__file_ioS");
24343    pragma Export (C, u00043, "ada__finalizationB");
24344    pragma Export (C, u00044, "ada__finalizationS");
24345    pragma Export (C, u00045, "system__finalization_rootB");
24346    pragma Export (C, u00046, "system__finalization_rootS");
24347    pragma Export (C, u00047, "system__finalization_implementationB");
24348    pragma Export (C, u00048, "system__finalization_implementationS");
24349    pragma Export (C, u00049, "system__string_ops_concat_3B");
24350    pragma Export (C, u00050, "system__string_ops_concat_3S");
24351    pragma Export (C, u00051, "system__stream_attributesB");
24352    pragma Export (C, u00052, "system__stream_attributesS");
24353    pragma Export (C, u00053, "ada__io_exceptionsS");
24354    pragma Export (C, u00054, "system__unsigned_typesS");
24355    pragma Export (C, u00055, "system__file_control_blockS");
24356    pragma Export (C, u00056, "ada__finalization__list_controllerB");
24357    pragma Export (C, u00057, "ada__finalization__list_controllerS");
24358
24359    -- BEGIN ELABORATION ORDER
24360    -- ada (spec)
24361    -- gnat (spec)
24362    -- gnat.heap_sort_a (spec)
24363    -- gnat.heap_sort_a (body)
24364    -- gnat.htable (spec)
24365    -- gnat.htable (body)
24366    -- interfaces (spec)
24367    -- system (spec)
24368    -- system.machine_code (spec)
24369    -- system.parameters (spec)
24370    -- system.parameters (body)
24371    -- interfaces.c_streams (spec)
24372    -- interfaces.c_streams (body)
24373    -- system.standard_library (spec)
24374    -- ada.exceptions (spec)
24375    -- system.exception_table (spec)
24376    -- system.exception_table (body)
24377    -- ada.io_exceptions (spec)
24378    -- system.exceptions (spec)
24379    -- system.storage_elements (spec)
24380    -- system.storage_elements (body)
24381    -- system.machine_state_operations (spec)
24382    -- system.machine_state_operations (body)
24383    -- system.secondary_stack (spec)
24384    -- system.stack_checking (spec)
24385    -- system.soft_links (spec)
24386    -- system.soft_links (body)
24387    -- system.stack_checking (body)
24388    -- system.secondary_stack (body)
24389    -- system.standard_library (body)
24390    -- system.string_ops (spec)
24391    -- system.string_ops (body)
24392    -- ada.tags (spec)
24393    -- ada.tags (body)
24394    -- ada.streams (spec)
24395    -- system.finalization_root (spec)
24396    -- system.finalization_root (body)
24397    -- system.string_ops_concat_3 (spec)
24398    -- system.string_ops_concat_3 (body)
24399    -- system.traceback (spec)
24400    -- system.traceback (body)
24401    -- ada.exceptions (body)
24402    -- system.unsigned_types (spec)
24403    -- system.stream_attributes (spec)
24404    -- system.stream_attributes (body)
24405    -- system.finalization_implementation (spec)
24406    -- system.finalization_implementation (body)
24407    -- ada.finalization (spec)
24408    -- ada.finalization (body)
24409    -- ada.finalization.list_controller (spec)
24410    -- ada.finalization.list_controller (body)
24411    -- system.file_control_block (spec)
24412    -- system.file_io (spec)
24413    -- system.file_io (body)
24414    -- ada.text_io (spec)
24415    -- ada.text_io (body)
24416    -- hello (body)
24417    -- END ELABORATION ORDER
24418
24419 end ada_main;
24420
24421 --  The following source file name pragmas allow the generated file
24422 --  names to be unique for different main programs. They are needed
24423 --  since the package name will always be Ada_Main.
24424
24425 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
24426 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
24427
24428 --  Generated package body for Ada_Main starts here
24429
24430 package body ada_main is
24431
24432    --  The actual finalization is performed by calling the
24433    --  library routine in System.Standard_Library.Adafinal
24434
24435    procedure Do_Finalize;
24436    pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
24437
24438    -------------
24439    -- adainit --
24440    -------------
24441
24442 @findex adainit
24443    procedure adainit is
24444
24445       --  These booleans are set to True once the associated unit has
24446       --  been elaborated. It is also used to avoid elaborating the
24447       --  same unit twice.
24448
24449       E040 : Boolean;
24450       pragma Import (Ada, E040, "interfaces__c_streams_E");
24451
24452       E008 : Boolean;
24453       pragma Import (Ada, E008, "ada__exceptions_E");
24454
24455       E014 : Boolean;
24456       pragma Import (Ada, E014, "system__exception_table_E");
24457
24458       E053 : Boolean;
24459       pragma Import (Ada, E053, "ada__io_exceptions_E");
24460
24461       E017 : Boolean;
24462       pragma Import (Ada, E017, "system__exceptions_E");
24463
24464       E024 : Boolean;
24465       pragma Import (Ada, E024, "system__secondary_stack_E");
24466
24467       E030 : Boolean;
24468       pragma Import (Ada, E030, "system__stack_checking_E");
24469
24470       E028 : Boolean;
24471       pragma Import (Ada, E028, "system__soft_links_E");
24472
24473       E035 : Boolean;
24474       pragma Import (Ada, E035, "ada__tags_E");
24475
24476       E033 : Boolean;
24477       pragma Import (Ada, E033, "ada__streams_E");
24478
24479       E046 : Boolean;
24480       pragma Import (Ada, E046, "system__finalization_root_E");
24481
24482       E048 : Boolean;
24483       pragma Import (Ada, E048, "system__finalization_implementation_E");
24484
24485       E044 : Boolean;
24486       pragma Import (Ada, E044, "ada__finalization_E");
24487
24488       E057 : Boolean;
24489       pragma Import (Ada, E057, "ada__finalization__list_controller_E");
24490
24491       E055 : Boolean;
24492       pragma Import (Ada, E055, "system__file_control_block_E");
24493
24494       E042 : Boolean;
24495       pragma Import (Ada, E042, "system__file_io_E");
24496
24497       E006 : Boolean;
24498       pragma Import (Ada, E006, "ada__text_io_E");
24499
24500       --  Set_Globals is a library routine that stores away the
24501       --  value of the indicated set of global values in global
24502       --  variables within the library.
24503
24504       procedure Set_Globals
24505         (Main_Priority            : Integer;
24506          Time_Slice_Value         : Integer;
24507          WC_Encoding              : Character;
24508          Locking_Policy           : Character;
24509          Queuing_Policy           : Character;
24510          Task_Dispatching_Policy  : Character;
24511          Adafinal                 : System.Address;
24512          Unreserve_All_Interrupts : Integer;
24513          Exception_Tracebacks     : Integer);
24514 @findex __gnat_set_globals
24515       pragma Import (C, Set_Globals, "__gnat_set_globals");
24516
24517       --  SDP_Table_Build is a library routine used to build the
24518       --  exception tables. See unit Ada.Exceptions in files
24519       --  a-except.ads/adb for full details of how zero cost
24520       --  exception handling works. This procedure, the call to
24521       --  it, and the two following tables are all omitted if the
24522       --  build is in longjmp/setjmp exception mode.
24523
24524 @findex SDP_Table_Build
24525 @findex Zero Cost Exceptions
24526       procedure SDP_Table_Build
24527         (SDP_Addresses   : System.Address;
24528          SDP_Count       : Natural;
24529          Elab_Addresses  : System.Address;
24530          Elab_Addr_Count : Natural);
24531       pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
24532
24533       --  Table of Unit_Exception_Table addresses. Used for zero
24534       --  cost exception handling to build the top level table.
24535
24536       ST : aliased constant array (1 .. 23) of System.Address := (
24537         Hello'UET_Address,
24538         Ada.Text_Io'UET_Address,
24539         Ada.Exceptions'UET_Address,
24540         Gnat.Heap_Sort_A'UET_Address,
24541         System.Exception_Table'UET_Address,
24542         System.Machine_State_Operations'UET_Address,
24543         System.Secondary_Stack'UET_Address,
24544         System.Parameters'UET_Address,
24545         System.Soft_Links'UET_Address,
24546         System.Stack_Checking'UET_Address,
24547         System.Traceback'UET_Address,
24548         Ada.Streams'UET_Address,
24549         Ada.Tags'UET_Address,
24550         System.String_Ops'UET_Address,
24551         Interfaces.C_Streams'UET_Address,
24552         System.File_Io'UET_Address,
24553         Ada.Finalization'UET_Address,
24554         System.Finalization_Root'UET_Address,
24555         System.Finalization_Implementation'UET_Address,
24556         System.String_Ops_Concat_3'UET_Address,
24557         System.Stream_Attributes'UET_Address,
24558         System.File_Control_Block'UET_Address,
24559         Ada.Finalization.List_Controller'UET_Address);
24560
24561       --  Table of addresses of elaboration routines. Used for
24562       --  zero cost exception handling to make sure these
24563       --  addresses are included in the top level procedure
24564       --  address table.
24565
24566       EA : aliased constant array (1 .. 23) of System.Address := (
24567         adainit'Code_Address,
24568         Do_Finalize'Code_Address,
24569         Ada.Exceptions'Elab_Spec'Address,
24570         System.Exceptions'Elab_Spec'Address,
24571         Interfaces.C_Streams'Elab_Spec'Address,
24572         System.Exception_Table'Elab_Body'Address,
24573         Ada.Io_Exceptions'Elab_Spec'Address,
24574         System.Stack_Checking'Elab_Spec'Address,
24575         System.Soft_Links'Elab_Body'Address,
24576         System.Secondary_Stack'Elab_Body'Address,
24577         Ada.Tags'Elab_Spec'Address,
24578         Ada.Tags'Elab_Body'Address,
24579         Ada.Streams'Elab_Spec'Address,
24580         System.Finalization_Root'Elab_Spec'Address,
24581         Ada.Exceptions'Elab_Body'Address,
24582         System.Finalization_Implementation'Elab_Spec'Address,
24583         System.Finalization_Implementation'Elab_Body'Address,
24584         Ada.Finalization'Elab_Spec'Address,
24585         Ada.Finalization.List_Controller'Elab_Spec'Address,
24586         System.File_Control_Block'Elab_Spec'Address,
24587         System.File_Io'Elab_Body'Address,
24588         Ada.Text_Io'Elab_Spec'Address,
24589         Ada.Text_Io'Elab_Body'Address);
24590
24591    --  Start of processing for adainit
24592
24593    begin
24594
24595       --  Call SDP_Table_Build to build the top level procedure
24596       --  table for zero cost exception handling (omitted in
24597       --  longjmp/setjmp mode).
24598
24599       SDP_Table_Build (ST'Address, 23, EA'Address, 23);
24600
24601       --  Call Set_Globals to record various information for
24602       --  this partition.  The values are derived by the binder
24603       --  from information stored in the ali files by the compiler.
24604
24605 @findex __gnat_set_globals
24606       Set_Globals
24607         (Main_Priority            => -1,
24608          --  Priority of main program, -1 if no pragma Priority used
24609
24610          Time_Slice_Value         => -1,
24611          --  Time slice from Time_Slice pragma, -1 if none used
24612
24613          WC_Encoding              => 'b',
24614          --  Wide_Character encoding used, default is brackets
24615
24616          Locking_Policy           => ' ',
24617          --  Locking_Policy used, default of space means not
24618          --  specified, otherwise it is the first character of
24619          --  the policy name.
24620
24621          Queuing_Policy           => ' ',
24622          --  Queuing_Policy used, default of space means not
24623          --  specified, otherwise it is the first character of
24624          --  the policy name.
24625
24626          Task_Dispatching_Policy  => ' ',
24627          --  Task_Dispatching_Policy used, default of space means
24628          --  not specified, otherwise first character of the
24629          --  policy name.
24630
24631          Adafinal                 => System.Null_Address,
24632          --  Address of Adafinal routine, not used anymore
24633
24634          Unreserve_All_Interrupts => 0,
24635          --  Set true if pragma Unreserve_All_Interrupts was used
24636
24637          Exception_Tracebacks     => 0);
24638          --  Indicates if exception tracebacks are enabled
24639
24640       Elab_Final_Code := 1;
24641
24642       --  Now we have the elaboration calls for all units in the partition.
24643       --  The Elab_Spec and Elab_Body attributes generate references to the
24644       --  implicit elaboration procedures generated by the compiler for
24645       --  each unit that requires elaboration.
24646
24647       if not E040 then
24648          Interfaces.C_Streams'Elab_Spec;
24649       end if;
24650       E040 := True;
24651       if not E008 then
24652          Ada.Exceptions'Elab_Spec;
24653       end if;
24654       if not E014 then
24655          System.Exception_Table'Elab_Body;
24656          E014 := True;
24657       end if;
24658       if not E053 then
24659          Ada.Io_Exceptions'Elab_Spec;
24660          E053 := True;
24661       end if;
24662       if not E017 then
24663          System.Exceptions'Elab_Spec;
24664          E017 := True;
24665       end if;
24666       if not E030 then
24667          System.Stack_Checking'Elab_Spec;
24668       end if;
24669       if not E028 then
24670          System.Soft_Links'Elab_Body;
24671          E028 := True;
24672       end if;
24673       E030 := True;
24674       if not E024 then
24675          System.Secondary_Stack'Elab_Body;
24676          E024 := True;
24677       end if;
24678       if not E035 then
24679          Ada.Tags'Elab_Spec;
24680       end if;
24681       if not E035 then
24682          Ada.Tags'Elab_Body;
24683          E035 := True;
24684       end if;
24685       if not E033 then
24686          Ada.Streams'Elab_Spec;
24687          E033 := True;
24688       end if;
24689       if not E046 then
24690          System.Finalization_Root'Elab_Spec;
24691       end if;
24692       E046 := True;
24693       if not E008 then
24694          Ada.Exceptions'Elab_Body;
24695          E008 := True;
24696       end if;
24697       if not E048 then
24698          System.Finalization_Implementation'Elab_Spec;
24699       end if;
24700       if not E048 then
24701          System.Finalization_Implementation'Elab_Body;
24702          E048 := True;
24703       end if;
24704       if not E044 then
24705          Ada.Finalization'Elab_Spec;
24706       end if;
24707       E044 := True;
24708       if not E057 then
24709          Ada.Finalization.List_Controller'Elab_Spec;
24710       end if;
24711       E057 := True;
24712       if not E055 then
24713          System.File_Control_Block'Elab_Spec;
24714          E055 := True;
24715       end if;
24716       if not E042 then
24717          System.File_Io'Elab_Body;
24718          E042 := True;
24719       end if;
24720       if not E006 then
24721          Ada.Text_Io'Elab_Spec;
24722       end if;
24723       if not E006 then
24724          Ada.Text_Io'Elab_Body;
24725          E006 := True;
24726       end if;
24727
24728       Elab_Final_Code := 0;
24729    end adainit;
24730
24731    --------------
24732    -- adafinal --
24733    --------------
24734
24735 @findex adafinal
24736    procedure adafinal is
24737    begin
24738       Do_Finalize;
24739    end adafinal;
24740
24741    ----------
24742    -- main --
24743    ----------
24744
24745    --  main is actually a function, as in the ANSI C standard,
24746    --  defined to return the exit status. The three parameters
24747    --  are the argument count, argument values and environment
24748    --  pointer.
24749
24750 @findex Main Program
24751    function main
24752      (argc : Integer;
24753       argv : System.Address;
24754       envp : System.Address)
24755       return Integer
24756    is
24757       --  The initialize routine performs low level system
24758       --  initialization using a standard library routine which
24759       --  sets up signal handling and performs any other
24760       --  required setup. The routine can be found in file
24761       --  a-init.c.
24762
24763 @findex __gnat_initialize
24764       procedure initialize;
24765       pragma Import (C, initialize, "__gnat_initialize");
24766
24767       --  The finalize routine performs low level system
24768       --  finalization using a standard library routine. The
24769       --  routine is found in file a-final.c and in the standard
24770       --  distribution is a dummy routine that does nothing, so
24771       --  really this is a hook for special user finalization.
24772
24773 @findex __gnat_finalize
24774       procedure finalize;
24775       pragma Import (C, finalize, "__gnat_finalize");
24776
24777       --  We get to the main program of the partition by using
24778       --  pragma Import because if we try to with the unit and
24779       --  call it Ada style, then not only do we waste time
24780       --  recompiling it, but also, we don't really know the right
24781       --  switches (e.g.@: identifier character set) to be used
24782       --  to compile it.
24783
24784       procedure Ada_Main_Program;
24785       pragma Import (Ada, Ada_Main_Program, "_ada_hello");
24786
24787    --  Start of processing for main
24788
24789    begin
24790       --  Save global variables
24791
24792       gnat_argc := argc;
24793       gnat_argv := argv;
24794       gnat_envp := envp;
24795
24796       --  Call low level system initialization
24797
24798       Initialize;
24799
24800       --  Call our generated Ada initialization routine
24801
24802       adainit;
24803
24804       --  This is the point at which we want the debugger to get
24805       --  control
24806
24807       Break_Start;
24808
24809       --  Now we call the main program of the partition
24810
24811       Ada_Main_Program;
24812
24813       --  Perform Ada finalization
24814
24815       adafinal;
24816
24817       --  Perform low level system finalization
24818
24819       Finalize;
24820
24821       --  Return the proper exit status
24822       return (gnat_exit_status);
24823    end;
24824
24825 --  This section is entirely comments, so it has no effect on the
24826 --  compilation of the Ada_Main package. It provides the list of
24827 --  object files and linker options, as well as some standard
24828 --  libraries needed for the link. The gnatlink utility parses
24829 --  this b~hello.adb file to read these comment lines to generate
24830 --  the appropriate command line arguments for the call to the
24831 --  system linker. The BEGIN/END lines are used for sentinels for
24832 --  this parsing operation.
24833
24834 --  The exact file names will of course depend on the environment,
24835 --  host/target and location of files on the host system.
24836
24837 @findex Object file list
24838 -- BEGIN Object file/option list
24839    --   ./hello.o
24840    --   -L./
24841    --   -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
24842    --   /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
24843 -- END Object file/option list
24844
24845 end ada_main;
24846 @end smallexample
24847
24848 @noindent
24849 The Ada code in the above example is exactly what is generated by the
24850 binder. We have added comments to more clearly indicate the function
24851 of each part of the generated @code{Ada_Main} package.
24852
24853 The code is standard Ada in all respects, and can be processed by any
24854 tools that handle Ada. In particular, it is possible to use the debugger
24855 in Ada mode to debug the generated @code{Ada_Main} package. For example,
24856 suppose that for reasons that you do not understand, your program is crashing
24857 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
24858 you can place a breakpoint on the call:
24859
24860 @smallexample @c ada
24861 Ada.Text_Io'Elab_Body;
24862 @end smallexample
24863
24864 @noindent
24865 and trace the elaboration routine for this package to find out where
24866 the problem might be (more usually of course you would be debugging
24867 elaboration code in your own application).
24868
24869 @node Elaboration Order Handling in GNAT
24870 @appendix Elaboration Order Handling in GNAT
24871 @cindex Order of elaboration
24872 @cindex Elaboration control
24873
24874 @menu
24875 * Elaboration Code::
24876 * Checking the Elaboration Order::
24877 * Controlling the Elaboration Order::
24878 * Controlling Elaboration in GNAT - Internal Calls::
24879 * Controlling Elaboration in GNAT - External Calls::
24880 * Default Behavior in GNAT - Ensuring Safety::
24881 * Treatment of Pragma Elaborate::
24882 * Elaboration Issues for Library Tasks::
24883 * Mixing Elaboration Models::
24884 * What to Do If the Default Elaboration Behavior Fails::
24885 * Elaboration for Dispatching Calls::
24886 * Summary of Procedures for Elaboration Control::
24887 * Other Elaboration Order Considerations::
24888 @end menu
24889
24890 @noindent
24891 This chapter describes the handling of elaboration code in Ada and
24892 in GNAT, and discusses how the order of elaboration of program units can
24893 be controlled in GNAT, either automatically or with explicit programming
24894 features.
24895
24896 @node Elaboration Code
24897 @section Elaboration Code
24898
24899 @noindent
24900 Ada provides rather general mechanisms for executing code at elaboration
24901 time, that is to say before the main program starts executing. Such code arises
24902 in three contexts:
24903
24904 @table @asis
24905 @item Initializers for variables.
24906 Variables declared at the library level, in package specs or bodies, can
24907 require initialization that is performed at elaboration time, as in:
24908 @smallexample @c ada
24909 @cartouche
24910 Sqrt_Half : Float := Sqrt (0.5);
24911 @end cartouche
24912 @end smallexample
24913
24914 @item Package initialization code
24915 Code in a @code{BEGIN-END} section at the outer level of a package body is
24916 executed as part of the package body elaboration code.
24917
24918 @item Library level task allocators
24919 Tasks that are declared using task allocators at the library level
24920 start executing immediately and hence can execute at elaboration time.
24921 @end table
24922
24923 @noindent
24924 Subprogram calls are possible in any of these contexts, which means that
24925 any arbitrary part of the program may be executed as part of the elaboration
24926 code. It is even possible to write a program which does all its work at
24927 elaboration time, with a null main program, although stylistically this
24928 would usually be considered an inappropriate way to structure
24929 a program.
24930
24931 An important concern arises in the context of elaboration code:
24932 we have to be sure that it is executed in an appropriate order. What we
24933 have is a series of elaboration code sections, potentially one section
24934 for each unit in the program. It is important that these execute
24935 in the correct order. Correctness here means that, taking the above
24936 example of the declaration of @code{Sqrt_Half},
24937 if some other piece of
24938 elaboration code references @code{Sqrt_Half},
24939 then it must run after the
24940 section of elaboration code that contains the declaration of
24941 @code{Sqrt_Half}.
24942
24943 There would never be any order of elaboration problem if we made a rule
24944 that whenever you @code{with} a unit, you must elaborate both the spec and body
24945 of that unit before elaborating the unit doing the @code{with}'ing:
24946
24947 @smallexample @c ada
24948 @group
24949 @cartouche
24950 with Unit_1;
24951 package Unit_2 is @dots{}
24952 @end cartouche
24953 @end group
24954 @end smallexample
24955
24956 @noindent
24957 would require that both the body and spec of @code{Unit_1} be elaborated
24958 before the spec of @code{Unit_2}. However, a rule like that would be far too
24959 restrictive. In particular, it would make it impossible to have routines
24960 in separate packages that were mutually recursive.
24961
24962 You might think that a clever enough compiler could look at the actual
24963 elaboration code and determine an appropriate correct order of elaboration,
24964 but in the general case, this is not possible. Consider the following
24965 example.
24966
24967 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
24968 that references
24969 the variable @code{Sqrt_1}, which is declared in the elaboration code
24970 of the body of @code{Unit_1}:
24971
24972 @smallexample @c ada
24973 @cartouche
24974 Sqrt_1 : Float := Sqrt (0.1);
24975 @end cartouche
24976 @end smallexample
24977
24978 @noindent
24979 The elaboration code of the body of @code{Unit_1} also contains:
24980
24981 @smallexample @c ada
24982 @group
24983 @cartouche
24984 if expression_1 = 1 then
24985    Q := Unit_2.Func_2;
24986 end if;
24987 @end cartouche
24988 @end group
24989 @end smallexample
24990
24991 @noindent
24992 @code{Unit_2} is exactly parallel,
24993 it has a procedure @code{Func_2} that references
24994 the variable @code{Sqrt_2}, which is declared in the elaboration code of
24995 the body @code{Unit_2}:
24996
24997 @smallexample @c ada
24998 @cartouche
24999 Sqrt_2 : Float := Sqrt (0.1);
25000 @end cartouche
25001 @end smallexample
25002
25003 @noindent
25004 The elaboration code of the body of @code{Unit_2} also contains:
25005
25006 @smallexample @c ada
25007 @group
25008 @cartouche
25009 if expression_2 = 2 then
25010    Q := Unit_1.Func_1;
25011 end if;
25012 @end cartouche
25013 @end group
25014 @end smallexample
25015
25016 @noindent
25017 Now the question is, which of the following orders of elaboration is
25018 acceptable:
25019
25020 @smallexample
25021 @group
25022 Spec of Unit_1
25023 Spec of Unit_2
25024 Body of Unit_1
25025 Body of Unit_2
25026 @end group
25027 @end smallexample
25028
25029 @noindent
25030 or
25031
25032 @smallexample
25033 @group
25034 Spec of Unit_2
25035 Spec of Unit_1
25036 Body of Unit_2
25037 Body of Unit_1
25038 @end group
25039 @end smallexample
25040
25041 @noindent
25042 If you carefully analyze the flow here, you will see that you cannot tell
25043 at compile time the answer to this question.
25044 If @code{expression_1} is not equal to 1,
25045 and @code{expression_2} is not equal to 2,
25046 then either order is acceptable, because neither of the function calls is
25047 executed. If both tests evaluate to true, then neither order is acceptable
25048 and in fact there is no correct order.
25049
25050 If one of the two expressions is true, and the other is false, then one
25051 of the above orders is correct, and the other is incorrect. For example,
25052 if @code{expression_1} /= 1 and @code{expression_2} = 2,
25053 then the call to @code{Func_1}
25054 will occur, but not the call to @code{Func_2.}
25055 This means that it is essential
25056 to elaborate the body of @code{Unit_1} before
25057 the body of @code{Unit_2}, so the first
25058 order of elaboration is correct and the second is wrong.
25059
25060 By making @code{expression_1} and @code{expression_2}
25061 depend on input data, or perhaps
25062 the time of day, we can make it impossible for the compiler or binder
25063 to figure out which of these expressions will be true, and hence it
25064 is impossible to guarantee a safe order of elaboration at run time.
25065
25066 @node Checking the Elaboration Order
25067 @section Checking the Elaboration Order
25068
25069 @noindent
25070 In some languages that involve the same kind of elaboration problems,
25071 e.g.@: Java and C++, the programmer is expected to worry about these
25072 ordering problems himself, and it is common to
25073 write a program in which an incorrect elaboration order  gives
25074 surprising results, because it references variables before they
25075 are initialized.
25076 Ada is designed to be a safe language, and a programmer-beware approach is
25077 clearly not sufficient. Consequently, the language provides three lines
25078 of defense:
25079
25080 @table @asis
25081 @item Standard rules
25082 Some standard rules restrict the possible choice of elaboration
25083 order. In particular, if you @code{with} a unit, then its spec is always
25084 elaborated before the unit doing the @code{with}. Similarly, a parent
25085 spec is always elaborated before the child spec, and finally
25086 a spec is always elaborated before its corresponding body.
25087
25088 @item Dynamic elaboration checks
25089 @cindex Elaboration checks
25090 @cindex Checks, elaboration
25091 Dynamic checks are made at run time, so that if some entity is accessed
25092 before it is elaborated (typically  by means of a subprogram call)
25093 then the exception (@code{Program_Error}) is raised.
25094
25095 @item Elaboration control
25096 Facilities are provided for the programmer to specify the desired order
25097 of elaboration.
25098 @end table
25099
25100 Let's look at these facilities in more detail. First, the rules for
25101 dynamic checking. One possible rule would be simply to say that the
25102 exception is raised if you access a variable which has not yet been
25103 elaborated. The trouble with this approach is that it could require
25104 expensive checks on every variable reference. Instead Ada has two
25105 rules which are a little more restrictive, but easier to check, and
25106 easier to state:
25107
25108 @table @asis
25109 @item Restrictions on calls
25110 A subprogram can only be called at elaboration time if its body
25111 has been elaborated. The rules for elaboration given above guarantee
25112 that the spec of the subprogram has been elaborated before the
25113 call, but not the body. If this rule is violated, then the
25114 exception @code{Program_Error} is raised.
25115
25116 @item Restrictions on instantiations
25117 A generic unit can only be instantiated if the body of the generic
25118 unit has been elaborated. Again, the rules for elaboration given above
25119 guarantee that the spec of the generic unit has been elaborated
25120 before the instantiation, but not the body. If this rule is
25121 violated, then the exception @code{Program_Error} is raised.
25122 @end table
25123
25124 @noindent
25125 The idea is that if the body has been elaborated, then any variables
25126 it references must have been elaborated; by checking for the body being
25127 elaborated we guarantee that none of its references causes any
25128 trouble. As we noted above, this is a little too restrictive, because a
25129 subprogram that has no non-local references in its body may in fact be safe
25130 to call. However, it really would be unsafe to rely on this, because
25131 it would mean that the caller was aware of details of the implementation
25132 in the body. This goes against the basic tenets of Ada.
25133
25134 A plausible implementation can be described as follows.
25135 A Boolean variable is associated with each subprogram
25136 and each generic unit. This variable is initialized to False, and is set to
25137 True at the point body is elaborated. Every call or instantiation checks the
25138 variable, and raises @code{Program_Error} if the variable is False.
25139
25140 Note that one might think that it would be good enough to have one Boolean
25141 variable for each package, but that would not deal with cases of trying
25142 to call a body in the same package as the call
25143 that has not been elaborated yet.
25144 Of course a compiler may be able to do enough analysis to optimize away
25145 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
25146 does such optimizations, but still the easiest conceptual model is to
25147 think of there being one variable per subprogram.
25148
25149 @node Controlling the Elaboration Order
25150 @section Controlling the Elaboration Order
25151
25152 @noindent
25153 In the previous section we discussed the rules in Ada which ensure
25154 that @code{Program_Error} is raised if an incorrect elaboration order is
25155 chosen. This prevents erroneous executions, but we need mechanisms to
25156 specify a correct execution and avoid the exception altogether.
25157 To achieve this, Ada provides a number of features for controlling
25158 the order of elaboration. We discuss these features in this section.
25159
25160 First, there are several ways of indicating to the compiler that a given
25161 unit has no elaboration problems:
25162
25163 @table @asis
25164 @item packages that do not require a body
25165 A library package that does not require a body does not permit
25166 a body (this rule was introduced in Ada 95).
25167 Thus if we have a such a package, as in:
25168
25169 @smallexample @c ada
25170 @group
25171 @cartouche
25172 package Definitions is
25173    generic
25174       type m is new integer;
25175    package Subp is
25176       type a is array (1 .. 10) of m;
25177       type b is array (1 .. 20) of m;
25178    end Subp;
25179 end Definitions;
25180 @end cartouche
25181 @end group
25182 @end smallexample
25183
25184 @noindent
25185 A package that @code{with}'s @code{Definitions} may safely instantiate
25186 @code{Definitions.Subp} because the compiler can determine that there
25187 definitely is no package body to worry about in this case
25188
25189 @item pragma Pure
25190 @cindex pragma Pure
25191 @findex Pure
25192 Places sufficient restrictions on a unit to guarantee that
25193 no call to any subprogram in the unit can result in an
25194 elaboration problem. This means that the compiler does not need
25195 to worry about the point of elaboration of such units, and in
25196 particular, does not need to check any calls to any subprograms
25197 in this unit.
25198
25199 @item pragma Preelaborate
25200 @findex Preelaborate
25201 @cindex pragma Preelaborate
25202 This pragma places slightly less stringent restrictions on a unit than
25203 does pragma Pure,
25204 but these restrictions are still sufficient to ensure that there
25205 are no elaboration problems with any calls to the unit.
25206
25207 @item pragma Elaborate_Body
25208 @findex Elaborate_Body
25209 @cindex pragma Elaborate_Body
25210 This pragma requires that the body of a unit be elaborated immediately
25211 after its spec. Suppose a unit @code{A} has such a pragma,
25212 and unit @code{B} does
25213 a @code{with} of unit @code{A}. Recall that the standard rules require
25214 the spec of unit @code{A}
25215 to be elaborated before the @code{with}'ing unit; given the pragma in
25216 @code{A}, we also know that the body of @code{A}
25217 will be elaborated before @code{B}, so
25218 that calls to @code{A} are safe and do not need a check.
25219 @end table
25220
25221 @noindent
25222 Note that,
25223 unlike pragma @code{Pure} and pragma @code{Preelaborate},
25224 the use of
25225 @code{Elaborate_Body} does not guarantee that the program is
25226 free of elaboration problems, because it may not be possible
25227 to satisfy the requested elaboration order.
25228 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
25229 If a programmer
25230 marks @code{Unit_1} as @code{Elaborate_Body},
25231 and not @code{Unit_2,} then the order of
25232 elaboration will be:
25233
25234 @smallexample
25235 @group
25236 Spec of Unit_2
25237 Spec of Unit_1
25238 Body of Unit_1
25239 Body of Unit_2
25240 @end group
25241 @end smallexample
25242
25243 @noindent
25244 Now that means that the call to @code{Func_1} in @code{Unit_2}
25245 need not be checked,
25246 it must be safe. But the call to @code{Func_2} in
25247 @code{Unit_1} may still fail if
25248 @code{Expression_1} is equal to 1,
25249 and the programmer must still take
25250 responsibility for this not being the case.
25251
25252 If all units carry a pragma @code{Elaborate_Body}, then all problems are
25253 eliminated, except for calls entirely within a body, which are
25254 in any case fully under programmer control. However, using the pragma
25255 everywhere is not always possible.
25256 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
25257 we marked both of them as having pragma @code{Elaborate_Body}, then
25258 clearly there would be no possible elaboration order.
25259
25260 The above pragmas allow a server to guarantee safe use by clients, and
25261 clearly this is the preferable approach. Consequently a good rule
25262 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
25263 and if this is not possible,
25264 mark them as @code{Elaborate_Body} if possible.
25265 As we have seen, there are situations where neither of these
25266 three pragmas can be used.
25267 So we also provide methods for clients to control the
25268 order of elaboration of the servers on which they depend:
25269
25270 @table @asis
25271 @item pragma Elaborate (unit)
25272 @findex Elaborate
25273 @cindex pragma Elaborate
25274 This pragma is placed in the context clause, after a @code{with} clause,
25275 and it requires that the body of the named unit be elaborated before
25276 the unit in which the pragma occurs. The idea is to use this pragma
25277 if the current unit calls at elaboration time, directly or indirectly,
25278 some subprogram in the named unit.
25279
25280 @item pragma Elaborate_All (unit)
25281 @findex Elaborate_All
25282 @cindex pragma Elaborate_All
25283 This is a stronger version of the Elaborate pragma. Consider the
25284 following example:
25285
25286 @smallexample
25287 Unit A @code{with}'s unit B and calls B.Func in elab code
25288 Unit B @code{with}'s unit C, and B.Func calls C.Func
25289 @end smallexample
25290
25291 @noindent
25292 Now if we put a pragma @code{Elaborate (B)}
25293 in unit @code{A}, this ensures that the
25294 body of @code{B} is elaborated before the call, but not the
25295 body of @code{C}, so
25296 the call to @code{C.Func} could still cause @code{Program_Error} to
25297 be raised.
25298
25299 The effect of a pragma @code{Elaborate_All} is stronger, it requires
25300 not only that the body of the named unit be elaborated before the
25301 unit doing the @code{with}, but also the bodies of all units that the
25302 named unit uses, following @code{with} links transitively. For example,
25303 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
25304 then it requires
25305 not only that the body of @code{B} be elaborated before @code{A},
25306 but also the
25307 body of @code{C}, because @code{B} @code{with}'s @code{C}.
25308 @end table
25309
25310 @noindent
25311 We are now in a position to give a usage rule in Ada for avoiding
25312 elaboration problems, at least if dynamic dispatching and access to
25313 subprogram values are not used. We will handle these cases separately
25314 later.
25315
25316 The rule is simple. If a unit has elaboration code that can directly or
25317 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
25318 a generic package in a @code{with}'ed unit,
25319 then if the @code{with}'ed unit does not have
25320 pragma @code{Pure} or @code{Preelaborate}, then the client should have
25321 a pragma @code{Elaborate_All}
25322 for the @code{with}'ed unit. By following this rule a client is
25323 assured that calls can be made without risk of an exception.
25324
25325 For generic subprogram instantiations, the rule can be relaxed to
25326 require only a pragma @code{Elaborate} since elaborating the body
25327 of a subprogram cannot cause any transitive elaboration (we are
25328 not calling the subprogram in this case, just elaborating its
25329 declaration).
25330
25331 If this rule is not followed, then a program may be in one of four
25332 states:
25333
25334 @table @asis
25335 @item No order exists
25336 No order of elaboration exists which follows the rules, taking into
25337 account any @code{Elaborate}, @code{Elaborate_All},
25338 or @code{Elaborate_Body} pragmas. In
25339 this case, an Ada compiler must diagnose the situation at bind
25340 time, and refuse to build an executable program.
25341
25342 @item One or more orders exist, all incorrect
25343 One or more acceptable elaboration orders exist, and all of them
25344 generate an elaboration order problem. In this case, the binder
25345 can build an executable program, but @code{Program_Error} will be raised
25346 when the program is run.
25347
25348 @item Several orders exist, some right, some incorrect
25349 One or more acceptable elaboration orders exists, and some of them
25350 work, and some do not. The programmer has not controlled
25351 the order of elaboration, so the binder may or may not pick one of
25352 the correct orders, and the program may or may not raise an
25353 exception when it is run. This is the worst case, because it means
25354 that the program may fail when moved to another compiler, or even
25355 another version of the same compiler.
25356
25357 @item One or more orders exists, all correct
25358 One ore more acceptable elaboration orders exist, and all of them
25359 work. In this case the program runs successfully. This state of
25360 affairs can be guaranteed by following the rule we gave above, but
25361 may be true even if the rule is not followed.
25362 @end table
25363
25364 @noindent
25365 Note that one additional advantage of following our rules on the use
25366 of @code{Elaborate} and @code{Elaborate_All}
25367 is that the program continues to stay in the ideal (all orders OK) state
25368 even if maintenance
25369 changes some bodies of some units. Conversely, if a program that does
25370 not follow this rule happens to be safe at some point, this state of affairs
25371 may deteriorate silently as a result of maintenance changes.
25372
25373 You may have noticed that the above discussion did not mention
25374 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
25375 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
25376 code in the body makes calls to some other unit, so it is still necessary
25377 to use @code{Elaborate_All} on such units.
25378
25379 @node Controlling Elaboration in GNAT - Internal Calls
25380 @section Controlling Elaboration in GNAT - Internal Calls
25381
25382 @noindent
25383 In the case of internal calls, i.e., calls within a single package, the
25384 programmer has full control over the order of elaboration, and it is up
25385 to the programmer to elaborate declarations in an appropriate order. For
25386 example writing:
25387
25388 @smallexample @c ada
25389 @group
25390 @cartouche
25391 function One return Float;
25392
25393 Q : Float := One;
25394
25395 function One return Float is
25396 begin
25397      return 1.0;
25398 end One;
25399 @end cartouche
25400 @end group
25401 @end smallexample
25402
25403 @noindent
25404 will obviously raise @code{Program_Error} at run time, because function
25405 One will be called before its body is elaborated. In this case GNAT will
25406 generate a warning that the call will raise @code{Program_Error}:
25407
25408 @smallexample
25409 @group
25410 @cartouche
25411  1. procedure y is
25412  2.    function One return Float;
25413  3.
25414  4.    Q : Float := One;
25415                     |
25416     >>> warning: cannot call "One" before body is elaborated
25417     >>> warning: Program_Error will be raised at run time
25418
25419  5.
25420  6.    function One return Float is
25421  7.    begin
25422  8.         return 1.0;
25423  9.    end One;
25424 10.
25425 11. begin
25426 12.    null;
25427 13. end;
25428 @end cartouche
25429 @end group
25430 @end smallexample
25431
25432 @noindent
25433 Note that in this particular case, it is likely that the call is safe, because
25434 the function @code{One} does not access any global variables.
25435 Nevertheless in Ada, we do not want the validity of the check to depend on
25436 the contents of the body (think about the separate compilation case), so this
25437 is still wrong, as we discussed in the previous sections.
25438
25439 The error is easily corrected by rearranging the declarations so that the
25440 body of @code{One} appears before the declaration containing the call
25441 (note that in Ada 95 and Ada 2005,
25442 declarations can appear in any order, so there is no restriction that
25443 would prevent this reordering, and if we write:
25444
25445 @smallexample @c ada
25446 @group
25447 @cartouche
25448 function One return Float;
25449
25450 function One return Float is
25451 begin
25452      return 1.0;
25453 end One;
25454
25455 Q : Float := One;
25456 @end cartouche
25457 @end group
25458 @end smallexample
25459
25460 @noindent
25461 then all is well, no warning is generated, and no
25462 @code{Program_Error} exception
25463 will be raised.
25464 Things are more complicated when a chain of subprograms is executed:
25465
25466 @smallexample @c ada
25467 @group
25468 @cartouche
25469 function A return Integer;
25470 function B return Integer;
25471 function C return Integer;
25472
25473 function B return Integer is begin return A; end;
25474 function C return Integer is begin return B; end;
25475
25476 X : Integer := C;
25477
25478 function A return Integer is begin return 1; end;
25479 @end cartouche
25480 @end group
25481 @end smallexample
25482
25483 @noindent
25484 Now the call to @code{C}
25485 at elaboration time in the declaration of @code{X} is correct, because
25486 the body of @code{C} is already elaborated,
25487 and the call to @code{B} within the body of
25488 @code{C} is correct, but the call
25489 to @code{A} within the body of @code{B} is incorrect, because the body
25490 of @code{A} has not been elaborated, so @code{Program_Error}
25491 will be raised on the call to @code{A}.
25492 In this case GNAT will generate a
25493 warning that @code{Program_Error} may be
25494 raised at the point of the call. Let's look at the warning:
25495
25496 @smallexample
25497 @group
25498 @cartouche
25499  1. procedure x is
25500  2.    function A return Integer;
25501  3.    function B return Integer;
25502  4.    function C return Integer;
25503  5.
25504  6.    function B return Integer is begin return A; end;
25505                                                     |
25506     >>> warning: call to "A" before body is elaborated may
25507                  raise Program_Error
25508     >>> warning: "B" called at line 7
25509     >>> warning: "C" called at line 9
25510
25511  7.    function C return Integer is begin return B; end;
25512  8.
25513  9.    X : Integer := C;
25514 10.
25515 11.    function A return Integer is begin return 1; end;
25516 12.
25517 13. begin
25518 14.    null;
25519 15. end;
25520 @end cartouche
25521 @end group
25522 @end smallexample
25523
25524 @noindent
25525 Note that the message here says ``may raise'', instead of the direct case,
25526 where the message says ``will be raised''. That's because whether
25527 @code{A} is
25528 actually called depends in general on run-time flow of control.
25529 For example, if the body of @code{B} said
25530
25531 @smallexample @c ada
25532 @group
25533 @cartouche
25534 function B return Integer is
25535 begin
25536    if some-condition-depending-on-input-data then
25537       return A;
25538    else
25539       return 1;
25540    end if;
25541 end B;
25542 @end cartouche
25543 @end group
25544 @end smallexample
25545
25546 @noindent
25547 then we could not know until run time whether the incorrect call to A would
25548 actually occur, so @code{Program_Error} might
25549 or might not be raised. It is possible for a compiler to
25550 do a better job of analyzing bodies, to
25551 determine whether or not @code{Program_Error}
25552 might be raised, but it certainly
25553 couldn't do a perfect job (that would require solving the halting problem
25554 and is provably impossible), and because this is a warning anyway, it does
25555 not seem worth the effort to do the analysis. Cases in which it
25556 would be relevant are rare.
25557
25558 In practice, warnings of either of the forms given
25559 above will usually correspond to
25560 real errors, and should be examined carefully and eliminated.
25561 In the rare case where a warning is bogus, it can be suppressed by any of
25562 the following methods:
25563
25564 @itemize @bullet
25565 @item
25566 Compile with the @option{-gnatws} switch set
25567
25568 @item
25569 Suppress @code{Elaboration_Check} for the called subprogram
25570
25571 @item
25572 Use pragma @code{Warnings_Off} to turn warnings off for the call
25573 @end itemize
25574
25575 @noindent
25576 For the internal elaboration check case,
25577 GNAT by default generates the
25578 necessary run-time checks to ensure
25579 that @code{Program_Error} is raised if any
25580 call fails an elaboration check. Of course this can only happen if a
25581 warning has been issued as described above. The use of pragma
25582 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
25583 some of these checks, meaning that it may be possible (but is not
25584 guaranteed) for a program to be able to call a subprogram whose body
25585 is not yet elaborated, without raising a @code{Program_Error} exception.
25586
25587 @node Controlling Elaboration in GNAT - External Calls
25588 @section Controlling Elaboration in GNAT - External Calls
25589
25590 @noindent
25591 The previous section discussed the case in which the execution of a
25592 particular thread of elaboration code occurred entirely within a
25593 single unit. This is the easy case to handle, because a programmer
25594 has direct and total control over the order of elaboration, and
25595 furthermore, checks need only be generated in cases which are rare
25596 and which the compiler can easily detect.
25597 The situation is more complex when separate compilation is taken into account.
25598 Consider the following:
25599
25600 @smallexample @c ada
25601 @cartouche
25602 @group
25603 package Math is
25604    function Sqrt (Arg : Float) return Float;
25605 end Math;
25606
25607 package body Math is
25608    function Sqrt (Arg : Float) return Float is
25609    begin
25610          @dots{}
25611    end Sqrt;
25612 end Math;
25613 @end group
25614 @group
25615 with Math;
25616 package Stuff is
25617    X : Float := Math.Sqrt (0.5);
25618 end Stuff;
25619
25620 with Stuff;
25621 procedure Main is
25622 begin
25623    @dots{}
25624 end Main;
25625 @end group
25626 @end cartouche
25627 @end smallexample
25628
25629 @noindent
25630 where @code{Main} is the main program. When this program is executed, the
25631 elaboration code must first be executed, and one of the jobs of the
25632 binder is to determine the order in which the units of a program are
25633 to be elaborated. In this case we have four units: the spec and body
25634 of @code{Math},
25635 the spec of @code{Stuff} and the body of @code{Main}).
25636 In what order should the four separate sections of elaboration code
25637 be executed?
25638
25639 There are some restrictions in the order of elaboration that the binder
25640 can choose. In particular, if unit U has a @code{with}
25641 for a package @code{X}, then you
25642 are assured that the spec of @code{X}
25643 is elaborated before U , but you are
25644 not assured that the body of @code{X}
25645 is elaborated before U.
25646 This means that in the above case, the binder is allowed to choose the
25647 order:
25648
25649 @smallexample
25650 spec of Math
25651 spec of Stuff
25652 body of Math
25653 body of Main
25654 @end smallexample
25655
25656 @noindent
25657 but that's not good, because now the call to @code{Math.Sqrt}
25658 that happens during
25659 the elaboration of the @code{Stuff}
25660 spec happens before the body of @code{Math.Sqrt} is
25661 elaborated, and hence causes @code{Program_Error} exception to be raised.
25662 At first glance, one might say that the binder is misbehaving, because
25663 obviously you want to elaborate the body of something you @code{with}
25664 first, but
25665 that is not a general rule that can be followed in all cases. Consider
25666
25667 @smallexample @c ada
25668 @group
25669 @cartouche
25670 package X is @dots{}
25671
25672 package Y is @dots{}
25673
25674 with X;
25675 package body Y is @dots{}
25676
25677 with Y;
25678 package body X is @dots{}
25679 @end cartouche
25680 @end group
25681 @end smallexample
25682
25683 @noindent
25684 This is a common arrangement, and, apart from the order of elaboration
25685 problems that might arise in connection with elaboration code, this works fine.
25686 A rule that says that you must first elaborate the body of anything you
25687 @code{with} cannot work in this case:
25688 the body of @code{X} @code{with}'s @code{Y},
25689 which means you would have to
25690 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
25691 which means
25692 you have to elaborate the body of @code{X} first, but @dots{} and we have a
25693 loop that cannot be broken.
25694
25695 It is true that the binder can in many cases guess an order of elaboration
25696 that is unlikely to cause a @code{Program_Error}
25697 exception to be raised, and it tries to do so (in the
25698 above example of @code{Math/Stuff/Spec}, the GNAT binder will
25699 by default
25700 elaborate the body of @code{Math} right after its spec, so all will be well).
25701
25702 However, a program that blindly relies on the binder to be helpful can
25703 get into trouble, as we discussed in the previous sections, so
25704 GNAT
25705 provides a number of facilities for assisting the programmer in
25706 developing programs that are robust with respect to elaboration order.
25707
25708 @node Default Behavior in GNAT - Ensuring Safety
25709 @section Default Behavior in GNAT - Ensuring Safety
25710
25711 @noindent
25712 The default behavior in GNAT ensures elaboration safety. In its
25713 default mode GNAT implements the
25714 rule we previously described as the right approach. Let's restate it:
25715
25716 @itemize
25717 @item
25718 @emph{If a unit has elaboration code that can directly or indirectly make a
25719 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
25720 package in a @code{with}'ed unit, then if the @code{with}'ed unit
25721 does not have pragma @code{Pure} or
25722 @code{Preelaborate}, then the client should have an
25723 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
25724
25725 @emph{In the case of instantiating a generic subprogram, it is always
25726 sufficient to have only an @code{Elaborate} pragma for the
25727 @code{with}'ed unit.}
25728 @end itemize
25729
25730 @noindent
25731 By following this rule a client is assured that calls and instantiations
25732 can be made without risk of an exception.
25733
25734 In this mode GNAT traces all calls that are potentially made from
25735 elaboration code, and puts in any missing implicit @code{Elaborate}
25736 and @code{Elaborate_All} pragmas.
25737 The advantage of this approach is that no elaboration problems
25738 are possible if the binder can find an elaboration order that is
25739 consistent with these implicit @code{Elaborate} and
25740 @code{Elaborate_All} pragmas. The
25741 disadvantage of this approach is that no such order may exist.
25742
25743 If the binder does not generate any diagnostics, then it means that it has
25744 found an elaboration order that is guaranteed to be safe. However, the binder
25745 may still be relying on implicitly generated @code{Elaborate} and
25746 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
25747 guaranteed.
25748
25749 If it is important to guarantee portability, then the compilations should
25750 use the
25751 @option{-gnatwl}
25752 (warn on elaboration problems) switch. This will cause warning messages
25753 to be generated indicating the missing @code{Elaborate} and
25754 @code{Elaborate_All} pragmas.
25755 Consider the following source program:
25756
25757 @smallexample @c ada
25758 @group
25759 @cartouche
25760 with k;
25761 package j is
25762   m : integer := k.r;
25763 end;
25764 @end cartouche
25765 @end group
25766 @end smallexample
25767
25768 @noindent
25769 where it is clear that there
25770 should be a pragma @code{Elaborate_All}
25771 for unit @code{k}. An implicit pragma will be generated, and it is
25772 likely that the binder will be able to honor it. However, if you want
25773 to port this program to some other Ada compiler than GNAT.
25774 it is safer to include the pragma explicitly in the source. If this
25775 unit is compiled with the
25776 @option{-gnatwl}
25777 switch, then the compiler outputs a warning:
25778
25779 @smallexample
25780 @group
25781 @cartouche
25782 1. with k;
25783 2. package j is
25784 3.   m : integer := k.r;
25785                      |
25786    >>> warning: call to "r" may raise Program_Error
25787    >>> warning: missing pragma Elaborate_All for "k"
25788
25789 4. end;
25790 @end cartouche
25791 @end group
25792 @end smallexample
25793
25794 @noindent
25795 and these warnings can be used as a guide for supplying manually
25796 the missing pragmas. It is usually a bad idea to use this warning
25797 option during development. That's because it will warn you when
25798 you need to put in a pragma, but cannot warn you when it is time
25799 to take it out. So the use of pragma @code{Elaborate_All} may lead to
25800 unnecessary dependencies and even false circularities.
25801
25802 This default mode is more restrictive than the Ada Reference
25803 Manual, and it is possible to construct programs which will compile
25804 using the dynamic model described there, but will run into a
25805 circularity using the safer static model we have described.
25806
25807 Of course any Ada compiler must be able to operate in a mode
25808 consistent with the requirements of the Ada Reference Manual,
25809 and in particular must have the capability of implementing the
25810 standard dynamic model of elaboration with run-time checks.
25811
25812 In GNAT, this standard mode can be achieved either by the use of
25813 the @option{-gnatE} switch on the compiler (@command{gcc} or
25814 @command{gnatmake}) command, or by the use of the configuration pragma:
25815
25816 @smallexample @c ada
25817 pragma Elaboration_Checks (DYNAMIC);
25818 @end smallexample
25819
25820 @noindent
25821 Either approach will cause the unit affected to be compiled using the
25822 standard dynamic run-time elaboration checks described in the Ada
25823 Reference Manual. The static model is generally preferable, since it
25824 is clearly safer to rely on compile and link time checks rather than
25825 run-time checks. However, in the case of legacy code, it may be
25826 difficult to meet the requirements of the static model. This
25827 issue is further discussed in
25828 @ref{What to Do If the Default Elaboration Behavior Fails}.
25829
25830 Note that the static model provides a strict subset of the allowed
25831 behavior and programs of the Ada Reference Manual, so if you do
25832 adhere to the static model and no circularities exist,
25833 then you are assured that your program will
25834 work using the dynamic model, providing that you remove any
25835 pragma Elaborate statements from the source.
25836
25837 @node Treatment of Pragma Elaborate
25838 @section Treatment of Pragma Elaborate
25839 @cindex Pragma Elaborate
25840
25841 @noindent
25842 The use of @code{pragma Elaborate}
25843 should generally be avoided in Ada 95 and Ada 2005 programs,
25844 since there is no guarantee that transitive calls
25845 will be properly handled. Indeed at one point, this pragma was placed
25846 in Annex J (Obsolescent Features), on the grounds that it is never useful.
25847
25848 Now that's a bit restrictive. In practice, the case in which
25849 @code{pragma Elaborate} is useful is when the caller knows that there
25850 are no transitive calls, or that the called unit contains all necessary
25851 transitive @code{pragma Elaborate} statements, and legacy code often
25852 contains such uses.
25853
25854 Strictly speaking the static mode in GNAT should ignore such pragmas,
25855 since there is no assurance at compile time that the necessary safety
25856 conditions are met. In practice, this would cause GNAT to be incompatible
25857 with correctly written Ada 83 code that had all necessary
25858 @code{pragma Elaborate} statements in place. Consequently, we made the
25859 decision that GNAT in its default mode will believe that if it encounters
25860 a @code{pragma Elaborate} then the programmer knows what they are doing,
25861 and it will trust that no elaboration errors can occur.
25862
25863 The result of this decision is two-fold. First to be safe using the
25864 static mode, you should remove all @code{pragma Elaborate} statements.
25865 Second, when fixing circularities in existing code, you can selectively
25866 use @code{pragma Elaborate} statements to convince the static mode of
25867 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
25868 statement.
25869
25870 When using the static mode with @option{-gnatwl}, any use of
25871 @code{pragma Elaborate} will generate a warning about possible
25872 problems.
25873
25874 @node Elaboration Issues for Library Tasks
25875 @section Elaboration Issues for Library Tasks
25876 @cindex Library tasks, elaboration issues
25877 @cindex Elaboration of library tasks
25878
25879 @noindent
25880 In this section we examine special elaboration issues that arise for
25881 programs that declare library level tasks.
25882
25883 Generally the model of execution of an Ada program is that all units are
25884 elaborated, and then execution of the program starts. However, the
25885 declaration of library tasks definitely does not fit this model. The
25886 reason for this is that library tasks start as soon as they are declared
25887 (more precisely, as soon as the statement part of the enclosing package
25888 body is reached), that is to say before elaboration
25889 of the program is complete. This means that if such a task calls a
25890 subprogram, or an entry in another task, the callee may or may not be
25891 elaborated yet, and in the standard
25892 Reference Manual model of dynamic elaboration checks, you can even
25893 get timing dependent Program_Error exceptions, since there can be
25894 a race between the elaboration code and the task code.
25895
25896 The static model of elaboration in GNAT seeks to avoid all such
25897 dynamic behavior, by being conservative, and the conservative
25898 approach in this particular case is to assume that all the code
25899 in a task body is potentially executed at elaboration time if
25900 a task is declared at the library level.
25901
25902 This can definitely result in unexpected circularities. Consider
25903 the following example
25904
25905 @smallexample @c ada
25906 package Decls is
25907   task Lib_Task is
25908      entry Start;
25909   end Lib_Task;
25910
25911   type My_Int is new Integer;
25912
25913   function Ident (M : My_Int) return My_Int;
25914 end Decls;
25915
25916 with Utils;
25917 package body Decls is
25918   task body Lib_Task is
25919   begin
25920      accept Start;
25921      Utils.Put_Val (2);
25922   end Lib_Task;
25923
25924   function Ident (M : My_Int) return My_Int is
25925   begin
25926      return M;
25927   end Ident;
25928 end Decls;
25929
25930 with Decls;
25931 package Utils is
25932   procedure Put_Val (Arg : Decls.My_Int);
25933 end Utils;
25934
25935 with Text_IO;
25936 package body Utils is
25937   procedure Put_Val (Arg : Decls.My_Int) is
25938   begin
25939      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
25940   end Put_Val;
25941 end Utils;
25942
25943 with Decls;
25944 procedure Main is
25945 begin
25946    Decls.Lib_Task.Start;
25947 end;
25948 @end smallexample
25949
25950 @noindent
25951 If the above example is compiled in the default static elaboration
25952 mode, then a circularity occurs. The circularity comes from the call
25953 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
25954 this call occurs in elaboration code, we need an implicit pragma
25955 @code{Elaborate_All} for @code{Utils}. This means that not only must
25956 the spec and body of @code{Utils} be elaborated before the body
25957 of @code{Decls}, but also the spec and body of any unit that is
25958 @code{with'ed} by the body of @code{Utils} must also be elaborated before
25959 the body of @code{Decls}. This is the transitive implication of
25960 pragma @code{Elaborate_All} and it makes sense, because in general
25961 the body of @code{Put_Val} might have a call to something in a
25962 @code{with'ed} unit.
25963
25964 In this case, the body of Utils (actually its spec) @code{with's}
25965 @code{Decls}. Unfortunately this means that the body of @code{Decls}
25966 must be elaborated before itself, in case there is a call from the
25967 body of @code{Utils}.
25968
25969 Here is the exact chain of events we are worrying about:
25970
25971 @enumerate
25972 @item
25973 In the body of @code{Decls} a call is made from within the body of a library
25974 task to a subprogram in the package @code{Utils}. Since this call may
25975 occur at elaboration time (given that the task is activated at elaboration
25976 time), we have to assume the worst, i.e., that the
25977 call does happen at elaboration time.
25978
25979 @item
25980 This means that the body and spec of @code{Util} must be elaborated before
25981 the body of @code{Decls} so that this call does not cause an access before
25982 elaboration.
25983
25984 @item
25985 Within the body of @code{Util}, specifically within the body of
25986 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
25987 by this package.
25988
25989 @item
25990 One such @code{with}'ed package is package @code{Decls}, so there
25991 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
25992 In fact there is such a call in this example, but we would have to
25993 assume that there was such a call even if it were not there, since
25994 we are not supposed to write the body of @code{Decls} knowing what
25995 is in the body of @code{Utils}; certainly in the case of the
25996 static elaboration model, the compiler does not know what is in
25997 other bodies and must assume the worst.
25998
25999 @item
26000 This means that the spec and body of @code{Decls} must also be
26001 elaborated before we elaborate the unit containing the call, but
26002 that unit is @code{Decls}! This means that the body of @code{Decls}
26003 must be elaborated before itself, and that's a circularity.
26004 @end enumerate
26005
26006 @noindent
26007 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
26008 the body of @code{Decls} you will get a true Ada Reference Manual
26009 circularity that makes the program illegal.
26010
26011 In practice, we have found that problems with the static model of
26012 elaboration in existing code often arise from library tasks, so
26013 we must address this particular situation.
26014
26015 Note that if we compile and run the program above, using the dynamic model of
26016 elaboration (that is to say use the @option{-gnatE} switch),
26017 then it compiles, binds,
26018 links, and runs, printing the expected result of 2. Therefore in some sense
26019 the circularity here is only apparent, and we need to capture
26020 the properties of this program that  distinguish it from other library-level
26021 tasks that have real elaboration problems.
26022
26023 We have four possible answers to this question:
26024
26025 @itemize @bullet
26026
26027 @item
26028 Use the dynamic model of elaboration.
26029
26030 If we use the @option{-gnatE} switch, then as noted above, the program works.
26031 Why is this? If we examine the task body, it is apparent that the task cannot
26032 proceed past the
26033 @code{accept} statement until after elaboration has been completed, because
26034 the corresponding entry call comes from the main program, not earlier.
26035 This is why the dynamic model works here. But that's really giving
26036 up on a precise analysis, and we prefer to take this approach only if we cannot
26037 solve the
26038 problem in any other manner. So let us examine two ways to reorganize
26039 the program to avoid the potential elaboration problem.
26040
26041 @item
26042 Split library tasks into separate packages.
26043
26044 Write separate packages, so that library tasks are isolated from
26045 other declarations as much as possible. Let us look at a variation on
26046 the above program.
26047
26048 @smallexample @c ada
26049 package Decls1 is
26050   task Lib_Task is
26051      entry Start;
26052   end Lib_Task;
26053 end Decls1;
26054
26055 with Utils;
26056 package body Decls1 is
26057   task body Lib_Task is
26058   begin
26059      accept Start;
26060      Utils.Put_Val (2);
26061   end Lib_Task;
26062 end Decls1;
26063
26064 package Decls2 is
26065   type My_Int is new Integer;
26066   function Ident (M : My_Int) return My_Int;
26067 end Decls2;
26068
26069 with Utils;
26070 package body Decls2 is
26071   function Ident (M : My_Int) return My_Int is
26072   begin
26073      return M;
26074   end Ident;
26075 end Decls2;
26076
26077 with Decls2;
26078 package Utils is
26079   procedure Put_Val (Arg : Decls2.My_Int);
26080 end Utils;
26081
26082 with Text_IO;
26083 package body Utils is
26084   procedure Put_Val (Arg : Decls2.My_Int) is
26085   begin
26086      Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
26087   end Put_Val;
26088 end Utils;
26089
26090 with Decls1;
26091 procedure Main is
26092 begin
26093    Decls1.Lib_Task.Start;
26094 end;
26095 @end smallexample
26096
26097 @noindent
26098 All we have done is to split @code{Decls} into two packages, one
26099 containing the library task, and one containing everything else. Now
26100 there is no cycle, and the program compiles, binds, links and executes
26101 using the default static model of elaboration.
26102
26103 @item
26104 Declare separate task types.
26105
26106 A significant part of the problem arises because of the use of the
26107 single task declaration form. This means that the elaboration of
26108 the task type, and the elaboration of the task itself (i.e.@: the
26109 creation of the task) happen at the same time. A good rule
26110 of style in Ada is to always create explicit task types. By
26111 following the additional step of placing task objects in separate
26112 packages from the task type declaration, many elaboration problems
26113 are avoided. Here is another modified example of the example program:
26114
26115 @smallexample @c ada
26116 package Decls is
26117   task type Lib_Task_Type is
26118      entry Start;
26119   end Lib_Task_Type;
26120
26121   type My_Int is new Integer;
26122
26123   function Ident (M : My_Int) return My_Int;
26124 end Decls;
26125
26126 with Utils;
26127 package body Decls is
26128   task body Lib_Task_Type is
26129   begin
26130      accept Start;
26131      Utils.Put_Val (2);
26132   end Lib_Task_Type;
26133
26134   function Ident (M : My_Int) return My_Int is
26135   begin
26136      return M;
26137   end Ident;
26138 end Decls;
26139
26140 with Decls;
26141 package Utils is
26142   procedure Put_Val (Arg : Decls.My_Int);
26143 end Utils;
26144
26145 with Text_IO;
26146 package body Utils is
26147   procedure Put_Val (Arg : Decls.My_Int) is
26148   begin
26149      Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
26150   end Put_Val;
26151 end Utils;
26152
26153 with Decls;
26154 package Declst is
26155    Lib_Task : Decls.Lib_Task_Type;
26156 end Declst;
26157
26158 with Declst;
26159 procedure Main is
26160 begin
26161    Declst.Lib_Task.Start;
26162 end;
26163 @end smallexample
26164
26165 @noindent
26166 What we have done here is to replace the @code{task} declaration in
26167 package @code{Decls} with a @code{task type} declaration. Then we
26168 introduce a separate package @code{Declst} to contain the actual
26169 task object. This separates the elaboration issues for
26170 the @code{task type}
26171 declaration, which causes no trouble, from the elaboration issues
26172 of the task object, which is also unproblematic, since it is now independent
26173 of the elaboration of  @code{Utils}.
26174 This separation of concerns also corresponds to
26175 a generally sound engineering principle of separating declarations
26176 from instances. This version of the program also compiles, binds, links,
26177 and executes, generating the expected output.
26178
26179 @item
26180 Use No_Entry_Calls_In_Elaboration_Code restriction.
26181 @cindex No_Entry_Calls_In_Elaboration_Code
26182
26183 The previous two approaches described how a program can be restructured
26184 to avoid the special problems caused by library task bodies. in practice,
26185 however, such restructuring may be difficult to apply to existing legacy code,
26186 so we must consider solutions that do not require massive rewriting.
26187
26188 Let us consider more carefully why our original sample program works
26189 under the dynamic model of elaboration. The reason is that the code
26190 in the task body blocks immediately on the @code{accept}
26191 statement. Now of course there is nothing to prohibit elaboration
26192 code from making entry calls (for example from another library level task),
26193 so we cannot tell in isolation that
26194 the task will not execute the accept statement  during elaboration.
26195
26196 However, in practice it is very unusual to see elaboration code
26197 make any entry calls, and the pattern of tasks starting
26198 at elaboration time and then immediately blocking on @code{accept} or
26199 @code{select} statements is very common. What this means is that
26200 the compiler is being too pessimistic when it analyzes the
26201 whole package body as though it might be executed at elaboration
26202 time.
26203
26204 If we know that the elaboration code contains no entry calls, (a very safe
26205 assumption most of the time, that could almost be made the default
26206 behavior), then we can compile all units of the program under control
26207 of the following configuration pragma:
26208
26209 @smallexample
26210 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
26211 @end smallexample
26212
26213 @noindent
26214 This pragma can be placed in the @file{gnat.adc} file in the usual
26215 manner. If we take our original unmodified program and compile it
26216 in the presence of a @file{gnat.adc} containing the above pragma,
26217 then once again, we can compile, bind, link, and execute, obtaining
26218 the expected result. In the presence of this pragma, the compiler does
26219 not trace calls in a task body, that appear after the first @code{accept}
26220 or @code{select} statement, and therefore does not report a potential
26221 circularity in the original program.
26222
26223 The compiler will check to the extent it can that the above
26224 restriction is not violated, but it is not always possible to do a
26225 complete check at compile time, so it is important to use this
26226 pragma only if the stated restriction is in fact met, that is to say
26227 no task receives an entry call before elaboration of all units is completed.
26228
26229 @end itemize
26230
26231 @node Mixing Elaboration Models
26232 @section Mixing Elaboration Models
26233 @noindent
26234 So far, we have assumed that the entire program is either compiled
26235 using the dynamic model or static model, ensuring consistency. It
26236 is possible to mix the two models, but rules have to be followed
26237 if this mixing is done to ensure that elaboration checks are not
26238 omitted.
26239
26240 The basic rule is that @emph{a unit compiled with the static model cannot
26241 be @code{with'ed} by a unit compiled with the dynamic model}. The
26242 reason for this is that in the static model, a unit assumes that
26243 its clients guarantee to use (the equivalent of) pragma
26244 @code{Elaborate_All} so that no elaboration checks are required
26245 in inner subprograms, and this assumption is violated if the
26246 client is compiled with dynamic checks.
26247
26248 The precise rule is as follows. A unit that is compiled with dynamic
26249 checks can only @code{with} a unit that meets at least one of the
26250 following criteria:
26251
26252 @itemize @bullet
26253
26254 @item
26255 The @code{with'ed} unit is itself compiled with dynamic elaboration
26256 checks (that is with the @option{-gnatE} switch.
26257
26258 @item
26259 The @code{with'ed} unit is an internal GNAT implementation unit from
26260 the System, Interfaces, Ada, or GNAT hierarchies.
26261
26262 @item
26263 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
26264
26265 @item
26266 The @code{with'ing} unit (that is the client) has an explicit pragma
26267 @code{Elaborate_All} for the @code{with'ed} unit.
26268
26269 @end itemize
26270
26271 @noindent
26272 If this rule is violated, that is if a unit with dynamic elaboration
26273 checks @code{with's} a unit that does not meet one of the above four
26274 criteria, then the binder (@code{gnatbind}) will issue a warning
26275 similar to that in the following example:
26276
26277 @smallexample
26278 warning: "x.ads" has dynamic elaboration checks and with's
26279 warning:   "y.ads" which has static elaboration checks
26280 @end smallexample
26281
26282 @noindent
26283 These warnings indicate that the rule has been violated, and that as a result
26284 elaboration checks may be missed in the resulting executable file.
26285 This warning may be suppressed using the @option{-ws} binder switch
26286 in the usual manner.
26287
26288 One useful application of this mixing rule is in the case of a subsystem
26289 which does not itself @code{with} units from the remainder of the
26290 application. In this case, the entire subsystem can be compiled with
26291 dynamic checks to resolve a circularity in the subsystem, while
26292 allowing the main application that uses this subsystem to be compiled
26293 using the more reliable default static model.
26294
26295 @node What to Do If the Default Elaboration Behavior Fails
26296 @section What to Do If the Default Elaboration Behavior Fails
26297
26298 @noindent
26299 If the binder cannot find an acceptable order, it outputs detailed
26300 diagnostics. For example:
26301 @smallexample
26302 @group
26303 @iftex
26304 @leftskip=0cm
26305 @end iftex
26306 error: elaboration circularity detected
26307 info:   "proc (body)" must be elaborated before "pack (body)"
26308 info:     reason: Elaborate_All probably needed in unit "pack (body)"
26309 info:     recompile "pack (body)" with -gnatwl
26310 info:                             for full details
26311 info:       "proc (body)"
26312 info:         is needed by its spec:
26313 info:       "proc (spec)"
26314 info:         which is withed by:
26315 info:       "pack (body)"
26316 info:  "pack (body)" must be elaborated before "proc (body)"
26317 info:     reason: pragma Elaborate in unit "proc (body)"
26318 @end group
26319
26320 @end smallexample
26321
26322 @noindent
26323 In this case we have a cycle that the binder cannot break. On the one
26324 hand, there is an explicit pragma Elaborate in @code{proc} for
26325 @code{pack}. This means that the body of @code{pack} must be elaborated
26326 before the body of @code{proc}. On the other hand, there is elaboration
26327 code in @code{pack} that calls a subprogram in @code{proc}. This means
26328 that for maximum safety, there should really be a pragma
26329 Elaborate_All in @code{pack} for @code{proc} which would require that
26330 the body of @code{proc} be elaborated before the body of
26331 @code{pack}. Clearly both requirements cannot be satisfied.
26332 Faced with a circularity of this kind, you have three different options.
26333
26334 @table @asis
26335 @item Fix the program
26336 The most desirable option from the point of view of long-term maintenance
26337 is to rearrange the program so that the elaboration problems are avoided.
26338 One useful technique is to place the elaboration code into separate
26339 child packages. Another is to move some of the initialization code to
26340 explicitly called subprograms, where the program controls the order
26341 of initialization explicitly. Although this is the most desirable option,
26342 it may be impractical and involve too much modification, especially in
26343 the case of complex legacy code.
26344
26345 @item Perform dynamic checks
26346 If the compilations are done using the
26347 @option{-gnatE}
26348 (dynamic elaboration check) switch, then GNAT behaves in a quite different
26349 manner. Dynamic checks are generated for all calls that could possibly result
26350 in raising an exception. With this switch, the compiler does not generate
26351 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
26352 exactly as specified in the @cite{Ada Reference Manual}.
26353 The binder will generate
26354 an executable program that may or may not raise @code{Program_Error}, and then
26355 it is the programmer's job to ensure that it does not raise an exception. Note
26356 that it is important to compile all units with the switch, it cannot be used
26357 selectively.
26358
26359 @item Suppress checks
26360 The drawback of dynamic checks is that they generate a
26361 significant overhead at run time, both in space and time. If you
26362 are absolutely sure that your program cannot raise any elaboration
26363 exceptions, and you still want to use the dynamic elaboration model,
26364 then you can use the configuration pragma
26365 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
26366 example this pragma could be placed in the @file{gnat.adc} file.
26367
26368 @item Suppress checks selectively
26369 When you know that certain calls or instantiations in elaboration code cannot
26370 possibly lead to an elaboration error, and the binder nevertheless complains
26371 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
26372 elaboration circularities, it is possible to remove those warnings locally and
26373 obtain a program that will bind. Clearly this can be unsafe, and it is the
26374 responsibility of the programmer to make sure that the resulting program has no
26375 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
26376 used with different granularity to suppress warnings and break elaboration
26377 circularities:
26378
26379 @itemize @bullet
26380 @item
26381 Place the pragma that names the called subprogram in the declarative part
26382 that contains the call.
26383
26384 @item
26385 Place the pragma in the declarative part, without naming an entity. This
26386 disables warnings on all calls in the corresponding  declarative region.
26387
26388 @item
26389 Place the pragma in the package spec that declares the called subprogram,
26390 and name the subprogram. This disables warnings on all elaboration calls to
26391 that subprogram.
26392
26393 @item
26394 Place the pragma in the package spec that declares the called subprogram,
26395 without naming any entity. This disables warnings on all elaboration calls to
26396 all subprograms declared in this spec.
26397
26398 @item Use Pragma Elaborate
26399 As previously described in section @xref{Treatment of Pragma Elaborate},
26400 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
26401 that no elaboration checks are required on calls to the designated unit.
26402 There may be cases in which the caller knows that no transitive calls
26403 can occur, so that a @code{pragma Elaborate} will be sufficient in a
26404 case where @code{pragma Elaborate_All} would cause a circularity.
26405 @end itemize
26406
26407 @noindent
26408 These five cases are listed in order of decreasing safety, and therefore
26409 require increasing programmer care in their application. Consider the
26410 following program:
26411
26412 @smallexample @c adanocomment
26413 package Pack1 is
26414   function F1 return Integer;
26415   X1 : Integer;
26416 end Pack1;
26417
26418 package Pack2 is
26419   function F2 return Integer;
26420   function Pure (x : integer) return integer;
26421   --  pragma Suppress (Elaboration_Check, On => Pure);  -- (3)
26422   --  pragma Suppress (Elaboration_Check);              -- (4)
26423 end Pack2;
26424
26425 with Pack2;
26426 package body Pack1 is
26427   function F1 return Integer is
26428   begin
26429     return 100;
26430   end F1;
26431   Val : integer := Pack2.Pure (11);    --  Elab. call (1)
26432 begin
26433   declare
26434     --  pragma Suppress(Elaboration_Check, Pack2.F2);   -- (1)
26435     --  pragma Suppress(Elaboration_Check);             -- (2)
26436   begin
26437     X1 := Pack2.F2 + 1;                --  Elab. call (2)
26438   end;
26439 end Pack1;
26440
26441 with Pack1;
26442 package body Pack2 is
26443   function F2 return Integer is
26444   begin
26445      return Pack1.F1;
26446   end F2;
26447   function Pure (x : integer) return integer is
26448   begin
26449      return x ** 3 - 3 * x;
26450   end;
26451 end Pack2;
26452
26453 with Pack1, Ada.Text_IO;
26454 procedure Proc3 is
26455 begin
26456   Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
26457 end Proc3;
26458 @end smallexample
26459 In the absence of any pragmas, an attempt to bind this program produces
26460 the following diagnostics:
26461 @smallexample
26462 @group
26463 @iftex
26464 @leftskip=.5cm
26465 @end iftex
26466 error: elaboration circularity detected
26467 info:    "pack1 (body)" must be elaborated before "pack1 (body)"
26468 info:       reason: Elaborate_All probably needed in unit "pack1 (body)"
26469 info:       recompile "pack1 (body)" with -gnatwl for full details
26470 info:          "pack1 (body)"
26471 info:             must be elaborated along with its spec:
26472 info:          "pack1 (spec)"
26473 info:             which is withed by:
26474 info:          "pack2 (body)"
26475 info:             which must be elaborated along with its spec:
26476 info:          "pack2 (spec)"
26477 info:             which is withed by:
26478 info:          "pack1 (body)"
26479 @end group
26480 @end smallexample
26481 The sources of the circularity are the two calls to @code{Pack2.Pure} and
26482 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
26483 F2 is safe, even though F2 calls F1, because the call appears after the
26484 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
26485 remove the warning on the call. It is also possible to use pragma (2)
26486 because there are no other potentially unsafe calls in the block.
26487
26488 @noindent
26489 The call to @code{Pure} is safe because this function does not depend on the
26490 state of @code{Pack2}. Therefore any call to this function is safe, and it
26491 is correct to place pragma (3) in the corresponding package spec.
26492
26493 @noindent
26494 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
26495 warnings on all calls to functions declared therein. Note that this is not
26496 necessarily safe, and requires more detailed examination of the subprogram
26497 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
26498 be already elaborated.
26499 @end table
26500
26501 @noindent
26502 It is hard to generalize on which of these four approaches should be
26503 taken. Obviously if it is possible to fix the program so that the default
26504 treatment works, this is preferable, but this may not always be practical.
26505 It is certainly simple enough to use
26506 @option{-gnatE}
26507 but the danger in this case is that, even if the GNAT binder
26508 finds a correct elaboration order, it may not always do so,
26509 and certainly a binder from another Ada compiler might not. A
26510 combination of testing and analysis (for which the warnings generated
26511 with the
26512 @option{-gnatwl}
26513 switch can be useful) must be used to ensure that the program is free
26514 of errors. One switch that is useful in this testing is the
26515 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
26516 switch for
26517 @code{gnatbind}.
26518 Normally the binder tries to find an order that has the best chance
26519 of avoiding elaboration problems. However, if this switch is used, the binder
26520 plays a devil's advocate role, and tries to choose the order that
26521 has the best chance of failing. If your program works even with this
26522 switch, then it has a better chance of being error free, but this is still
26523 not a guarantee.
26524
26525 For an example of this approach in action, consider the C-tests (executable
26526 tests) from the ACVC suite. If these are compiled and run with the default
26527 treatment, then all but one of them succeed without generating any error
26528 diagnostics from the binder. However, there is one test that fails, and
26529 this is not surprising, because the whole point of this test is to ensure
26530 that the compiler can handle cases where it is impossible to determine
26531 a correct order statically, and it checks that an exception is indeed
26532 raised at run time.
26533
26534 This one test must be compiled and run using the
26535 @option{-gnatE}
26536 switch, and then it passes. Alternatively, the entire suite can
26537 be run using this switch. It is never wrong to run with the dynamic
26538 elaboration switch if your code is correct, and we assume that the
26539 C-tests are indeed correct (it is less efficient, but efficiency is
26540 not a factor in running the ACVC tests.)
26541
26542 @node Elaboration for Dispatching Calls
26543 @section Elaboration for Dispatching Calls
26544 @cindex Dispatching calls
26545
26546 @noindent
26547 In rare cases, the static elaboration model fails to prevent
26548 dispatching calls to not-yet-elaborated subprograms. In such cases, we
26549 fall back to run-time checks; premature calls to any primitive
26550 operation of a tagged type before the body of the operation has been
26551 elaborated will raise @code{Program_Error}.
26552
26553 Access-to-subprogram types, however, are handled conservatively, and
26554 do not require run-time checks. This was not true in earlier versions
26555 of the compiler; you can use the @option{-gnatd.U} debug switch to
26556 revert to the old behavior if the new conservative behavior causes
26557 elaboration cycles.
26558
26559 @node Summary of Procedures for Elaboration Control
26560 @section Summary of Procedures for Elaboration Control
26561 @cindex Elaboration control
26562
26563 @noindent
26564 First, compile your program with the default options, using none of
26565 the special elaboration control switches. If the binder successfully
26566 binds your program, then you can be confident that, apart from issues
26567 raised by the use of access-to-subprogram types and dynamic dispatching,
26568 the program is free of elaboration errors. If it is important that the
26569 program be portable, then use the
26570 @option{-gnatwl}
26571 switch to generate warnings about missing @code{Elaborate} or
26572 @code{Elaborate_All} pragmas, and supply the missing pragmas.
26573
26574 If the program fails to bind using the default static elaboration
26575 handling, then you can fix the program to eliminate the binder
26576 message, or recompile the entire program with the
26577 @option{-gnatE} switch to generate dynamic elaboration checks,
26578 and, if you are sure there really are no elaboration problems,
26579 use a global pragma @code{Suppress (Elaboration_Check)}.
26580
26581 @node Other Elaboration Order Considerations
26582 @section Other Elaboration Order Considerations
26583 @noindent
26584 This section has been entirely concerned with the issue of finding a valid
26585 elaboration order, as defined by the Ada Reference Manual. In a case
26586 where several elaboration orders are valid, the task is to find one
26587 of the possible valid elaboration orders (and the static model in GNAT
26588 will ensure that this is achieved).
26589
26590 The purpose of the elaboration rules in the Ada Reference Manual is to
26591 make sure that no entity is accessed before it has been elaborated. For
26592 a subprogram, this means that the spec and body must have been elaborated
26593 before the subprogram is called. For an object, this means that the object
26594 must have been elaborated before its value is read or written. A violation
26595 of either of these two requirements is an access before elaboration order,
26596 and this section has been all about avoiding such errors.
26597
26598 In the case where more than one order of elaboration is possible, in the
26599 sense that access before elaboration errors are avoided, then any one of
26600 the orders is ``correct'' in the sense that it meets the requirements of
26601 the Ada Reference Manual, and no such error occurs.
26602
26603 However, it may be the case for a given program, that there are
26604 constraints on the order of elaboration that come not from consideration
26605 of avoiding elaboration errors, but rather from extra-lingual logic
26606 requirements. Consider this example:
26607
26608 @smallexample @c ada
26609 with Init_Constants;
26610 package Constants is
26611    X : Integer := 0;
26612    Y : Integer := 0;
26613 end Constants;
26614
26615 package Init_Constants is
26616    procedure P; -- require a body
26617 end Init_Constants;
26618
26619 with Constants;
26620 package body Init_Constants is
26621    procedure P is begin null; end;
26622 begin
26623    Constants.X := 3;
26624    Constants.Y := 4;
26625 end Init_Constants;
26626
26627 with Constants;
26628 package Calc is
26629    Z : Integer := Constants.X + Constants.Y;
26630 end Calc;
26631
26632 with Calc;
26633 with Text_IO; use Text_IO;
26634 procedure Main is
26635 begin
26636    Put_Line (Calc.Z'Img);
26637 end Main;
26638 @end smallexample
26639
26640 @noindent
26641 In this example, there is more than one valid order of elaboration. For
26642 example both the following are correct orders:
26643
26644 @smallexample
26645 Init_Constants spec
26646 Constants spec
26647 Calc spec
26648 Init_Constants body
26649 Main body
26650
26651   and
26652
26653 Init_Constants spec
26654 Init_Constants body
26655 Constants spec
26656 Calc spec
26657 Main body
26658 @end smallexample
26659
26660 @noindent
26661 There is no language rule to prefer one or the other, both are correct
26662 from an order of elaboration point of view. But the programmatic effects
26663 of the two orders are very different. In the first, the elaboration routine
26664 of @code{Calc} initializes @code{Z} to zero, and then the main program
26665 runs with this value of zero. But in the second order, the elaboration
26666 routine of @code{Calc} runs after the body of Init_Constants has set
26667 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
26668 runs.
26669
26670 One could perhaps by applying pretty clever non-artificial intelligence
26671 to the situation guess that it is more likely that the second order of
26672 elaboration is the one desired, but there is no formal linguistic reason
26673 to prefer one over the other. In fact in this particular case, GNAT will
26674 prefer the second order, because of the rule that bodies are elaborated
26675 as soon as possible, but it's just luck that this is what was wanted
26676 (if indeed the second order was preferred).
26677
26678 If the program cares about the order of elaboration routines in a case like
26679 this, it is important to specify the order required. In this particular
26680 case, that could have been achieved by adding to the spec of Calc:
26681
26682 @smallexample @c ada
26683 pragma Elaborate_All (Constants);
26684 @end smallexample
26685
26686 @noindent
26687 which requires that the body (if any) and spec of @code{Constants},
26688 as well as the body and spec of any unit @code{with}'ed by
26689 @code{Constants} be elaborated before @code{Calc} is elaborated.
26690
26691 Clearly no automatic method can always guess which alternative you require,
26692 and if you are working with legacy code that had constraints of this kind
26693 which were not properly specified by adding @code{Elaborate} or
26694 @code{Elaborate_All} pragmas, then indeed it is possible that two different
26695 compilers can choose different orders.
26696
26697 However, GNAT does attempt to diagnose the common situation where there
26698 are uninitialized variables in the visible part of a package spec, and the
26699 corresponding package body has an elaboration block that directly or
26700 indirectly initialized one or more of these variables. This is the situation
26701 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
26702 a warning that suggests this addition if it detects this situation.
26703
26704 The @code{gnatbind}
26705 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
26706 out problems. This switch causes bodies to be elaborated as late as possible
26707 instead of as early as possible. In the example above, it would have forced
26708 the choice of the first elaboration order. If you get different results
26709 when using this switch, and particularly if one set of results is right,
26710 and one is wrong as far as you are concerned, it shows that you have some
26711 missing @code{Elaborate} pragmas. For the example above, we have the
26712 following output:
26713
26714 @smallexample
26715 gnatmake -f -q main
26716 main
26717  7
26718 gnatmake -f -q main -bargs -p
26719 main
26720  0
26721 @end smallexample
26722
26723 @noindent
26724 It is of course quite unlikely that both these results are correct, so
26725 it is up to you in a case like this to investigate the source of the
26726 difference, by looking at the two elaboration orders that are chosen,
26727 and figuring out which is correct, and then adding the necessary
26728 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
26729
26730
26731 @c **********************************
26732 @node Overflow Check Handling in GNAT
26733 @appendix Overflow Check Handling in GNAT
26734 @cindex Overflow checks
26735 @cindex Checks (overflow)
26736 @c **********************************
26737
26738 @menu
26739 * Background::
26740 * Overflow Checking Modes in GNAT::
26741 * Specifying the Desired Mode::
26742 * Default Settings::
26743 * Implementation Notes::
26744 @end menu
26745
26746
26747 @node Background
26748 @section Background
26749
26750 @noindent
26751 Overflow checks are checks that the compiler may make to ensure
26752 that intermediate results are not out of range. For example:
26753
26754 @smallexample @c ada
26755    A : Integer;
26756    ...
26757    A := A + 1;
26758 @end smallexample
26759
26760 @noindent
26761 if @code{A} has the value @code{Integer'Last}, then the addition may cause
26762 overflow since the result is out of range of the type @code{Integer}.
26763 In this case @code{Constraint_Error} will be raised if checks are
26764 enabled.
26765
26766 A trickier situation arises in examples like the following:
26767
26768 @smallexample @c ada
26769   A, C : Integer;
26770   ...
26771   A := (A + 1) + C;
26772 @end smallexample
26773
26774 @noindent
26775 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
26776 Now the final result of the expression on the right hand side is
26777 @code{Integer'Last} which is in range, but the question arises whether the
26778 intermediate addition of @code{(A + 1)} raises an overflow error.
26779
26780 The (perhaps surprising) answer is that the Ada language
26781 definition does not answer this question. Instead it leaves
26782 it up to the implementation to do one of two things if overflow
26783 checks are enabled.
26784
26785 @itemize @bullet
26786 @item
26787 raise an exception (@code{Constraint_Error}), or
26788
26789 @item
26790 yield the correct mathematical result which is then used in
26791 subsequent operations.
26792 @end itemize
26793
26794 @noindent
26795 If the compiler chooses the first approach, then the assignment of this
26796 example will indeed raise @code{Constraint_Error} if overflow checking is
26797 enabled, or result in erroneous execution if overflow checks are suppressed.
26798
26799 But if the compiler
26800 chooses the second approach, then it can perform both additions yielding
26801 the correct mathematical result, which is in range, so no exception
26802 will be raised, and the right result is obtained, regardless of whether
26803 overflow checks are suppressed.
26804
26805 Note that in the first example an
26806 exception will be raised in either case, since if the compiler
26807 gives the correct mathematical result for the addition, it will
26808 be out of range of the target type of the assignment, and thus
26809 fails the range check.
26810
26811 This lack of specified behavior in the handling of overflow for
26812 intermediate results is a source of non-portability, and can thus
26813 be problematic when programs are ported. Most typically this arises
26814 in a situation where the original compiler did not raise an exception,
26815 and then the application is moved to a compiler where the check is
26816 performed on the intermediate result and an unexpected exception is
26817 raised.
26818
26819 Furthermore, when using Ada 2012's preconditions and other
26820 assertion forms, another issue arises. Consider:
26821
26822 @smallexample @c ada
26823      procedure P (A, B : Integer) with
26824        Pre => A + B <= Integer'Last;
26825 @end smallexample
26826
26827 @noindent
26828 One often wants to regard arithmetic in a context like this from
26829 a mathematical point of view. So for example, if the two actual parameters
26830 for a call to @code{P} are both @code{Integer'Last}, then
26831 the precondition should be regarded as False. If we are executing
26832 in a mode with run-time checks enabled for preconditions, then we would
26833 like this precondition to fail, rather than raising an exception
26834 because of the intermediate overflow.
26835
26836 However, the language definition leaves the specification of
26837 whether the above condition fails (raising @code{Assert_Error}) or
26838 causes an intermediate overflow (raising @code{Constraint_Error})
26839 up to the implementation.
26840
26841 The situation is worse in a case such as the following:
26842
26843 @smallexample @c ada
26844      procedure Q (A, B, C : Integer) with
26845        Pre => A + B + C <= Integer'Last;
26846 @end smallexample
26847
26848 @noindent
26849 Consider the call
26850
26851 @smallexample @c ada
26852      Q (A => Integer'Last, B => 1, C => -1);
26853 @end smallexample
26854
26855 @noindent
26856 From a mathematical point of view the precondition
26857 is True, but at run time we may (but are not guaranteed to) get an
26858 exception raised because of the intermediate overflow (and we really
26859 would prefer this precondition to be considered True at run time).
26860
26861 @node Overflow Checking Modes in GNAT
26862 @section Overflow Checking Modes in GNAT
26863
26864 @noindent
26865 To deal with the portability issue, and with the problem of
26866 mathematical versus run-time interpretation of the expressions in
26867 assertions, GNAT provides comprehensive control over the handling
26868 of intermediate overflow. GNAT can operate in three modes, and
26869 furthemore, permits separate selection of operating modes for
26870 the expressions within assertions (here the term ``assertions''
26871 is used in the technical sense, which includes preconditions and so forth)
26872 and for expressions appearing outside assertions.
26873
26874 The three modes are:
26875
26876 @itemize @bullet
26877 @item   @i{Use base type for intermediate operations} (@code{STRICT})
26878
26879      In this mode, all intermediate results for predefined arithmetic
26880      operators are computed using the base type, and the result must
26881      be in range of the base type. If this is not the
26882      case then either an exception is raised (if overflow checks are
26883      enabled) or the execution is erroneous (if overflow checks are suppressed).
26884      This is the normal default mode.
26885
26886 @item   @i{Most intermediate overflows avoided} (@code{MINIMIZED})
26887
26888      In this mode, the compiler attempts to avoid intermediate overflows by
26889      using a larger integer type, typically @code{Long_Long_Integer},
26890      as the type in which arithmetic is
26891      performed for predefined arithmetic operators. This may be slightly more
26892      expensive at
26893      run time (compared to suppressing intermediate overflow checks), though
26894      the cost is negligible on modern 64-bit machines. For the examples given
26895      earlier, no intermediate overflows would have resulted in exceptions,
26896      since the intermediate results are all in the range of
26897      @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
26898      of GNAT). In addition, if checks are enabled, this reduces the number of
26899      checks that must be made, so this choice may actually result in an
26900      improvement in space and time behavior.
26901
26902      However, there are cases where @code{Long_Long_Integer} is not large
26903      enough, consider the following example:
26904
26905 @smallexample @c ada
26906        procedure R (A, B, C, D : Integer) with
26907          Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
26908 @end smallexample
26909
26910      where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
26911      Now the intermediate results are
26912      out of the range of @code{Long_Long_Integer} even though the final result
26913      is in range and the precondition is True (from a mathematical point
26914      of view). In such a case, operating in this mode, an overflow occurs
26915      for the intermediate computation (which is why this mode
26916      says @i{most} intermediate overflows are avoided). In this case,
26917      an exception is raised if overflow checks are enabled, and the
26918      execution is erroneous if overflow checks are suppressed.
26919
26920 @item   @i{All intermediate overflows avoided} (@code{ELIMINATED})
26921
26922      In this mode, the compiler  avoids all intermediate overflows
26923      by using arbitrary precision arithmetic as required. In this
26924      mode, the above example with @code{A**2 * B**2} would
26925      not cause intermediate overflow, because the intermediate result
26926      would be evaluated using sufficient precision, and the result
26927      of evaluating the precondition would be True.
26928
26929      This mode has the advantage of avoiding any intermediate
26930      overflows, but at the expense of significant run-time overhead,
26931      including the use of a library (included automatically in this
26932      mode) for multiple-precision arithmetic.
26933
26934      This mode provides cleaner semantics for assertions, since now
26935      the run-time behavior emulates true arithmetic behavior for the
26936      predefined arithmetic operators, meaning that there is never a
26937      conflict between the mathematical view of the assertion, and its
26938      run-time behavior.
26939
26940      Note that in this mode, the behavior is unaffected by whether or
26941      not overflow checks are suppressed, since overflow does not occur.
26942      It is possible for gigantic intermediate expressions to raise
26943      @code{Storage_Error} as a result of attempting to compute the
26944      results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
26945      but overflow is impossible.
26946
26947
26948 @end itemize
26949
26950 @noindent
26951   Note that these modes apply only to the evaluation of predefined
26952   arithmetic, membership, and comparison operators for signed integer
26953   aritmetic.
26954
26955   For fixed-point arithmetic, checks can be suppressed. But if checks
26956   are enabled
26957   then fixed-point values are always checked for overflow against the
26958   base type for intermediate expressions (that is such checks always
26959   operate in the equivalent of @code{STRICT} mode).
26960
26961   For floating-point, on nearly all architectures, @code{Machine_Overflows}
26962   is False, and IEEE infinities are generated, so overflow exceptions
26963   are never raised. If you want to avoid infinities, and check that
26964   final results of expressions are in range, then you can declare a
26965   constrained floating-point type, and range checks will be carried
26966   out in the normal manner (with infinite values always failing all
26967   range checks).
26968
26969
26970 @c -------------------------
26971 @node Specifying the Desired Mode
26972 @section Specifying the Desired Mode
26973
26974 @noindent
26975 The desired mode of for handling intermediate overflow can be specified using
26976 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
26977 The pragma has the form
26978 @cindex pragma @code{Overflow_Mode}
26979
26980 @smallexample @c ada
26981     pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
26982 @end smallexample
26983
26984 @noindent
26985 where @code{MODE} is one of
26986
26987 @itemize @bullet
26988 @item   @code{STRICT}:  intermediate overflows checked (using base type)
26989 @item   @code{MINIMIZED}: minimize intermediate overflows
26990 @item   @code{ELIMINATED}: eliminate intermediate overflows
26991 @end itemize
26992
26993 @noindent
26994 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
26995 @code{minimized} all have the same effect.
26996
26997 If only the @code{General} parameter is present, then the given @code{MODE}
26998 applies
26999 to expressions both within and outside assertions. If both arguments
27000 are present, then @code{General} applies to expressions outside assertions,
27001 and @code{Assertions} applies to expressions within assertions. For example:
27002
27003 @smallexample @c ada
27004    pragma Overflow_Mode
27005      (General => Minimized, Assertions => Eliminated);
27006 @end smallexample
27007
27008 @noindent
27009 specifies that general expressions outside assertions be evaluated
27010 in ``minimize intermediate overflows'' mode, and expressions within
27011 assertions be evaluated in ``eliminate intermediate overflows'' mode.
27012 This is often a reasonable choice, avoiding excessive overhead
27013 outside assertions, but assuring a high degree of portability
27014 when importing code from another compiler, while incurring
27015 the extra overhead for assertion expressions to ensure that
27016 the behavior at run time matches the expected mathematical
27017 behavior.
27018
27019 The @code{Overflow_Mode} pragma has the same scoping and placement
27020 rules as pragma @code{Suppress}, so it can occur either as a
27021 configuration pragma, specifying a default for the whole
27022 program, or in a declarative scope, where it applies to the
27023 remaining declarations and statements in that scope.
27024
27025 Note that pragma @code{Overflow_Mode} does not affect whether
27026 overflow checks are enabled or suppressed. It only controls the
27027 method used to compute intermediate values. To control whether
27028 overflow checking is enabled or suppressed, use pragma @code{Suppress}
27029 or @code{Unsuppress} in the usual manner
27030
27031 Additionally, a compiler switch @option{-gnato?} or @option{-gnato??}
27032 can be used to control the checking mode default (which can be subsequently
27033 overridden using pragmas).
27034 @cindex @option{-gnato?} (gcc)
27035 @cindex @option{-gnato??} (gcc)
27036
27037 Here `@code{?}' is one of the digits `@code{1}' through `@code{3}':
27038
27039 @itemize @bullet
27040 @item   @code{1}:
27041 use base type for intermediate operations (@code{STRICT})
27042 @item   @code{2}:
27043 minimize intermediate overflows (@code{MINIMIZED})
27044 @item   @code{3}:
27045 eliminate intermediate overflows (@code{ELIMINATED})
27046 @end itemize
27047
27048 @noindent
27049 As with the pragma, if only one digit appears then it applies to all
27050 cases; if two digits are given, then the first applies outside
27051 assertions, and the second within assertions. Thus the equivalent
27052 of the example pragma above would be
27053 @option{^-gnato23^/OVERFLOW_CHECKS=23^}.
27054
27055 If no digits follow the @option{-gnato}, then it is equivalent to
27056 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
27057 causing all intermediate operations to be computed using the base
27058 type (@code{STRICT} mode).
27059
27060 In addition to setting the mode used for computation of intermediate
27061 results, the @code{-gnato} switch also enables overflow checking (which
27062 is suppressed by default). It thus combines the effect of using
27063 a pragma @code{Overflow_Mode} and pragma @code{Unsuppress}.
27064
27065
27066 @c -------------------------
27067 @node Default Settings
27068 @section Default Settings
27069
27070 The default mode for overflow checks is
27071
27072 @smallexample
27073    General => Strict
27074 @end smallexample
27075
27076 @noindent
27077 which causes all computations both inside and outside assertions to use
27078 the base type. In addition overflow checks are suppressed.
27079
27080 This retains compatibility with previous versions of
27081 GNAT which suppressed overflow checks by default and always
27082 used the base type for computation of intermediate results.
27083
27084 The switch @option{-gnato} (with no digits following) is equivalent to
27085 @cindex @option{-gnato} (gcc)
27086
27087 @smallexample
27088    General => Strict
27089 @end smallexample
27090
27091 @noindent
27092 which causes overflow checking of all intermediate overflows
27093 both inside and outside assertions against the base type.
27094 This provides compatibility
27095 with this switch as implemented in previous versions of GNAT.
27096
27097 The pragma @code{Suppress (Overflow_Check)} disables overflow
27098 checking, but it has no effect on the method used for computing
27099 intermediate results.
27100
27101 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
27102 checking, but it has no effect on the method used for computing
27103 intermediate results.
27104
27105 @c -------------------------
27106 @node Implementation Notes
27107 @section Implementation Notes
27108
27109 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
27110 reasonably efficient, and can be generally used. It also helps
27111 to ensure compatibility with code imported from some other
27112 compiler to GNAT.
27113
27114 Setting all intermediate overflows checking (@code{CHECKED} mode)
27115 makes sense if you want to
27116 make sure that your code is compatible with any other possible
27117 Ada implementation. This may be useful in ensuring portability
27118 for code that is to be exported to some other compiler than GNAT.
27119
27120
27121 The Ada standard allows the reassociation of expressions at
27122 the same precedence level if no parentheses are present. For
27123 example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but
27124 the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly
27125 introducing or eliminating an overflow exception. The GNAT
27126 compiler never takes advantage of this freedom, and the
27127 expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}.
27128 If you need the other order, you can write the parentheses
27129 explicitly @w{@code{A+(B+C)}} and GNAT will respect this order.
27130
27131 The use of @code{ELIMINATED} mode will cause the compiler to
27132 automatically include an appropriate arbitrary precision
27133 integer arithmetic package. The compiler will make calls
27134 to this package, though only in cases where it cannot be
27135 sure that @code{Long_Long_Integer} is sufficient to guard against
27136 intermediate overflows. This package does not use dynamic
27137 alllocation, but it does use the secondary stack, so an
27138 appropriate secondary stack package must be present (this
27139 is always true for standard full Ada, but may require
27140 specific steps for restricted run times such as ZFP).
27141
27142 Although @code{ELIMINATED} mode causes expressions to use arbitrary
27143 precision arithmetic, avoiding overflow, the final result
27144 must be in an appropriate range. This is true even if the
27145 final result is of type @code{[Long_[Long_]]Integer'Base}, which
27146 still has the same bounds as its associated constrained
27147 type at run-time.
27148
27149 Currently, the @code{ELIMINATED} mode is only available on target
27150 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
27151 platforms).
27152
27153 @c *******************************
27154 @node Conditional Compilation
27155 @appendix Conditional Compilation
27156 @c *******************************
27157 @cindex Conditional compilation
27158
27159 @noindent
27160 It is often necessary to arrange for a single source program
27161 to serve multiple purposes, where it is compiled in different
27162 ways to achieve these different goals. Some examples of the
27163 need for this feature are
27164
27165 @itemize @bullet
27166 @item  Adapting a program to a different hardware environment
27167 @item  Adapting a program to a different target architecture
27168 @item  Turning debugging features on and off
27169 @item  Arranging for a program to compile with different compilers
27170 @end itemize
27171
27172 @noindent
27173 In C, or C++, the typical approach would be to use the preprocessor
27174 that is defined as part of the language. The Ada language does not
27175 contain such a feature. This is not an oversight, but rather a very
27176 deliberate design decision, based on the experience that overuse of
27177 the preprocessing features in C and C++ can result in programs that
27178 are extremely difficult to maintain. For example, if we have ten
27179 switches that can be on or off, this means that there are a thousand
27180 separate programs, any one of which might not even be syntactically
27181 correct, and even if syntactically correct, the resulting program
27182 might not work correctly. Testing all combinations can quickly become
27183 impossible.
27184
27185 Nevertheless, the need to tailor programs certainly exists, and in
27186 this Appendix we will discuss how this can
27187 be achieved using Ada in general, and GNAT in particular.
27188
27189 @menu
27190 * Use of Boolean Constants::
27191 * Debugging - A Special Case::
27192 * Conditionalizing Declarations::
27193 * Use of Alternative Implementations::
27194 * Preprocessing::
27195 @end menu
27196
27197 @node Use of Boolean Constants
27198 @section Use of Boolean Constants
27199
27200 @noindent
27201 In the case where the difference is simply which code
27202 sequence is executed, the cleanest solution is to use Boolean
27203 constants to control which code is executed.
27204
27205 @smallexample @c ada
27206 @group
27207 FP_Initialize_Required : constant Boolean := True;
27208 @dots{}
27209 if FP_Initialize_Required then
27210 @dots{}
27211 end if;
27212 @end group
27213 @end smallexample
27214
27215 @noindent
27216 Not only will the code inside the @code{if} statement not be executed if
27217 the constant Boolean is @code{False}, but it will also be completely
27218 deleted from the program.
27219 However, the code is only deleted after the @code{if} statement
27220 has been checked for syntactic and semantic correctness.
27221 (In contrast, with preprocessors the code is deleted before the
27222 compiler ever gets to see it, so it is not checked until the switch
27223 is turned on.)
27224 @cindex Preprocessors (contrasted with conditional compilation)
27225
27226 Typically the Boolean constants will be in a separate package,
27227 something like:
27228
27229 @smallexample @c ada
27230 @group
27231 package Config is
27232    FP_Initialize_Required : constant Boolean := True;
27233    Reset_Available        : constant Boolean := False;
27234    @dots{}
27235 end Config;
27236 @end group
27237 @end smallexample
27238
27239 @noindent
27240 The @code{Config} package exists in multiple forms for the various targets,
27241 with an appropriate script selecting the version of @code{Config} needed.
27242 Then any other unit requiring conditional compilation can do a @code{with}
27243 of @code{Config} to make the constants visible.
27244
27245
27246 @node Debugging - A Special Case
27247 @section Debugging - A Special Case
27248
27249 @noindent
27250 A common use of conditional code is to execute statements (for example
27251 dynamic checks, or output of intermediate results) under control of a
27252 debug switch, so that the debugging behavior can be turned on and off.
27253 This can be done using a Boolean constant to control whether the code
27254 is active:
27255
27256 @smallexample @c ada
27257 @group
27258 if Debugging then
27259    Put_Line ("got to the first stage!");
27260 end if;
27261 @end group
27262 @end smallexample
27263
27264 @noindent
27265 or
27266
27267 @smallexample @c ada
27268 @group
27269 if Debugging and then Temperature > 999.0 then
27270    raise Temperature_Crazy;
27271 end if;
27272 @end group
27273 @end smallexample
27274
27275 @noindent
27276 Since this is a common case, there are special features to deal with
27277 this in a convenient manner. For the case of tests, Ada 2005 has added
27278 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
27279 @cindex pragma @code{Assert}
27280 on the @code{Assert} pragma that has always been available in GNAT, so this
27281 feature may be used with GNAT even if you are not using Ada 2005 features.
27282 The use of pragma @code{Assert} is described in
27283 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
27284 example, the last test could be written:
27285
27286 @smallexample @c ada
27287 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
27288 @end smallexample
27289
27290 @noindent
27291 or simply
27292
27293 @smallexample @c ada
27294 pragma Assert (Temperature <= 999.0);
27295 @end smallexample
27296
27297 @noindent
27298 In both cases, if assertions are active and the temperature is excessive,
27299 the exception @code{Assert_Failure} will be raised, with the given string in
27300 the first case or a string indicating the location of the pragma in the second
27301 case used as the exception message.
27302
27303 You can turn assertions on and off by using the @code{Assertion_Policy}
27304 pragma.
27305 @cindex pragma @code{Assertion_Policy}
27306 This is an Ada 2005 pragma which is implemented in all modes by
27307 GNAT, but only in the latest versions of GNAT which include Ada 2005
27308 capability. Alternatively, you can use the @option{-gnata} switch
27309 @cindex @option{-gnata} switch
27310 to enable assertions from the command line (this is recognized by all versions
27311 of GNAT).
27312
27313 For the example above with the @code{Put_Line}, the GNAT-specific pragma
27314 @code{Debug} can be used:
27315 @cindex pragma @code{Debug}
27316
27317 @smallexample @c ada
27318 pragma Debug (Put_Line ("got to the first stage!"));
27319 @end smallexample
27320
27321 @noindent
27322 If debug pragmas are enabled, the argument, which must be of the form of
27323 a procedure call, is executed (in this case, @code{Put_Line} will be called).
27324 Only one call can be present, but of course a special debugging procedure
27325 containing any code you like can be included in the program and then
27326 called in a pragma @code{Debug} argument as needed.
27327
27328 One advantage of pragma @code{Debug} over the @code{if Debugging then}
27329 construct is that pragma @code{Debug} can appear in declarative contexts,
27330 such as at the very beginning of a procedure, before local declarations have
27331 been elaborated.
27332
27333 Debug pragmas are enabled using either the @option{-gnata} switch that also
27334 controls assertions, or with a separate Debug_Policy pragma.
27335 @cindex pragma @code{Debug_Policy}
27336 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
27337 in Ada 95 and Ada 83 programs as well), and is analogous to
27338 pragma @code{Assertion_Policy} to control assertions.
27339
27340 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
27341 and thus they can appear in @file{gnat.adc} if you are not using a
27342 project file, or in the file designated to contain configuration pragmas
27343 in a project file.
27344 They then apply to all subsequent compilations. In practice the use of
27345 the @option{-gnata} switch is often the most convenient method of controlling
27346 the status of these pragmas.
27347
27348 Note that a pragma is not a statement, so in contexts where a statement
27349 sequence is required, you can't just write a pragma on its own. You have
27350 to add a @code{null} statement.
27351
27352 @smallexample @c ada
27353 @group
27354 if @dots{} then
27355    @dots{} -- some statements
27356 else
27357    pragma Assert (Num_Cases < 10);
27358    null;
27359 end if;
27360 @end group
27361 @end smallexample
27362
27363
27364 @node Conditionalizing Declarations
27365 @section Conditionalizing Declarations
27366
27367 @noindent
27368 In some cases, it may be necessary to conditionalize declarations to meet
27369 different requirements. For example we might want a bit string whose length
27370 is set to meet some hardware message requirement.
27371
27372 In some cases, it may be possible to do this using declare blocks controlled
27373 by conditional constants:
27374
27375 @smallexample @c ada
27376 @group
27377 if Small_Machine then
27378    declare
27379       X : Bit_String (1 .. 10);
27380    begin
27381       @dots{}
27382    end;
27383 else
27384    declare
27385       X : Large_Bit_String (1 .. 1000);
27386    begin
27387       @dots{}
27388    end;
27389 end if;
27390 @end group
27391 @end smallexample
27392
27393 @noindent
27394 Note that in this approach, both declarations are analyzed by the
27395 compiler so this can only be used where both declarations are legal,
27396 even though one of them will not be used.
27397
27398 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
27399 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
27400 that are parameterized by these constants. For example
27401
27402 @smallexample @c ada
27403 @group
27404 for Rec use
27405   Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
27406 end record;
27407 @end group
27408 @end smallexample
27409
27410 @noindent
27411 If @code{Bits_Per_Word} is set to 32, this generates either
27412
27413 @smallexample @c ada
27414 @group
27415 for Rec use
27416   Field1 at 0 range 0 .. 32;
27417 end record;
27418 @end group
27419 @end smallexample
27420
27421 @noindent
27422 for the big endian case, or
27423
27424 @smallexample @c ada
27425 @group
27426 for Rec use record
27427   Field1 at 0 range 10 .. 32;
27428 end record;
27429 @end group
27430 @end smallexample
27431
27432 @noindent
27433 for the little endian case. Since a powerful subset of Ada expression
27434 notation is usable for creating static constants, clever use of this
27435 feature can often solve quite difficult problems in conditionalizing
27436 compilation (note incidentally that in Ada 95, the little endian
27437 constant was introduced as @code{System.Default_Bit_Order}, so you do not
27438 need to define this one yourself).
27439
27440
27441 @node Use of Alternative Implementations
27442 @section Use of Alternative Implementations
27443
27444 @noindent
27445 In some cases, none of the approaches described above are adequate. This
27446 can occur for example if the set of declarations required is radically
27447 different for two different configurations.
27448
27449 In this situation, the official Ada way of dealing with conditionalizing
27450 such code is to write separate units for the different cases. As long as
27451 this does not result in excessive duplication of code, this can be done
27452 without creating maintenance problems. The approach is to share common
27453 code as far as possible, and then isolate the code and declarations
27454 that are different. Subunits are often a convenient method for breaking
27455 out a piece of a unit that is to be conditionalized, with separate files
27456 for different versions of the subunit for different targets, where the
27457 build script selects the right one to give to the compiler.
27458 @cindex Subunits (and conditional compilation)
27459
27460 As an example, consider a situation where a new feature in Ada 2005
27461 allows something to be done in a really nice way. But your code must be able
27462 to compile with an Ada 95 compiler. Conceptually you want to say:
27463
27464 @smallexample @c ada
27465 @group
27466 if Ada_2005 then
27467    @dots{} neat Ada 2005 code
27468 else
27469    @dots{} not quite as neat Ada 95 code
27470 end if;
27471 @end group
27472 @end smallexample
27473
27474 @noindent
27475 where @code{Ada_2005} is a Boolean constant.
27476
27477 But this won't work when @code{Ada_2005} is set to @code{False},
27478 since the @code{then} clause will be illegal for an Ada 95 compiler.
27479 (Recall that although such unreachable code would eventually be deleted
27480 by the compiler, it still needs to be legal.  If it uses features
27481 introduced in Ada 2005, it will be illegal in Ada 95.)
27482
27483 So instead we write
27484
27485 @smallexample @c ada
27486 procedure Insert is separate;
27487 @end smallexample
27488
27489 @noindent
27490 Then we have two files for the subunit @code{Insert}, with the two sets of
27491 code.
27492 If the package containing this is called @code{File_Queries}, then we might
27493 have two files
27494
27495 @itemize @bullet
27496 @item    @file{file_queries-insert-2005.adb}
27497 @item    @file{file_queries-insert-95.adb}
27498 @end itemize
27499
27500 @noindent
27501 and the build script renames the appropriate file to
27502
27503 @smallexample
27504 file_queries-insert.adb
27505 @end smallexample
27506
27507 @noindent
27508 and then carries out the compilation.
27509
27510 This can also be done with project files' naming schemes. For example:
27511
27512 @smallexample @c project
27513 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
27514 @end smallexample
27515
27516 @noindent
27517 Note also that with project files it is desirable to use a different extension
27518 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
27519 conflict may arise through another commonly used feature: to declare as part
27520 of the project a set of directories containing all the sources obeying the
27521 default naming scheme.
27522
27523 The use of alternative units is certainly feasible in all situations,
27524 and for example the Ada part of the GNAT run-time is conditionalized
27525 based on the target architecture using this approach. As a specific example,
27526 consider the implementation of the AST feature in VMS. There is one
27527 spec:
27528
27529 @smallexample
27530 s-asthan.ads
27531 @end smallexample
27532
27533 @noindent
27534 which is the same for all architectures, and three bodies:
27535
27536 @table @file
27537 @item    s-asthan.adb
27538 used for all non-VMS operating systems
27539 @item    s-asthan-vms-alpha.adb
27540 used for VMS on the Alpha
27541 @item    s-asthan-vms-ia64.adb
27542 used for VMS on the ia64
27543 @end table
27544
27545 @noindent
27546 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
27547 this operating system feature is not available, and the two remaining
27548 versions interface with the corresponding versions of VMS to provide
27549 VMS-compatible AST handling. The GNAT build script knows the architecture
27550 and operating system, and automatically selects the right version,
27551 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
27552
27553 Another style for arranging alternative implementations is through Ada's
27554 access-to-subprogram facility.
27555 In case some functionality is to be conditionally included,
27556 you can declare an access-to-procedure variable @code{Ref} that is initialized
27557 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
27558 when appropriate.
27559 In some library package, set @code{Ref} to @code{Proc'Access} for some
27560 procedure @code{Proc} that performs the relevant processing.
27561 The initialization only occurs if the library package is included in the
27562 program.
27563 The same idea can also be implemented using tagged types and dispatching
27564 calls.
27565
27566
27567 @node Preprocessing
27568 @section Preprocessing
27569 @cindex Preprocessing
27570
27571 @noindent
27572 Although it is quite possible to conditionalize code without the use of
27573 C-style preprocessing, as described earlier in this section, it is
27574 nevertheless convenient in some cases to use the C approach. Moreover,
27575 older Ada compilers have often provided some preprocessing capability,
27576 so legacy code may depend on this approach, even though it is not
27577 standard.
27578
27579 To accommodate such use, GNAT provides a preprocessor (modeled to a large
27580 extent on the various preprocessors that have been used
27581 with legacy code on other compilers, to enable easier transition).
27582
27583 The preprocessor may be used in two separate modes. It can be used quite
27584 separately from the compiler, to generate a separate output source file
27585 that is then fed to the compiler as a separate step. This is the
27586 @code{gnatprep} utility, whose use is fully described in
27587 @ref{Preprocessing with gnatprep}.
27588 @cindex @code{gnatprep}
27589
27590 The preprocessing language allows such constructs as
27591
27592 @smallexample
27593 @group
27594 #if DEBUG or else (PRIORITY > 4) then
27595    bunch of declarations
27596 #else
27597    completely different bunch of declarations
27598 #end if;
27599 @end group
27600 @end smallexample
27601
27602 @noindent
27603 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
27604 defined either on the command line or in a separate file.
27605
27606 The other way of running the preprocessor is even closer to the C style and
27607 often more convenient. In this approach the preprocessing is integrated into
27608 the compilation process. The compiler is fed the preprocessor input which
27609 includes @code{#if} lines etc, and then the compiler carries out the
27610 preprocessing internally and processes the resulting output.
27611 For more details on this approach, see @ref{Integrated Preprocessing}.
27612
27613
27614 @c *******************************
27615 @node Inline Assembler
27616 @appendix Inline Assembler
27617 @c *******************************
27618
27619 @noindent
27620 If you need to write low-level software that interacts directly
27621 with the hardware, Ada provides two ways to incorporate assembly
27622 language code into your program.  First, you can import and invoke
27623 external routines written in assembly language, an Ada feature fully
27624 supported by GNAT@.  However, for small sections of code it may be simpler
27625 or more efficient to include assembly language statements directly
27626 in your Ada source program, using the facilities of the implementation-defined
27627 package @code{System.Machine_Code}, which incorporates the gcc
27628 Inline Assembler.  The Inline Assembler approach offers a number of advantages,
27629 including the following:
27630
27631 @itemize @bullet
27632 @item No need to use non-Ada tools
27633 @item Consistent interface over different targets
27634 @item Automatic usage of the proper calling conventions
27635 @item Access to Ada constants and variables
27636 @item Definition of intrinsic routines
27637 @item Possibility of inlining a subprogram comprising assembler code
27638 @item Code optimizer can take Inline Assembler code into account
27639 @end itemize
27640
27641 This chapter presents a series of examples to show you how to use
27642 the Inline Assembler.  Although it focuses on the Intel x86,
27643 the general approach applies also to other processors.
27644 It is assumed that you are familiar with Ada
27645 and with assembly language programming.
27646
27647 @menu
27648 * Basic Assembler Syntax::
27649 * A Simple Example of Inline Assembler::
27650 * Output Variables in Inline Assembler::
27651 * Input Variables in Inline Assembler::
27652 * Inlining Inline Assembler Code::
27653 * Other Asm Functionality::
27654 @end menu
27655
27656 @c ---------------------------------------------------------------------------
27657 @node Basic Assembler Syntax
27658 @section Basic Assembler Syntax
27659
27660 @noindent
27661 The assembler used by GNAT and gcc is based not on the Intel assembly
27662 language, but rather on a language that descends from the AT&T Unix
27663 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
27664 The following table summarizes the main features of @emph{as} syntax
27665 and points out the differences from the Intel conventions.
27666 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
27667 pre-processor) documentation for further information.
27668
27669 @table @asis
27670 @item Register names
27671 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
27672 @*
27673 Intel: No extra punctuation; for example @code{eax}
27674
27675 @item Immediate operand
27676 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
27677 @*
27678 Intel: No extra punctuation; for example @code{4}
27679
27680 @item Address
27681 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
27682 @*
27683 Intel: No extra punctuation; for example @code{loc}
27684
27685 @item Memory contents
27686 gcc / @emph{as}: No extra punctuation; for example @code{loc}
27687 @*
27688 Intel: Square brackets; for example @code{[loc]}
27689
27690 @item Register contents
27691 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
27692 @*
27693 Intel: Square brackets; for example @code{[eax]}
27694
27695 @item Hexadecimal numbers
27696 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
27697 @*
27698 Intel: Trailing ``h''; for example @code{A0h}
27699
27700 @item Operand size
27701 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
27702 a 16-bit word
27703 @*
27704 Intel: Implicit, deduced by assembler; for example @code{mov}
27705
27706 @item Instruction repetition
27707 gcc / @emph{as}: Split into two lines; for example
27708 @*
27709 @code{rep}
27710 @*
27711 @code{stosl}
27712 @*
27713 Intel: Keep on one line; for example @code{rep stosl}
27714
27715 @item Order of operands
27716 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
27717 @*
27718 Intel: Destination first; for example @code{mov eax, 4}
27719 @end table
27720
27721 @c ---------------------------------------------------------------------------
27722 @node A Simple Example of Inline Assembler
27723 @section A Simple Example of Inline Assembler
27724
27725 @noindent
27726 The following example will generate a single assembly language statement,
27727 @code{nop}, which does nothing.  Despite its lack of run-time effect,
27728 the example will be useful in illustrating the basics of
27729 the Inline Assembler facility.
27730
27731 @smallexample @c ada
27732 @group
27733 with System.Machine_Code; use System.Machine_Code;
27734 procedure Nothing is
27735 begin
27736    Asm ("nop");
27737 end Nothing;
27738 @end group
27739 @end smallexample
27740
27741 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
27742 here it takes one parameter, a @emph{template string} that must be a static
27743 expression and that will form the generated instruction.
27744 @code{Asm} may be regarded as a compile-time procedure that parses
27745 the template string and additional parameters (none here),
27746 from which it generates a sequence of assembly language instructions.
27747
27748 The examples in this chapter will illustrate several of the forms
27749 for invoking @code{Asm}; a complete specification of the syntax
27750 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
27751 Manual}.
27752
27753 Under the standard GNAT conventions, the @code{Nothing} procedure
27754 should be in a file named @file{nothing.adb}.
27755 You can build the executable in the usual way:
27756 @smallexample
27757 gnatmake nothing
27758 @end smallexample
27759 However, the interesting aspect of this example is not its run-time behavior
27760 but rather the generated assembly code.
27761 To see this output, invoke the compiler as follows:
27762 @smallexample
27763    gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
27764 @end smallexample
27765 where the options are:
27766
27767 @table @code
27768 @item -c
27769 compile only (no bind or link)
27770 @item -S
27771 generate assembler listing
27772 @item -fomit-frame-pointer
27773 do not set up separate stack frames
27774 @item -gnatp
27775 do not add runtime checks
27776 @end table
27777
27778 This gives a human-readable assembler version of the code. The resulting
27779 file will have the same name as the Ada source file, but with a @code{.s}
27780 extension. In our example, the file @file{nothing.s} has the following
27781 contents:
27782
27783 @smallexample
27784 @group
27785 .file "nothing.adb"
27786 gcc2_compiled.:
27787 ___gnu_compiled_ada:
27788 .text
27789    .align 4
27790 .globl __ada_nothing
27791 __ada_nothing:
27792 #APP
27793    nop
27794 #NO_APP
27795    jmp L1
27796    .align 2,0x90
27797 L1:
27798    ret
27799 @end group
27800 @end smallexample
27801
27802 The assembly code you included is clearly indicated by
27803 the compiler, between the @code{#APP} and @code{#NO_APP}
27804 delimiters. The character before the 'APP' and 'NOAPP'
27805 can differ on different targets. For example, GNU/Linux uses '#APP' while
27806 on NT you will see '/APP'.
27807
27808 If you make a mistake in your assembler code (such as using the
27809 wrong size modifier, or using a wrong operand for the instruction) GNAT
27810 will report this error in a temporary file, which will be deleted when
27811 the compilation is finished.  Generating an assembler file will help
27812 in such cases, since you can assemble this file separately using the
27813 @emph{as} assembler that comes with gcc.
27814
27815 Assembling the file using the command
27816
27817 @smallexample
27818 as @file{nothing.s}
27819 @end smallexample
27820 @noindent
27821 will give you error messages whose lines correspond to the assembler
27822 input file, so you can easily find and correct any mistakes you made.
27823 If there are no errors, @emph{as} will generate an object file
27824 @file{nothing.out}.
27825
27826 @c ---------------------------------------------------------------------------
27827 @node Output Variables in Inline Assembler
27828 @section Output Variables in Inline Assembler
27829
27830 @noindent
27831 The examples in this section, showing how to access the processor flags,
27832 illustrate how to specify the destination operands for assembly language
27833 statements.
27834
27835 @smallexample @c ada
27836 @group
27837 with Interfaces; use Interfaces;
27838 with Ada.Text_IO; use Ada.Text_IO;
27839 with System.Machine_Code; use System.Machine_Code;
27840 procedure Get_Flags is
27841    Flags : Unsigned_32;
27842    use ASCII;
27843 begin
27844    Asm ("pushfl"          & LF & HT & -- push flags on stack
27845         "popl %%eax"      & LF & HT & -- load eax with flags
27846         "movl %%eax, %0",             -- store flags in variable
27847         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27848    Put_Line ("Flags register:" & Flags'Img);
27849 end Get_Flags;
27850 @end group
27851 @end smallexample
27852
27853 In order to have a nicely aligned assembly listing, we have separated
27854 multiple assembler statements in the Asm template string with linefeed
27855 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
27856 The resulting section of the assembly output file is:
27857
27858 @smallexample
27859 @group
27860 #APP
27861    pushfl
27862    popl %eax
27863    movl %eax, -40(%ebp)
27864 #NO_APP
27865 @end group
27866 @end smallexample
27867
27868 It would have been legal to write the Asm invocation as:
27869
27870 @smallexample
27871 Asm ("pushfl popl %%eax movl %%eax, %0")
27872 @end smallexample
27873
27874 but in the generated assembler file, this would come out as:
27875
27876 @smallexample
27877 #APP
27878    pushfl popl %eax movl %eax, -40(%ebp)
27879 #NO_APP
27880 @end smallexample
27881
27882 which is not so convenient for the human reader.
27883
27884 We use Ada comments
27885 at the end of each line to explain what the assembler instructions
27886 actually do.  This is a useful convention.
27887
27888 When writing Inline Assembler instructions, you need to precede each register
27889 and variable name with a percent sign.  Since the assembler already requires
27890 a percent sign at the beginning of a register name, you need two consecutive
27891 percent signs for such names in the Asm template string, thus @code{%%eax}.
27892 In the generated assembly code, one of the percent signs will be stripped off.
27893
27894 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
27895 variables: operands you later define using @code{Input} or @code{Output}
27896 parameters to @code{Asm}.
27897 An output variable is illustrated in
27898 the third statement in the Asm template string:
27899 @smallexample
27900 movl %%eax, %0
27901 @end smallexample
27902 The intent is to store the contents of the eax register in a variable that can
27903 be accessed in Ada.  Simply writing @code{movl %%eax, Flags} would not
27904 necessarily work, since the compiler might optimize by using a register
27905 to hold Flags, and the expansion of the @code{movl} instruction would not be
27906 aware of this optimization.  The solution is not to store the result directly
27907 but rather to advise the compiler to choose the correct operand form;
27908 that is the purpose of the @code{%0} output variable.
27909
27910 Information about the output variable is supplied in the @code{Outputs}
27911 parameter to @code{Asm}:
27912 @smallexample
27913 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27914 @end smallexample
27915
27916 The output is defined by the @code{Asm_Output} attribute of the target type;
27917 the general format is
27918 @smallexample
27919 Type'Asm_Output (constraint_string, variable_name)
27920 @end smallexample
27921
27922 The constraint string directs the compiler how
27923 to store/access the associated variable.  In the example
27924 @smallexample
27925 Unsigned_32'Asm_Output ("=m", Flags);
27926 @end smallexample
27927 the @code{"m"} (memory) constraint tells the compiler that the variable
27928 @code{Flags} should be stored in a memory variable, thus preventing
27929 the optimizer from keeping it in a register.  In contrast,
27930 @smallexample
27931 Unsigned_32'Asm_Output ("=r", Flags);
27932 @end smallexample
27933 uses the @code{"r"} (register) constraint, telling the compiler to
27934 store the variable in a register.
27935
27936 If the constraint is preceded by the equal character (@strong{=}), it tells
27937 the compiler that the variable will be used to store data into it.
27938
27939 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
27940 allowing the optimizer to choose whatever it deems best.
27941
27942 There are a fairly large number of constraints, but the ones that are
27943 most useful (for the Intel x86 processor) are the following:
27944
27945 @table @code
27946 @item =
27947 output constraint
27948 @item g
27949 global (i.e.@: can be stored anywhere)
27950 @item m
27951 in memory
27952 @item I
27953 a constant
27954 @item a
27955 use eax
27956 @item b
27957 use ebx
27958 @item c
27959 use ecx
27960 @item d
27961 use edx
27962 @item S
27963 use esi
27964 @item D
27965 use edi
27966 @item r
27967 use one of eax, ebx, ecx or edx
27968 @item q
27969 use one of eax, ebx, ecx, edx, esi or edi
27970 @end table
27971
27972 The full set of constraints is described in the gcc and @emph{as}
27973 documentation; note that it is possible to combine certain constraints
27974 in one constraint string.
27975
27976 You specify the association of an output variable with an assembler operand
27977 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
27978 integer.  Thus in
27979 @smallexample @c ada
27980 @group
27981 Asm ("pushfl"          & LF & HT & -- push flags on stack
27982      "popl %%eax"      & LF & HT & -- load eax with flags
27983      "movl %%eax, %0",             -- store flags in variable
27984      Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27985 @end group
27986 @end smallexample
27987 @noindent
27988 @code{%0} will be replaced in the expanded code by the appropriate operand,
27989 whatever
27990 the compiler decided for the @code{Flags} variable.
27991
27992 In general, you may have any number of output variables:
27993 @itemize @bullet
27994 @item
27995 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
27996 @item
27997 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
27998 of @code{Asm_Output} attributes
27999 @end itemize
28000
28001 For example:
28002 @smallexample @c ada
28003 @group
28004 Asm ("movl %%eax, %0" & LF & HT &
28005      "movl %%ebx, %1" & LF & HT &
28006      "movl %%ecx, %2",
28007      Outputs => (Unsigned_32'Asm_Output ("=g", Var_A),   --  %0 = Var_A
28008                  Unsigned_32'Asm_Output ("=g", Var_B),   --  %1 = Var_B
28009                  Unsigned_32'Asm_Output ("=g", Var_C))); --  %2 = Var_C
28010 @end group
28011 @end smallexample
28012 @noindent
28013 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
28014 in the Ada program.
28015
28016 As a variation on the @code{Get_Flags} example, we can use the constraints
28017 string to direct the compiler to store the eax register into the @code{Flags}
28018 variable, instead of including the store instruction explicitly in the
28019 @code{Asm} template string:
28020
28021 @smallexample @c ada
28022 @group
28023 with Interfaces; use Interfaces;
28024 with Ada.Text_IO; use Ada.Text_IO;
28025 with System.Machine_Code; use System.Machine_Code;
28026 procedure Get_Flags_2 is
28027    Flags : Unsigned_32;
28028    use ASCII;
28029 begin
28030    Asm ("pushfl"      & LF & HT & -- push flags on stack
28031         "popl %%eax",             -- save flags in eax
28032         Outputs => Unsigned_32'Asm_Output ("=a", Flags));
28033    Put_Line ("Flags register:" & Flags'Img);
28034 end Get_Flags_2;
28035 @end group
28036 @end smallexample
28037
28038 @noindent
28039 The @code{"a"} constraint tells the compiler that the @code{Flags}
28040 variable will come from the eax register. Here is the resulting code:
28041
28042 @smallexample
28043 @group
28044 #APP
28045    pushfl
28046    popl %eax
28047 #NO_APP
28048    movl %eax,-40(%ebp)
28049 @end group
28050 @end smallexample
28051
28052 @noindent
28053 The compiler generated the store of eax into Flags after
28054 expanding the assembler code.
28055
28056 Actually, there was no need to pop the flags into the eax register;
28057 more simply, we could just pop the flags directly into the program variable:
28058
28059 @smallexample @c ada
28060 @group
28061 with Interfaces; use Interfaces;
28062 with Ada.Text_IO; use Ada.Text_IO;
28063 with System.Machine_Code; use System.Machine_Code;
28064 procedure Get_Flags_3 is
28065    Flags : Unsigned_32;
28066    use ASCII;
28067 begin
28068    Asm ("pushfl"  & LF & HT & -- push flags on stack
28069         "pop %0",             -- save flags in Flags
28070         Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28071    Put_Line ("Flags register:" & Flags'Img);
28072 end Get_Flags_3;
28073 @end group
28074 @end smallexample
28075
28076 @c ---------------------------------------------------------------------------
28077 @node Input Variables in Inline Assembler
28078 @section Input Variables in Inline Assembler
28079
28080 @noindent
28081 The example in this section illustrates how to specify the source operands
28082 for assembly language statements.
28083 The program simply increments its input value by 1:
28084
28085 @smallexample @c ada
28086 @group
28087 with Interfaces; use Interfaces;
28088 with Ada.Text_IO; use Ada.Text_IO;
28089 with System.Machine_Code; use System.Machine_Code;
28090 procedure Increment is
28091
28092    function Incr (Value : Unsigned_32) return Unsigned_32 is
28093       Result : Unsigned_32;
28094    begin
28095       Asm ("incl %0",
28096            Outputs => Unsigned_32'Asm_Output ("=a", Result),
28097            Inputs  => Unsigned_32'Asm_Input ("a", Value));
28098       return Result;
28099    end Incr;
28100
28101    Value : Unsigned_32;
28102
28103 begin
28104    Value := 5;
28105    Put_Line ("Value before is" & Value'Img);
28106    Value := Incr (Value);
28107    Put_Line ("Value after is" & Value'Img);
28108 end Increment;
28109 @end group
28110 @end smallexample
28111
28112 The @code{Outputs} parameter to @code{Asm} specifies
28113 that the result will be in the eax register and that it is to be stored
28114 in the @code{Result} variable.
28115
28116 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
28117 but with an @code{Asm_Input} attribute.
28118 The @code{"="} constraint, indicating an output value, is not present.
28119
28120 You can have multiple input variables, in the same way that you can have more
28121 than one output variable.
28122
28123 The parameter count (%0, %1) etc, still starts at the first output statement,
28124 and continues with the input statements.
28125
28126 Just as the @code{Outputs} parameter causes the register to be stored into the
28127 target variable after execution of the assembler statements, so does the
28128 @code{Inputs} parameter cause its variable to be loaded into the register
28129 before execution of the assembler statements.
28130
28131 Thus the effect of the @code{Asm} invocation is:
28132 @enumerate
28133 @item load the 32-bit value of @code{Value} into eax
28134 @item execute the @code{incl %eax} instruction
28135 @item store the contents of eax into the @code{Result} variable
28136 @end enumerate
28137
28138 The resulting assembler file (with @option{-O2} optimization) contains:
28139 @smallexample
28140 @group
28141 _increment__incr.1:
28142    subl $4,%esp
28143    movl 8(%esp),%eax
28144 #APP
28145    incl %eax
28146 #NO_APP
28147    movl %eax,%edx
28148    movl %ecx,(%esp)
28149    addl $4,%esp
28150    ret
28151 @end group
28152 @end smallexample
28153
28154 @c ---------------------------------------------------------------------------
28155 @node Inlining Inline Assembler Code
28156 @section Inlining Inline Assembler Code
28157
28158 @noindent
28159 For a short subprogram such as the @code{Incr} function in the previous
28160 section, the overhead of the call and return (creating / deleting the stack
28161 frame) can be significant, compared to the amount of code in the subprogram
28162 body.  A solution is to apply Ada's @code{Inline} pragma to the subprogram,
28163 which directs the compiler to expand invocations of the subprogram at the
28164 point(s) of call, instead of setting up a stack frame for out-of-line calls.
28165 Here is the resulting program:
28166
28167 @smallexample @c ada
28168 @group
28169 with Interfaces; use Interfaces;
28170 with Ada.Text_IO; use Ada.Text_IO;
28171 with System.Machine_Code; use System.Machine_Code;
28172 procedure Increment_2 is
28173
28174    function Incr (Value : Unsigned_32) return Unsigned_32 is
28175       Result : Unsigned_32;
28176    begin
28177       Asm ("incl %0",
28178            Outputs => Unsigned_32'Asm_Output ("=a", Result),
28179            Inputs  => Unsigned_32'Asm_Input ("a", Value));
28180       return Result;
28181    end Incr;
28182    pragma Inline (Increment);
28183
28184    Value : Unsigned_32;
28185
28186 begin
28187    Value := 5;
28188    Put_Line ("Value before is" & Value'Img);
28189    Value := Increment (Value);
28190    Put_Line ("Value after is" & Value'Img);
28191 end Increment_2;
28192 @end group
28193 @end smallexample
28194
28195 Compile the program with both optimization (@option{-O2}) and inlining
28196 (@option{-gnatn}) enabled.
28197
28198 The @code{Incr} function is still compiled as usual, but at the
28199 point in @code{Increment} where our function used to be called:
28200
28201 @smallexample
28202 @group
28203 pushl %edi
28204 call _increment__incr.1
28205 @end group
28206 @end smallexample
28207
28208 @noindent
28209 the code for the function body directly appears:
28210
28211 @smallexample
28212 @group
28213 movl %esi,%eax
28214 #APP
28215    incl %eax
28216 #NO_APP
28217    movl %eax,%edx
28218 @end group
28219 @end smallexample
28220
28221 @noindent
28222 thus saving the overhead of stack frame setup and an out-of-line call.
28223
28224 @c ---------------------------------------------------------------------------
28225 @node Other Asm Functionality
28226 @section Other @code{Asm} Functionality
28227
28228 @noindent
28229 This section describes two important parameters to the @code{Asm}
28230 procedure: @code{Clobber}, which identifies register usage;
28231 and @code{Volatile}, which inhibits unwanted optimizations.
28232
28233 @menu
28234 * The Clobber Parameter::
28235 * The Volatile Parameter::
28236 @end menu
28237
28238 @c ---------------------------------------------------------------------------
28239 @node The Clobber Parameter
28240 @subsection The @code{Clobber} Parameter
28241
28242 @noindent
28243 One of the dangers of intermixing assembly language and a compiled language
28244 such as Ada is that the compiler needs to be aware of which registers are
28245 being used by the assembly code.  In some cases, such as the earlier examples,
28246 the constraint string is sufficient to indicate register usage (e.g.,
28247 @code{"a"} for
28248 the eax register).  But more generally, the compiler needs an explicit
28249 identification of the registers that are used by the Inline Assembly
28250 statements.
28251
28252 Using a register that the compiler doesn't know about
28253 could be a side effect of an instruction (like @code{mull}
28254 storing its result in both eax and edx).
28255 It can also arise from explicit register usage in your
28256 assembly code; for example:
28257 @smallexample
28258 @group
28259 Asm ("movl %0, %%ebx" & LF & HT &
28260      "movl %%ebx, %1",
28261      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28262      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In));
28263 @end group
28264 @end smallexample
28265 @noindent
28266 where the compiler (since it does not analyze the @code{Asm} template string)
28267 does not know you are using the ebx register.
28268
28269 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
28270 to identify the registers that will be used by your assembly code:
28271
28272 @smallexample
28273 @group
28274 Asm ("movl %0, %%ebx" & LF & HT &
28275      "movl %%ebx, %1",
28276      Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28277      Inputs  => Unsigned_32'Asm_Input  ("g", Var_In),
28278      Clobber => "ebx");
28279 @end group
28280 @end smallexample
28281
28282 The Clobber parameter is a static string expression specifying the
28283 register(s) you are using.  Note that register names are @emph{not} prefixed
28284 by a percent sign. Also, if more than one register is used then their names
28285 are separated by commas; e.g., @code{"eax, ebx"}
28286
28287 The @code{Clobber} parameter has several additional uses:
28288 @enumerate
28289 @item Use ``register'' name @code{cc} to indicate that flags might have changed
28290 @item Use ``register'' name @code{memory} if you changed a memory location
28291 @end enumerate
28292
28293 @c ---------------------------------------------------------------------------
28294 @node The Volatile Parameter
28295 @subsection The @code{Volatile} Parameter
28296 @cindex Volatile parameter
28297
28298 @noindent
28299 Compiler optimizations in the presence of Inline Assembler may sometimes have
28300 unwanted effects.  For example, when an @code{Asm} invocation with an input
28301 variable is inside a loop, the compiler might move the loading of the input
28302 variable outside the loop, regarding it as a one-time initialization.
28303
28304 If this effect is not desired, you can disable such optimizations by setting
28305 the @code{Volatile} parameter to @code{True}; for example:
28306
28307 @smallexample @c ada
28308 @group
28309 Asm ("movl %0, %%ebx" & LF & HT &
28310      "movl %%ebx, %1",
28311      Outputs  => Unsigned_32'Asm_Output ("=g", Var_Out),
28312      Inputs   => Unsigned_32'Asm_Input  ("g", Var_In),
28313      Clobber  => "ebx",
28314      Volatile => True);
28315 @end group
28316 @end smallexample
28317
28318 By default, @code{Volatile} is set to @code{False} unless there is no
28319 @code{Outputs} parameter.
28320
28321 Although setting @code{Volatile} to @code{True} prevents unwanted
28322 optimizations, it will also disable other optimizations that might be
28323 important for efficiency. In general, you should set @code{Volatile}
28324 to @code{True} only if the compiler's optimizations have created
28325 problems.
28326 @c END OF INLINE ASSEMBLER CHAPTER
28327 @c ===============================
28328
28329 @c ***********************************
28330 @c * Compatibility and Porting Guide *
28331 @c ***********************************
28332 @node Compatibility and Porting Guide
28333 @appendix Compatibility and Porting Guide
28334
28335 @noindent
28336 This chapter describes the compatibility issues that may arise between
28337 GNAT and other Ada compilation systems (including those for Ada 83),
28338 and shows how GNAT can expedite porting
28339 applications developed in other Ada environments.
28340
28341 @menu
28342 * Compatibility with Ada 83::
28343 * Compatibility between Ada 95 and Ada 2005::
28344 * Implementation-dependent characteristics::
28345 * Compatibility with Other Ada Systems::
28346 * Representation Clauses::
28347 @ifclear vms
28348 @c Brief section is only in non-VMS version
28349 @c Full chapter is in VMS version
28350 * Compatibility with HP Ada 83::
28351 @end ifclear
28352 @ifset vms
28353 * Transitioning to 64-Bit GNAT for OpenVMS::
28354 @end ifset
28355 @end menu
28356
28357 @node Compatibility with Ada 83
28358 @section Compatibility with Ada 83
28359 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
28360
28361 @noindent
28362 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83.  In
28363 particular, the design intention was that the difficulties associated
28364 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
28365 that occur when moving from one Ada 83 system to another.
28366
28367 However, there are a number of points at which there are minor
28368 incompatibilities.  The @cite{Ada 95 Annotated Reference Manual} contains
28369 full details of these issues,
28370 and should be consulted for a complete treatment.
28371 In practice the
28372 following subsections treat the most likely issues to be encountered.
28373
28374 @menu
28375 * Legal Ada 83 programs that are illegal in Ada 95::
28376 * More deterministic semantics::
28377 * Changed semantics::
28378 * Other language compatibility issues::
28379 @end menu
28380
28381 @node Legal Ada 83 programs that are illegal in Ada 95
28382 @subsection Legal Ada 83 programs that are illegal in Ada 95
28383
28384 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
28385 Ada 95 and thus also in Ada 2005:
28386
28387 @table @emph
28388 @item Character literals
28389 Some uses of character literals are ambiguous.  Since Ada 95 has introduced
28390 @code{Wide_Character} as a new predefined character type, some uses of
28391 character literals that were legal in Ada 83 are illegal in Ada 95.
28392 For example:
28393 @smallexample @c ada
28394    for Char in 'A' .. 'Z' loop @dots{} end loop;
28395 @end smallexample
28396
28397 @noindent
28398 The problem is that @code{'A'} and @code{'Z'} could be from either
28399 @code{Character} or @code{Wide_Character}.  The simplest correction
28400 is to make the type explicit; e.g.:
28401 @smallexample @c ada
28402    for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
28403 @end smallexample
28404
28405 @item New reserved words
28406 The identifiers @code{abstract}, @code{aliased}, @code{protected},
28407 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
28408 Existing Ada 83 code using any of these identifiers must be edited to
28409 use some alternative name.
28410
28411 @item Freezing rules
28412 The rules in Ada 95 are slightly different with regard to the point at
28413 which entities are frozen, and representation pragmas and clauses are
28414 not permitted past the freeze point.  This shows up most typically in
28415 the form of an error message complaining that a representation item
28416 appears too late, and the appropriate corrective action is to move
28417 the item nearer to the declaration of the entity to which it refers.
28418
28419 A particular case is that representation pragmas
28420 @ifset vms
28421 (including the
28422 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
28423 @end ifset
28424 cannot be applied to a subprogram body.  If necessary, a separate subprogram
28425 declaration must be introduced to which the pragma can be applied.
28426
28427 @item Optional bodies for library packages
28428 In Ada 83, a package that did not require a package body was nevertheless
28429 allowed to have one.  This lead to certain surprises in compiling large
28430 systems (situations in which the body could be unexpectedly ignored by the
28431 binder).  In Ada 95, if a package does not require a body then it is not
28432 permitted to have a body.  To fix this problem, simply remove a redundant
28433 body if it is empty, or, if it is non-empty, introduce a dummy declaration
28434 into the spec that makes the body required.  One approach is to add a private
28435 part to the package declaration (if necessary), and define a parameterless
28436 procedure called @code{Requires_Body}, which must then be given a dummy
28437 procedure body in the package body, which then becomes required.
28438 Another approach (assuming that this does not introduce elaboration
28439 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
28440 since one effect of this pragma is to require the presence of a package body.
28441
28442 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
28443 In Ada 95, the exception @code{Numeric_Error} is a renaming of
28444 @code{Constraint_Error}.
28445 This means that it is illegal to have separate exception handlers for
28446 the two exceptions.  The fix is simply to remove the handler for the
28447 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
28448 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
28449
28450 @item Indefinite subtypes in generics
28451 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
28452 as the actual for a generic formal private type, but then the instantiation
28453 would be illegal if there were any instances of declarations of variables
28454 of this type in the generic body.  In Ada 95, to avoid this clear violation
28455 of the methodological principle known as the ``contract model'',
28456 the generic declaration explicitly indicates whether
28457 or not such instantiations are permitted.  If a generic formal parameter
28458 has explicit unknown discriminants, indicated by using @code{(<>)} after the
28459 subtype name, then it can be instantiated with indefinite types, but no
28460 stand-alone variables can be declared of this type.  Any attempt to declare
28461 such a variable will result in an illegality at the time the generic is
28462 declared.  If the @code{(<>)} notation is not used, then it is illegal
28463 to instantiate the generic with an indefinite type.
28464 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
28465 It will show up as a compile time error, and
28466 the fix is usually simply to add the @code{(<>)} to the generic declaration.
28467 @end table
28468
28469 @node More deterministic semantics
28470 @subsection More deterministic semantics
28471
28472 @table @emph
28473 @item Conversions
28474 Conversions from real types to integer types round away from 0.  In Ada 83
28475 the conversion Integer(2.5) could deliver either 2 or 3 as its value.  This
28476 implementation freedom was intended to support unbiased rounding in
28477 statistical applications, but in practice it interfered with portability.
28478 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
28479 is required.  Numeric code may be affected by this change in semantics.
28480 Note, though, that this issue is no worse than already existed in Ada 83
28481 when porting code from one vendor to another.
28482
28483 @item Tasking
28484 The Real-Time Annex introduces a set of policies that define the behavior of
28485 features that were implementation dependent in Ada 83, such as the order in
28486 which open select branches are executed.
28487 @end table
28488
28489 @node Changed semantics
28490 @subsection Changed semantics
28491
28492 @noindent
28493 The worst kind of incompatibility is one where a program that is legal in
28494 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
28495 possible in Ada 83.  Fortunately this is extremely rare, but the one
28496 situation that you should be alert to is the change in the predefined type
28497 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
28498
28499 @table @emph
28500 @item Range of type @code{Character}
28501 The range of @code{Standard.Character} is now the full 256 characters
28502 of Latin-1, whereas in most Ada 83 implementations it was restricted
28503 to 128 characters. Although some of the effects of
28504 this change will be manifest in compile-time rejection of legal
28505 Ada 83 programs it is possible for a working Ada 83 program to have
28506 a different effect in Ada 95, one that was not permitted in Ada 83.
28507 As an example, the expression
28508 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
28509 delivers @code{255} as its value.
28510 In general, you should look at the logic of any
28511 character-processing Ada 83 program and see whether it needs to be adapted
28512 to work correctly with Latin-1.  Note that the predefined Ada 95 API has a
28513 character handling package that may be relevant if code needs to be adapted
28514 to account for the additional Latin-1 elements.
28515 The desirable fix is to
28516 modify the program to accommodate the full character set, but in some cases
28517 it may be convenient to define a subtype or derived type of Character that
28518 covers only the restricted range.
28519 @cindex Latin-1
28520 @end table
28521
28522 @node Other language compatibility issues
28523 @subsection Other language compatibility issues
28524
28525 @table @emph
28526 @item @option{-gnat83} switch
28527 All implementations of GNAT provide a switch that causes GNAT to operate
28528 in Ada 83 mode.  In this mode, some but not all compatibility problems
28529 of the type described above are handled automatically.  For example, the
28530 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
28531 as identifiers as in Ada 83.
28532 However,
28533 in practice, it is usually advisable to make the necessary modifications
28534 to the program to remove the need for using this switch.
28535 See @ref{Compiling Different Versions of Ada}.
28536
28537 @item Support for removed Ada 83 pragmas and attributes
28538 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
28539 generally because they were replaced by other mechanisms.  Ada 95 and Ada 2005
28540 compilers are allowed, but not required, to implement these missing
28541 elements.  In contrast with some other compilers, GNAT implements all
28542 such pragmas and attributes, eliminating this compatibility concern.  These
28543 include @code{pragma Interface} and the floating point type attributes
28544 (@code{Emax}, @code{Mantissa}, etc.), among other items.
28545 @end table
28546
28547
28548 @node Compatibility between Ada 95 and Ada 2005
28549 @section Compatibility between Ada 95 and Ada 2005
28550 @cindex Compatibility between Ada 95 and Ada 2005
28551
28552 @noindent
28553 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
28554 a number of incompatibilities. Several are enumerated below;
28555 for a complete description please see the
28556 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
28557 @cite{Rationale for Ada 2005}.
28558
28559 @table @emph
28560 @item New reserved words.
28561 The words @code{interface}, @code{overriding} and @code{synchronized} are
28562 reserved in Ada 2005.
28563 A pre-Ada 2005 program that uses any of these as an identifier will be
28564 illegal.
28565
28566 @item New declarations in predefined packages.
28567 A number of packages in the predefined environment contain new declarations:
28568 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
28569 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
28570 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
28571 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
28572 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
28573 If an Ada 95 program does a @code{with} and @code{use} of any of these
28574 packages, the new declarations may cause name clashes.
28575
28576 @item Access parameters.
28577 A nondispatching subprogram with an access parameter cannot be renamed
28578 as a dispatching operation.  This was permitted in Ada 95.
28579
28580 @item Access types, discriminants, and constraints.
28581 Rule changes in this area have led to some incompatibilities; for example,
28582 constrained subtypes of some access types are not permitted in Ada 2005.
28583
28584 @item Aggregates for limited types.
28585 The allowance of aggregates for limited types in Ada 2005 raises the
28586 possibility of ambiguities in legal Ada 95 programs, since additional types
28587 now need to be considered in expression resolution.
28588
28589 @item Fixed-point multiplication and division.
28590 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
28591 were legal in Ada 95 and invoked the predefined versions of these operations,
28592 are now ambiguous.
28593 The ambiguity may be resolved either by applying a type conversion to the
28594 expression, or by explicitly invoking the operation from package
28595 @code{Standard}.
28596
28597 @item Return-by-reference types.
28598 The Ada 95 return-by-reference mechanism has been removed.  Instead, the user
28599 can declare a function returning a value from an anonymous access type.
28600 @end table
28601
28602
28603 @node Implementation-dependent characteristics
28604 @section Implementation-dependent characteristics
28605 @noindent
28606 Although the Ada language defines the semantics of each construct as
28607 precisely as practical, in some situations (for example for reasons of
28608 efficiency, or where the effect is heavily dependent on the host or target
28609 platform) the implementation is allowed some freedom.  In porting Ada 83
28610 code to GNAT, you need to be aware of whether / how the existing code
28611 exercised such implementation dependencies.  Such characteristics fall into
28612 several categories, and GNAT offers specific support in assisting the
28613 transition from certain Ada 83 compilers.
28614
28615 @menu
28616 * Implementation-defined pragmas::
28617 * Implementation-defined attributes::
28618 * Libraries::
28619 * Elaboration order::
28620 * Target-specific aspects::
28621 @end menu
28622
28623 @node Implementation-defined pragmas
28624 @subsection Implementation-defined pragmas
28625
28626 @noindent
28627 Ada compilers are allowed to supplement the language-defined pragmas, and
28628 these are a potential source of non-portability.  All GNAT-defined pragmas
28629 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
28630 Reference Manual}, and these include several that are specifically
28631 intended to correspond to other vendors' Ada 83 pragmas.
28632 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
28633 For compatibility with HP Ada 83, GNAT supplies the pragmas
28634 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
28635 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
28636 and @code{Volatile}.
28637 Other relevant pragmas include @code{External} and @code{Link_With}.
28638 Some vendor-specific
28639 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
28640 recognized, thus
28641 avoiding compiler rejection of units that contain such pragmas; they are not
28642 relevant in a GNAT context and hence are not otherwise implemented.
28643
28644 @node Implementation-defined attributes
28645 @subsection Implementation-defined attributes
28646
28647 Analogous to pragmas, the set of attributes may be extended by an
28648 implementation.  All GNAT-defined attributes are described in
28649 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
28650 Manual}, and these include several that are specifically intended
28651 to correspond to other vendors' Ada 83 attributes.  For migrating from VADS,
28652 the attribute @code{VADS_Size} may be useful.  For compatibility with HP
28653 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
28654 @code{Type_Class}.
28655
28656 @node Libraries
28657 @subsection Libraries
28658 @noindent
28659 Vendors may supply libraries to supplement the standard Ada API.  If Ada 83
28660 code uses vendor-specific libraries then there are several ways to manage
28661 this in Ada 95 or Ada 2005:
28662 @enumerate
28663 @item
28664 If the source code for the libraries (specs and bodies) are
28665 available, then the libraries can be migrated in the same way as the
28666 application.
28667 @item
28668 If the source code for the specs but not the bodies are
28669 available, then you can reimplement the bodies.
28670 @item
28671 Some features introduced by Ada 95 obviate the need for library support.  For
28672 example most Ada 83 vendors supplied a package for unsigned integers.  The
28673 Ada 95 modular type feature is the preferred way to handle this need, so
28674 instead of migrating or reimplementing the unsigned integer package it may
28675 be preferable to retrofit the application using modular types.
28676 @end enumerate
28677
28678 @node Elaboration order
28679 @subsection Elaboration order
28680 @noindent
28681 The implementation can choose any elaboration order consistent with the unit
28682 dependency relationship.  This freedom means that some orders can result in
28683 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
28684 to invoke a subprogram its body has been elaborated, or to instantiate a
28685 generic before the generic body has been elaborated.  By default GNAT
28686 attempts to choose a safe order (one that will not encounter access before
28687 elaboration problems) by implicitly inserting @code{Elaborate} or
28688 @code{Elaborate_All} pragmas where
28689 needed.  However, this can lead to the creation of elaboration circularities
28690 and a resulting rejection of the program by gnatbind.  This issue is
28691 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
28692 In brief, there are several
28693 ways to deal with this situation:
28694
28695 @itemize @bullet
28696 @item
28697 Modify the program to eliminate the circularities, e.g.@: by moving
28698 elaboration-time code into explicitly-invoked procedures
28699 @item
28700 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
28701 @code{Elaborate} pragmas, and then inhibit the generation of implicit
28702 @code{Elaborate_All}
28703 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
28704 (by selectively suppressing elaboration checks via pragma
28705 @code{Suppress(Elaboration_Check)} when it is safe to do so).
28706 @end itemize
28707
28708 @node Target-specific aspects
28709 @subsection Target-specific aspects
28710 @noindent
28711 Low-level applications need to deal with machine addresses, data
28712 representations, interfacing with assembler code, and similar issues.  If
28713 such an Ada 83 application is being ported to different target hardware (for
28714 example where the byte endianness has changed) then you will need to
28715 carefully examine the program logic; the porting effort will heavily depend
28716 on the robustness of the original design.  Moreover, Ada 95 (and thus
28717 Ada 2005) are sometimes
28718 incompatible with typical Ada 83 compiler practices regarding implicit
28719 packing, the meaning of the Size attribute, and the size of access values.
28720 GNAT's approach to these issues is described in @ref{Representation Clauses}.
28721
28722 @node Compatibility with Other Ada Systems
28723 @section Compatibility with Other Ada Systems
28724
28725 @noindent
28726 If programs avoid the use of implementation dependent and
28727 implementation defined features, as documented in the @cite{Ada
28728 Reference Manual}, there should be a high degree of portability between
28729 GNAT and other Ada systems.  The following are specific items which
28730 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
28731 compilers, but do not affect porting code to GNAT@.
28732 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
28733 the following issues may or may not arise for Ada 2005 programs
28734 when other compilers appear.)
28735
28736 @table @emph
28737 @item Ada 83 Pragmas and Attributes
28738 Ada 95 compilers are allowed, but not required, to implement the missing
28739 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
28740 GNAT implements all such pragmas and attributes, eliminating this as
28741 a compatibility concern, but some other Ada 95 compilers reject these
28742 pragmas and attributes.
28743
28744 @item Specialized Needs Annexes
28745 GNAT implements the full set of special needs annexes.  At the
28746 current time, it is the only Ada 95 compiler to do so.  This means that
28747 programs making use of these features may not be portable to other Ada
28748 95 compilation systems.
28749
28750 @item Representation Clauses
28751 Some other Ada 95 compilers implement only the minimal set of
28752 representation clauses required by the Ada 95 reference manual.  GNAT goes
28753 far beyond this minimal set, as described in the next section.
28754 @end table
28755
28756 @node Representation Clauses
28757 @section Representation Clauses
28758
28759 @noindent
28760 The Ada 83 reference manual was quite vague in describing both the minimal
28761 required implementation of representation clauses, and also their precise
28762 effects.  Ada 95 (and thus also Ada 2005) are much more explicit, but the
28763 minimal set of capabilities required is still quite limited.
28764
28765 GNAT implements the full required set of capabilities in
28766 Ada 95 and Ada 2005, but also goes much further, and in particular
28767 an effort has been made to be compatible with existing Ada 83 usage to the
28768 greatest extent possible.
28769
28770 A few cases exist in which Ada 83 compiler behavior is incompatible with
28771 the requirements in Ada 95 (and thus also Ada 2005).  These are instances of
28772 intentional or accidental dependence on specific implementation dependent
28773 characteristics of these Ada 83 compilers.  The following is a list of
28774 the cases most likely to arise in existing Ada 83 code.
28775
28776 @table @emph
28777 @item Implicit Packing
28778 Some Ada 83 compilers allowed a Size specification to cause implicit
28779 packing of an array or record.  This could cause expensive implicit
28780 conversions for change of representation in the presence of derived
28781 types, and the Ada design intends to avoid this possibility.
28782 Subsequent AI's were issued to make it clear that such implicit
28783 change of representation in response to a Size clause is inadvisable,
28784 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
28785 Reference Manuals as implementation advice that is followed by GNAT@.
28786 The problem will show up as an error
28787 message rejecting the size clause.  The fix is simply to provide
28788 the explicit pragma @code{Pack}, or for more fine tuned control, provide
28789 a Component_Size clause.
28790
28791 @item Meaning of Size Attribute
28792 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
28793 the minimal number of bits required to hold values of the type.  For example,
28794 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
28795 32 (since no sign bit is required).  Some Ada 83 compilers gave 31, and
28796 some 32 in this situation.  This problem will usually show up as a compile
28797 time error, but not always.  It is a good idea to check all uses of the
28798 'Size attribute when porting Ada 83 code.  The GNAT specific attribute
28799 Object_Size can provide a useful way of duplicating the behavior of
28800 some Ada 83 compiler systems.
28801
28802 @item Size of Access Types
28803 A common assumption in Ada 83 code is that an access type is in fact a pointer,
28804 and that therefore it will be the same size as a System.Address value.  This
28805 assumption is true for GNAT in most cases with one exception.  For the case of
28806 a pointer to an unconstrained array type (where the bounds may vary from one
28807 value of the access type to another), the default is to use a ``fat pointer'',
28808 which is represented as two separate pointers, one to the bounds, and one to
28809 the array.  This representation has a number of advantages, including improved
28810 efficiency.  However, it may cause some difficulties in porting existing Ada 83
28811 code which makes the assumption that, for example, pointers fit in 32 bits on
28812 a machine with 32-bit addressing.
28813
28814 To get around this problem, GNAT also permits the use of ``thin pointers'' for
28815 access types in this case (where the designated type is an unconstrained array
28816 type).  These thin pointers are indeed the same size as a System.Address value.
28817 To specify a thin pointer, use a size clause for the type, for example:
28818
28819 @smallexample @c ada
28820 type X is access all String;
28821 for X'Size use Standard'Address_Size;
28822 @end smallexample
28823
28824 @noindent
28825 which will cause the type X to be represented using a single pointer.
28826 When using this representation, the bounds are right behind the array.
28827 This representation is slightly less efficient, and does not allow quite
28828 such flexibility in the use of foreign pointers or in using the
28829 Unrestricted_Access attribute to create pointers to non-aliased objects.
28830 But for any standard portable use of the access type it will work in
28831 a functionally correct manner and allow porting of existing code.
28832 Note that another way of forcing a thin pointer representation
28833 is to use a component size clause for the element size in an array,
28834 or a record representation clause for an access field in a record.
28835 @end table
28836
28837 @ifclear vms
28838 @c This brief section is only in the non-VMS version
28839 @c The complete chapter on HP Ada is in the VMS version
28840 @node Compatibility with HP Ada 83
28841 @section Compatibility with HP Ada 83
28842
28843 @noindent
28844 The VMS version of GNAT fully implements all the pragmas and attributes
28845 provided by HP Ada 83, as well as providing the standard HP Ada 83
28846 libraries, including Starlet.  In addition, data layouts and parameter
28847 passing conventions are highly compatible.  This means that porting
28848 existing HP Ada 83 code to GNAT in VMS systems should be easier than
28849 most other porting efforts.  The following are some of the most
28850 significant differences between GNAT and HP Ada 83.
28851
28852 @table @emph
28853 @item Default floating-point representation
28854 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
28855 it is VMS format.  GNAT does implement the necessary pragmas
28856 (Long_Float, Float_Representation) for changing this default.
28857
28858 @item System
28859 The package System in GNAT exactly corresponds to the definition in the
28860 Ada 95 reference manual, which means that it excludes many of the
28861 HP Ada 83 extensions.  However, a separate package Aux_DEC is provided
28862 that contains the additional definitions, and a special pragma,
28863 Extend_System allows this package to be treated transparently as an
28864 extension of package System.
28865
28866 @item To_Address
28867 The definitions provided by Aux_DEC are exactly compatible with those
28868 in the HP Ada 83 version of System, with one exception.
28869 HP Ada provides the following declarations:
28870
28871 @smallexample @c ada
28872 TO_ADDRESS (INTEGER)
28873 TO_ADDRESS (UNSIGNED_LONGWORD)
28874 TO_ADDRESS (@i{universal_integer})
28875 @end smallexample
28876
28877 @noindent
28878 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
28879 an extension to Ada 83 not strictly compatible with the reference manual.
28880 In GNAT, we are constrained to be exactly compatible with the standard,
28881 and this means we cannot provide this capability.  In HP Ada 83, the
28882 point of this definition is to deal with a call like:
28883
28884 @smallexample @c ada
28885 TO_ADDRESS (16#12777#);
28886 @end smallexample
28887
28888 @noindent
28889 Normally, according to the Ada 83 standard, one would expect this to be
28890 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
28891 of TO_ADDRESS@.  However, in HP Ada 83, there is no ambiguity, since the
28892 definition using @i{universal_integer} takes precedence.
28893
28894 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
28895 is not possible to be 100% compatible.  Since there are many programs using
28896 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
28897 to change the name of the function in the UNSIGNED_LONGWORD case, so the
28898 declarations provided in the GNAT version of AUX_Dec are:
28899
28900 @smallexample @c ada
28901 function To_Address (X : Integer) return Address;
28902 pragma Pure_Function (To_Address);
28903
28904 function To_Address_Long (X : Unsigned_Longword)
28905  return Address;
28906 pragma Pure_Function (To_Address_Long);
28907 @end smallexample
28908
28909 @noindent
28910 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
28911 change the name to TO_ADDRESS_LONG@.
28912
28913 @item Task_Id values
28914 The Task_Id values assigned will be different in the two systems, and GNAT
28915 does not provide a specified value for the Task_Id of the environment task,
28916 which in GNAT is treated like any other declared task.
28917 @end table
28918
28919 @noindent
28920 For full details on these and other less significant compatibility issues,
28921 see appendix E of the HP publication entitled @cite{HP Ada, Technical
28922 Overview and Comparison on HP Platforms}.
28923
28924 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
28925 attributes are recognized, although only a subset of them can sensibly
28926 be implemented.  The description of pragmas in @ref{Implementation
28927 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
28928 indicates whether or not they are applicable to non-VMS systems.
28929 @end ifclear
28930
28931 @ifset vms
28932 @node Transitioning to 64-Bit GNAT for OpenVMS
28933 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
28934
28935 @noindent
28936 This section is meant to assist users of pre-2006 @value{EDITION}
28937 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
28938 the version of the GNAT technology supplied in 2006 and later for
28939 OpenVMS on both Alpha and I64.
28940
28941 @menu
28942 * Introduction to transitioning::
28943 * Migration of 32 bit code::
28944 * Taking advantage of 64 bit addressing::
28945 * Technical details::
28946 @end menu
28947
28948 @node Introduction to transitioning
28949 @subsection Introduction
28950
28951 @noindent
28952 64-bit @value{EDITION} for Open VMS has been designed to meet
28953 three main goals:
28954
28955 @enumerate
28956 @item
28957 Providing a full conforming implementation of Ada 95 and Ada 2005
28958
28959 @item
28960 Allowing maximum backward compatibility, thus easing migration of existing
28961 Ada source code
28962
28963 @item
28964 Supplying a path for exploiting the full 64-bit address range
28965 @end enumerate
28966
28967 @noindent
28968 Ada's strong typing semantics has made it
28969 impractical to have different 32-bit and 64-bit modes. As soon as
28970 one object could possibly be outside the 32-bit address space, this
28971 would make it necessary for the @code{System.Address} type to be 64 bits.
28972 In particular, this would cause inconsistencies if 32-bit code is
28973 called from 64-bit code that raises an exception.
28974
28975 This issue has been resolved by always using 64-bit addressing
28976 at the system level, but allowing for automatic conversions between
28977 32-bit and 64-bit addresses where required. Thus users who
28978 do not currently require 64-bit addressing capabilities, can
28979 recompile their code with only minimal changes (and indeed
28980 if the code is written in portable Ada, with no assumptions about
28981 the size of the @code{Address} type, then no changes at all are necessary).
28982 At the same time,
28983 this approach provides a simple, gradual upgrade path to future
28984 use of larger memories than available for 32-bit systems.
28985 Also, newly written applications or libraries will by default
28986 be fully compatible with future systems exploiting 64-bit
28987 addressing capabilities.
28988
28989 @ref{Migration of 32 bit code}, will focus on porting applications
28990 that do not require more than 2 GB of
28991 addressable memory. This code will be referred to as
28992 @emph{32-bit code}.
28993 For applications intending to exploit the full 64-bit address space,
28994 @ref{Taking advantage of 64 bit addressing},
28995 will consider further changes that may be required.
28996 Such code will be referred to below as @emph{64-bit code}.
28997
28998 @node Migration of 32 bit code
28999 @subsection Migration of 32-bit code
29000
29001 @menu
29002 * Address types::
29003 * Access types and 32/64-bit allocation::
29004 * Unchecked conversions::
29005 * Predefined constants::
29006 * Interfacing with C::
29007 * 32/64-bit descriptors::
29008 * Experience with source compatibility::
29009 @end menu
29010
29011 @node Address types
29012 @subsubsection Address types
29013
29014 @noindent
29015 To solve the problem of mixing 64-bit and 32-bit addressing,
29016 while maintaining maximum backward compatibility, the following
29017 approach has been taken:
29018
29019 @itemize @bullet
29020 @item
29021 @code{System.Address} always has a size of 64 bits
29022 @cindex @code{System.Address} size
29023 @cindex @code{Address} size
29024
29025 @item
29026 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
29027 @cindex @code{System.Short_Address} size
29028 @cindex @code{Short_Address} size
29029 @end itemize
29030
29031 @noindent
29032 Since @code{System.Short_Address} is a subtype of @code{System.Address},
29033 a @code{Short_Address}
29034 may be used where an @code{Address} is required, and vice versa, without
29035 needing explicit type conversions.
29036 By virtue of the Open VMS parameter passing conventions,
29037 even imported
29038 and exported subprograms that have 32-bit address parameters are
29039 compatible with those that have 64-bit address parameters.
29040 (See @ref{Making code 64 bit clean} for details.)
29041
29042 The areas that may need attention are those where record types have
29043 been defined that contain components of the type @code{System.Address}, and
29044 where objects of this type are passed to code expecting a record layout with
29045 32-bit addresses.
29046
29047 Different compilers on different platforms cannot be
29048 expected to represent the same type in the same way,
29049 since alignment constraints
29050 and other system-dependent properties affect the compiler's decision.
29051 For that reason, Ada code
29052 generally uses representation clauses to specify the expected
29053 layout where required.
29054
29055 If such a representation clause uses 32 bits for a component having
29056 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
29057 will detect that error and produce a specific diagnostic message.
29058 The developer should then determine whether the representation
29059 should be 64 bits or not and make either of two changes:
29060 change the size to 64 bits and leave the type as @code{System.Address}, or
29061 leave the size as 32 bits and change the type to @code{System.Short_Address}.
29062 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
29063 required in any code setting or accessing the field; the compiler will
29064 automatically perform any needed conversions between address
29065 formats.
29066
29067 @node Access types and 32/64-bit allocation
29068 @subsubsection Access types and 32/64-bit allocation
29069 @cindex 32-bit allocation
29070 @cindex 64-bit allocation
29071
29072 @noindent
29073 By default, objects designated by access values are always allocated in
29074 the 64-bit address space, and access values themselves are represented
29075 in 64 bits.  If these defaults are not appropriate, and 32-bit allocation
29076 is required (for example if the address of an allocated object is assigned
29077 to a @code{Short_Address} variable), then several alternatives are available:
29078
29079 @itemize @bullet
29080 @item
29081 A pool-specific access type (ie, an @w{Ada 83} access type, whose
29082 definition is @code{access T} versus @code{access all T} or
29083 @code{access constant T}), may be declared with a @code{'Size} representation
29084 clause that establishes the size as 32 bits.
29085 In such circumstances allocations for that type will
29086 be from the 32-bit heap.  Such a clause is not permitted
29087 for a general access type (declared with @code{access all} or
29088 @code{access constant}) as values of such types must be able to refer
29089 to any object of the designated type, including objects residing outside
29090 the 32-bit address range.  Existing @w{Ada 83} code will not contain such
29091 type definitions, however, since general access types were introduced
29092 in @w{Ada 95}.
29093
29094 @item
29095 Switches for @command{GNAT BIND} control whether the internal GNAT
29096 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
29097 @cindex @code{__gnat_malloc}
29098 The switches are respectively @option{-H64} (the default) and
29099 @option{-H32}.
29100 @cindex @option{-H32} (@command{gnatbind})
29101 @cindex @option{-H64} (@command{gnatbind})
29102
29103 @item
29104 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
29105 @cindex @code{GNAT$NO_MALLOC_64} environment variable
29106 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
29107 If this variable is left
29108 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
29109 then the default (64-bit) allocation is used.
29110 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
29111 then 32-bit allocation is used.  The gnatbind qualifiers described above
29112 override this logical name.
29113
29114 @item
29115 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
29116 @cindex @option{-mno-malloc64} (^gcc^gcc^)
29117 at a low level to convert explicit calls to @code{malloc} and related
29118 functions from the C run-time library so that they perform allocations
29119 in the 32-bit heap.
29120 Since all internal allocations from GNAT use @code{__gnat_malloc},
29121 this switch is not required unless the program makes explicit calls on
29122 @code{malloc} (or related functions) from interfaced C code.
29123 @end itemize
29124
29125
29126 @node Unchecked conversions
29127 @subsubsection Unchecked conversions
29128
29129 @noindent
29130 In the case of an @code{Unchecked_Conversion} where the source type is a
29131 64-bit access type or the type @code{System.Address}, and the target
29132 type is a 32-bit type, the compiler will generate a warning.
29133 Even though the generated code will still perform the required
29134 conversions, it is highly recommended in these cases to use
29135 respectively a 32-bit access type or @code{System.Short_Address}
29136 as the source type.
29137
29138 @node Predefined constants
29139 @subsubsection Predefined constants
29140
29141 @noindent
29142 The following table shows the correspondence between pre-2006 versions of
29143 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
29144 (``New''):
29145
29146 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
29147 @item   @b{Constant}                     @tab @b{Old} @tab @b{New}
29148 @item   @code{System.Word_Size}          @tab 32      @tab 64
29149 @item   @code{System.Memory_Size}        @tab 2**32   @tab 2**64
29150 @item   @code{System.Short_Memory_Size}  @tab 2**32   @tab 2**32
29151 @item   @code{System.Address_Size}       @tab 32      @tab 64
29152 @end multitable
29153
29154 @noindent
29155 If you need to refer to the specific
29156 memory size of a 32-bit implementation, instead of the
29157 actual memory size, use @code{System.Short_Memory_Size}
29158 rather than @code{System.Memory_Size}.
29159 Similarly, references to @code{System.Address_Size} may need
29160 to be replaced by @code{System.Short_Address'Size}.
29161 The program @command{gnatfind} may be useful for locating
29162 references to the above constants, so that you can verify that they
29163 are still correct.
29164
29165 @node Interfacing with C
29166 @subsubsection Interfacing with C
29167
29168 @noindent
29169 In order to minimize the impact of the transition to 64-bit addresses on
29170 legacy programs, some fundamental types in the @code{Interfaces.C}
29171 package hierarchy continue to be represented in 32 bits.
29172 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
29173 This eases integration with the default HP C layout choices, for example
29174 as found in the system routines in @code{DECC$SHR.EXE}.
29175 Because of this implementation choice, the type fully compatible with
29176 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
29177 Depending on the context the compiler will issue a
29178 warning or an error when type @code{Address} is used, alerting the user to a
29179 potential problem. Otherwise 32-bit programs that use
29180 @code{Interfaces.C} should normally not require code modifications
29181
29182 The other issue arising with C interfacing concerns pragma @code{Convention}.
29183 For VMS 64-bit systems, there is an issue of the appropriate default size
29184 of C convention pointers in the absence of an explicit size clause. The HP
29185 C compiler can choose either 32 or 64 bits depending on compiler options.
29186 GNAT chooses 32-bits rather than 64-bits in the default case where no size
29187 clause is given. This proves a better choice for porting 32-bit legacy
29188 applications. In order to have a 64-bit representation, it is necessary to
29189 specify a size representation clause. For example:
29190
29191 @smallexample @c ada
29192 type int_star is access Interfaces.C.int;
29193 pragma Convention(C, int_star);
29194 for int_star'Size use 64;  -- Necessary to get 64 and not 32 bits
29195 @end smallexample
29196
29197 @node 32/64-bit descriptors
29198 @subsubsection 32/64-bit descriptors
29199
29200 @noindent
29201 By default, GNAT uses a 64-bit descriptor mechanism.  For an imported
29202 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
29203 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
29204 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
29205 @cindex @code{Short_Descriptor} mechanism for imported subprograms
29206
29207 If the configuration pragma @code{Short_Descriptors} is supplied, then
29208 all descriptors will be 32 bits.
29209 @cindex pragma @code{Short_Descriptors}
29210
29211 @node Experience with source compatibility
29212 @subsubsection Experience with source compatibility
29213
29214 @noindent
29215 The Security Server and STARLET on I64 provide an interesting ``test case''
29216 for source compatibility issues, since it is in such system code
29217 where assumptions about @code{Address} size might be expected to occur.
29218 Indeed, there were a small number of occasions in the Security Server
29219 file @file{jibdef.ads}
29220 where a representation clause for a record type specified
29221 32 bits for a component of type @code{Address}.
29222 All of these errors were detected by the compiler.
29223 The repair was obvious and immediate; to simply replace @code{Address} by
29224 @code{Short_Address}.
29225
29226 In the case of STARLET, there were several record types that should
29227 have had representation clauses but did not.  In these record types
29228 there was an implicit assumption that an @code{Address} value occupied
29229 32 bits.
29230 These compiled without error, but their usage resulted in run-time error
29231 returns from STARLET system calls.
29232 Future GNAT technology enhancements may include a tool that detects and flags
29233 these sorts of potential source code porting problems.
29234
29235 @c ****************************************
29236 @node Taking advantage of 64 bit addressing
29237 @subsection Taking advantage of 64-bit addressing
29238
29239 @menu
29240 * Making code 64 bit clean::
29241 * Allocating memory from the 64 bit storage pool::
29242 * Restrictions on use of 64 bit objects::
29243 * STARLET and other predefined libraries::
29244 @end menu
29245
29246 @node Making code 64 bit clean
29247 @subsubsection Making code 64-bit clean
29248
29249 @noindent
29250 In order to prevent problems that may occur when (parts of) a
29251 system start using memory outside the 32-bit address range,
29252 we recommend some additional guidelines:
29253
29254 @itemize @bullet
29255 @item
29256 For imported subprograms that take parameters of the
29257 type @code{System.Address}, ensure that these subprograms can
29258 indeed handle 64-bit addresses. If not, or when in doubt,
29259 change the subprogram declaration to specify
29260 @code{System.Short_Address} instead.
29261
29262 @item
29263 Resolve all warnings related to size mismatches in
29264 unchecked conversions. Failing to do so causes
29265 erroneous execution if the source object is outside
29266 the 32-bit address space.
29267
29268 @item
29269 (optional) Explicitly use the 32-bit storage pool
29270 for access types used in a 32-bit context, or use
29271 generic access types where possible
29272 (@pxref{Restrictions on use of 64 bit objects}).
29273 @end itemize
29274
29275 @noindent
29276 If these rules are followed, the compiler will automatically insert
29277 any necessary checks to ensure that no addresses or access values
29278 passed to 32-bit code ever refer to objects outside the 32-bit
29279 address range.
29280 Any attempt to do this will raise @code{Constraint_Error}.
29281
29282 @node Allocating memory from the 64 bit storage pool
29283 @subsubsection Allocating memory from the 64-bit storage pool
29284
29285 @noindent
29286 By default, all allocations -- for both pool-specific and general
29287 access types -- use the 64-bit storage pool.  To override
29288 this default, for an individual access type or globally, see
29289 @ref{Access types and 32/64-bit allocation}.
29290
29291 @node Restrictions on use of 64 bit objects
29292 @subsubsection Restrictions on use of 64-bit objects
29293
29294 @noindent
29295 Taking the address of an object allocated from a 64-bit storage pool,
29296 and then passing this address to a subprogram expecting
29297 @code{System.Short_Address},
29298 or assigning it to a variable of type @code{Short_Address}, will cause
29299 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
29300 (@pxref{Making code 64 bit clean}), or checks are suppressed,
29301 no exception is raised and execution
29302 will become erroneous.
29303
29304 @node STARLET and other predefined libraries
29305 @subsubsection STARLET and other predefined libraries
29306
29307 @noindent
29308 All code that comes as part of GNAT is 64-bit clean, but the
29309 restrictions given in @ref{Restrictions on use of 64 bit objects},
29310 still apply. Look at the package
29311 specs to see in which contexts objects allocated
29312 in 64-bit address space are acceptable.
29313
29314 @node Technical details
29315 @subsection Technical details
29316
29317 @noindent
29318 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
29319 Ada standard with respect to the type of @code{System.Address}. Previous
29320 versions of @value{EDITION} have defined this type as private and implemented it as a
29321 modular type.
29322
29323 In order to allow defining @code{System.Short_Address} as a proper subtype,
29324 and to match the implicit sign extension in parameter passing,
29325 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
29326 visible (i.e., non-private) integer type.
29327 Standard operations on the type, such as the binary operators ``+'', ``-'',
29328 etc., that take @code{Address} operands and return an @code{Address} result,
29329 have been hidden by declaring these
29330 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
29331 ambiguities that would otherwise result from overloading.
29332 (Note that, although @code{Address} is a visible integer type,
29333 good programming practice dictates against exploiting the type's
29334 integer properties such as literals, since this will compromise
29335 code portability.)
29336
29337 Defining @code{Address} as a visible integer type helps achieve
29338 maximum compatibility for existing Ada code,
29339 without sacrificing the capabilities of the 64-bit architecture.
29340 @end ifset
29341
29342 @c ************************************************
29343 @node Microsoft Windows Topics
29344 @appendix Microsoft Windows Topics
29345 @cindex Windows NT
29346 @cindex Windows 95
29347 @cindex Windows 98
29348
29349 @noindent
29350 This chapter describes topics that are specific to the Microsoft Windows
29351 platforms (NT, 2000, and XP Professional).
29352
29353 @menu
29354 @ifclear FSFEDITION
29355 * Installing from the Command Line::
29356 @end ifclear
29357 * Using GNAT on Windows::
29358 * Using a network installation of GNAT::
29359 * CONSOLE and WINDOWS subsystems::
29360 * Temporary Files::
29361 * Mixed-Language Programming on Windows::
29362 * Windows Calling Conventions::
29363 * Introduction to Dynamic Link Libraries (DLLs)::
29364 * Using DLLs with GNAT::
29365 * Building DLLs with GNAT Project files::
29366 * Building DLLs with GNAT::
29367 * Building DLLs with gnatdll::
29368 * GNAT and Windows Resources::
29369 * Debugging a DLL::
29370 * Setting Stack Size from gnatlink::
29371 * Setting Heap Size from gnatlink::
29372 @end menu
29373
29374 @ifclear FSFEDITION
29375 @node Installing from the Command Line
29376 @section Installing from the Command Line
29377 @cindex Batch installation
29378 @cindex Silent installation
29379 @cindex Unassisted installation
29380
29381 @noindent
29382 By default the @value{EDITION} installers display a GUI that prompts the user
29383 to enter installation path and similar information, and guide him through the
29384 installation process. It is also possible to perform silent installations
29385 using the command-line interface.
29386
29387 In order to install one of the @value{EDITION} installers from the command
29388 line you should pass parameter @code{/S} (and, optionally,
29389 @code{/D=<directory>}) as command-line arguments.
29390
29391 @ifset PROEDITION
29392 For example, for an unattended installation of
29393 @value{EDITION} 7.0.2 into the default directory
29394 @code{C:\GNATPRO\7.0.2} you would run:
29395
29396 @smallexample
29397 gnatpro-7.0.2-i686-pc-mingw32-bin.exe /S
29398 @end smallexample
29399
29400 To install into a custom directory, say, @code{C:\TOOLS\GNATPRO\7.0.2}:
29401
29402 @smallexample
29403 gnatpro-7.0.2-i686-pc-mingw32-bin /S /D=C:\TOOLS\GNATPRO\7.0.2
29404 @end smallexample
29405 @end ifset
29406
29407 @ifset GPLEDITION
29408 For example, for an unattended installation of
29409 @value{EDITION} 2012 into @code{C:\GNAT\2012}:
29410
29411 @smallexample
29412 gnat-gpl-2012-i686-pc-mingw32-bin /S /D=C:\GNAT\2012
29413 @end smallexample
29414 @end ifset
29415
29416 You can use the same syntax for all installers.
29417
29418 Note that unattended installations don't modify system path, nor create file
29419 associations, so such activities need to be done by hand.
29420 @end ifclear
29421
29422 @node Using GNAT on Windows
29423 @section Using GNAT on Windows
29424
29425 @noindent
29426 One of the strengths of the GNAT technology is that its tool set
29427 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
29428 @code{gdb} debugger, etc.) is used in the same way regardless of the
29429 platform.
29430
29431 On Windows this tool set is complemented by a number of Microsoft-specific
29432 tools that have been provided to facilitate interoperability with Windows
29433 when this is required. With these tools:
29434
29435 @itemize @bullet
29436
29437 @item
29438 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
29439 subsystems.
29440
29441 @item
29442 You can use any Dynamically Linked Library (DLL) in your Ada code (both
29443 relocatable and non-relocatable DLLs are supported).
29444
29445 @item
29446 You can build Ada DLLs for use in other applications. These applications
29447 can be written in a language other than Ada (e.g., C, C++, etc). Again both
29448 relocatable and non-relocatable Ada DLLs are supported.
29449
29450 @item
29451 You can include Windows resources in your Ada application.
29452
29453 @item
29454 You can use or create COM/DCOM objects.
29455 @end itemize
29456
29457 @noindent
29458 Immediately below are listed all known general GNAT-for-Windows restrictions.
29459 Other restrictions about specific features like Windows Resources and DLLs
29460 are listed in separate sections below.
29461
29462 @itemize @bullet
29463
29464 @item
29465 It is not possible to use @code{GetLastError} and @code{SetLastError}
29466 when tasking, protected records, or exceptions are used. In these
29467 cases, in order to implement Ada semantics, the GNAT run-time system
29468 calls certain Win32 routines that set the last error variable to 0 upon
29469 success. It should be possible to use @code{GetLastError} and
29470 @code{SetLastError} when tasking, protected record, and exception
29471 features are not used, but it is not guaranteed to work.
29472
29473 @item
29474 It is not possible to link against Microsoft C++ libraries except for
29475 import libraries. Interfacing must be done by the mean of DLLs.
29476
29477 @item
29478 It is possible to link against Microsoft C libraries. Yet the preferred
29479 solution is to use C/C++ compiler that comes with @value{EDITION}, since it
29480 doesn't require having two different development environments and makes the
29481 inter-language debugging experience smoother.
29482
29483 @item
29484 When the compilation environment is located on FAT32 drives, users may
29485 experience recompilations of the source files that have not changed if
29486 Daylight Saving Time (DST) state has changed since the last time files
29487 were compiled. NTFS drives do not have this problem.
29488
29489 @item
29490 No components of the GNAT toolset use any entries in the Windows
29491 registry. The only entries that can be created are file associations and
29492 PATH settings, provided the user has chosen to create them at installation
29493 time, as well as some minimal book-keeping information needed to correctly
29494 uninstall or integrate different GNAT products.
29495 @end itemize
29496
29497 @node Using a network installation of GNAT
29498 @section Using a network installation of GNAT
29499
29500 @noindent
29501 Make sure the system on which GNAT is installed is accessible from the
29502 current machine, i.e., the install location is shared over the network.
29503 Shared resources are accessed on Windows by means of UNC paths, which
29504 have the format @code{\\server\sharename\path}
29505
29506 In order to use such a network installation, simply add the UNC path of the
29507 @file{bin} directory of your GNAT installation in front of your PATH. For
29508 example, if GNAT is installed in @file{\GNAT} directory of a share location
29509 called @file{c-drive} on a machine @file{LOKI}, the following command will
29510 make it available:
29511
29512 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
29513
29514 Be aware that every compilation using the network installation results in the
29515 transfer of large amounts of data across the network and will likely cause
29516 serious performance penalty.
29517
29518 @node CONSOLE and WINDOWS subsystems
29519 @section CONSOLE and WINDOWS subsystems
29520 @cindex CONSOLE Subsystem
29521 @cindex WINDOWS Subsystem
29522 @cindex -mwindows
29523
29524 @noindent
29525 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
29526 (which is the default subsystem) will always create a console when
29527 launching the application. This is not something desirable when the
29528 application has a Windows GUI. To get rid of this console the
29529 application must be using the @code{WINDOWS} subsystem. To do so
29530 the @option{-mwindows} linker option must be specified.
29531
29532 @smallexample
29533 $ gnatmake winprog -largs -mwindows
29534 @end smallexample
29535
29536 @node Temporary Files
29537 @section Temporary Files
29538 @cindex Temporary files
29539
29540 @noindent
29541 It is possible to control where temporary files gets created by setting
29542 the @env{TMP} environment variable. The file will be created:
29543
29544 @itemize
29545 @item Under the directory pointed to by the @env{TMP} environment variable if
29546 this directory exists.
29547
29548 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
29549 set (or not pointing to a directory) and if this directory exists.
29550
29551 @item Under the current working directory otherwise.
29552 @end itemize
29553
29554 @noindent
29555 This allows you to determine exactly where the temporary
29556 file will be created. This is particularly useful in networked
29557 environments where you may not have write access to some
29558 directories.
29559
29560 @node Mixed-Language Programming on Windows
29561 @section Mixed-Language Programming on Windows
29562
29563 @noindent
29564 Developing pure Ada applications on Windows is no different than on
29565 other GNAT-supported platforms. However, when developing or porting an
29566 application that contains a mix of Ada and C/C++, the choice of your
29567 Windows C/C++ development environment conditions your overall
29568 interoperability strategy.
29569
29570 If you use @command{gcc} or Microsoft C to compile the non-Ada part of
29571 your application, there are no Windows-specific restrictions that
29572 affect the overall interoperability with your Ada code. If you do want
29573 to use the Microsoft tools for your C++ code, you have two choices:
29574
29575 @enumerate
29576 @item
29577 Encapsulate your C++ code in a DLL to be linked with your Ada
29578 application. In this case, use the Microsoft or whatever environment to
29579 build the DLL and use GNAT to build your executable
29580 (@pxref{Using DLLs with GNAT}).
29581
29582 @item
29583 Or you can encapsulate your Ada code in a DLL to be linked with the
29584 other part of your application. In this case, use GNAT to build the DLL
29585 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
29586 or whatever environment to build your executable.
29587 @end enumerate
29588
29589 In addition to the description about C main in
29590 @pxref{Mixed Language Programming} section, if the C main uses a
29591 stand-alone library it is required on x86-windows to
29592 setup the SEH context. For this the C main must looks like this:
29593
29594 @smallexample
29595 /* main.c */
29596 extern void adainit (void);
29597 extern void adafinal (void);
29598 extern void __gnat_initialize(void*);
29599 extern void call_to_ada (void);
29600
29601 int main (int argc, char *argv[])
29602 @{
29603   int SEH [2];
29604
29605   /* Initialize the SEH context */
29606   __gnat_initialize (&SEH);
29607
29608   adainit();
29609
29610   /* Then call Ada services in the stand-alone library */
29611
29612   call_to_ada();
29613
29614   adafinal();
29615 @}
29616 @end smallexample
29617
29618 Note that this is not needed on x86_64-windows where the Windows
29619 native SEH support is used.
29620
29621 @node Windows Calling Conventions
29622 @section Windows Calling Conventions
29623 @findex Stdcall
29624 @findex APIENTRY
29625
29626 This section pertain only to Win32. On Win64 there is a single native
29627 calling convention. All convention specifiers are ignored on this
29628 platform.
29629
29630 @menu
29631 * C Calling Convention::
29632 * Stdcall Calling Convention::
29633 * Win32 Calling Convention::
29634 * DLL Calling Convention::
29635 @end menu
29636
29637 @noindent
29638 When a subprogram @code{F} (caller) calls a subprogram @code{G}
29639 (callee), there are several ways to push @code{G}'s parameters on the
29640 stack and there are several possible scenarios to clean up the stack
29641 upon @code{G}'s return. A calling convention is an agreed upon software
29642 protocol whereby the responsibilities between the caller (@code{F}) and
29643 the callee (@code{G}) are clearly defined. Several calling conventions
29644 are available for Windows:
29645
29646 @itemize @bullet
29647 @item
29648 @code{C} (Microsoft defined)
29649
29650 @item
29651 @code{Stdcall} (Microsoft defined)
29652
29653 @item
29654 @code{Win32} (GNAT specific)
29655
29656 @item
29657 @code{DLL} (GNAT specific)
29658 @end itemize
29659
29660 @node C Calling Convention
29661 @subsection @code{C} Calling Convention
29662
29663 @noindent
29664 This is the default calling convention used when interfacing to C/C++
29665 routines compiled with either @command{gcc} or Microsoft Visual C++.
29666
29667 In the @code{C} calling convention subprogram parameters are pushed on the
29668 stack by the caller from right to left. The caller itself is in charge of
29669 cleaning up the stack after the call. In addition, the name of a routine
29670 with @code{C} calling convention is mangled by adding a leading underscore.
29671
29672 The name to use on the Ada side when importing (or exporting) a routine
29673 with @code{C} calling convention is the name of the routine. For
29674 instance the C function:
29675
29676 @smallexample
29677 int get_val (long);
29678 @end smallexample
29679
29680 @noindent
29681 should be imported from Ada as follows:
29682
29683 @smallexample @c ada
29684 @group
29685 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29686 pragma Import (C, Get_Val, External_Name => "get_val");
29687 @end group
29688 @end smallexample
29689
29690 @noindent
29691 Note that in this particular case the @code{External_Name} parameter could
29692 have been omitted since, when missing, this parameter is taken to be the
29693 name of the Ada entity in lower case. When the @code{Link_Name} parameter
29694 is missing, as in the above example, this parameter is set to be the
29695 @code{External_Name} with a leading underscore.
29696
29697 When importing a variable defined in C, you should always use the @code{C}
29698 calling convention unless the object containing the variable is part of a
29699 DLL (in which case you should use the @code{Stdcall} calling
29700 convention, @pxref{Stdcall Calling Convention}).
29701
29702 @node Stdcall Calling Convention
29703 @subsection @code{Stdcall} Calling Convention
29704
29705 @noindent
29706 This convention, which was the calling convention used for Pascal
29707 programs, is used by Microsoft for all the routines in the Win32 API for
29708 efficiency reasons. It must be used to import any routine for which this
29709 convention was specified.
29710
29711 In the @code{Stdcall} calling convention subprogram parameters are pushed
29712 on the stack by the caller from right to left. The callee (and not the
29713 caller) is in charge of cleaning the stack on routine exit. In addition,
29714 the name of a routine with @code{Stdcall} calling convention is mangled by
29715 adding a leading underscore (as for the @code{C} calling convention) and a
29716 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
29717 bytes) of the parameters passed to the routine.
29718
29719 The name to use on the Ada side when importing a C routine with a
29720 @code{Stdcall} calling convention is the name of the C routine. The leading
29721 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
29722 the compiler. For instance the Win32 function:
29723
29724 @smallexample
29725 @b{APIENTRY} int get_val (long);
29726 @end smallexample
29727
29728 @noindent
29729 should be imported from Ada as follows:
29730
29731 @smallexample @c ada
29732 @group
29733 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29734 pragma Import (Stdcall, Get_Val);
29735 --  On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
29736 @end group
29737 @end smallexample
29738
29739 @noindent
29740 As for the @code{C} calling convention, when the @code{External_Name}
29741 parameter is missing, it is taken to be the name of the Ada entity in lower
29742 case. If instead of writing the above import pragma you write:
29743
29744 @smallexample @c ada
29745 @group
29746 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29747 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
29748 @end group
29749 @end smallexample
29750
29751 @noindent
29752 then the imported routine is @code{_retrieve_val@@4}. However, if instead
29753 of specifying the @code{External_Name} parameter you specify the
29754 @code{Link_Name} as in the following example:
29755
29756 @smallexample @c ada
29757 @group
29758 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29759 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
29760 @end group
29761 @end smallexample
29762
29763 @noindent
29764 then the imported routine is @code{retrieve_val}, that is, there is no
29765 decoration at all. No leading underscore and no Stdcall suffix
29766 @code{@@}@code{@var{nn}}.
29767
29768 @noindent
29769 This is especially important as in some special cases a DLL's entry
29770 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
29771 name generated for a call has it.
29772
29773 @noindent
29774 It is also possible to import variables defined in a DLL by using an
29775 import pragma for a variable. As an example, if a DLL contains a
29776 variable defined as:
29777
29778 @smallexample
29779 int my_var;
29780 @end smallexample
29781
29782 @noindent
29783 then, to access this variable from Ada you should write:
29784
29785 @smallexample @c ada
29786 @group
29787 My_Var : Interfaces.C.int;
29788 pragma Import (Stdcall, My_Var);
29789 @end group
29790 @end smallexample
29791
29792 @noindent
29793 Note that to ease building cross-platform bindings this convention
29794 will be handled as a @code{C} calling convention on non-Windows platforms.
29795
29796 @node Win32 Calling Convention
29797 @subsection @code{Win32} Calling Convention
29798
29799 @noindent
29800 This convention, which is GNAT-specific is fully equivalent to the
29801 @code{Stdcall} calling convention described above.
29802
29803 @node DLL Calling Convention
29804 @subsection @code{DLL} Calling Convention
29805
29806 @noindent
29807 This convention, which is GNAT-specific is fully equivalent to the
29808 @code{Stdcall} calling convention described above.
29809
29810 @node Introduction to Dynamic Link Libraries (DLLs)
29811 @section Introduction to Dynamic Link Libraries (DLLs)
29812 @findex DLL
29813
29814 @noindent
29815 A Dynamically Linked Library (DLL) is a library that can be shared by
29816 several applications running under Windows. A DLL can contain any number of
29817 routines and variables.
29818
29819 One advantage of DLLs is that you can change and enhance them without
29820 forcing all the applications that depend on them to be relinked or
29821 recompiled. However, you should be aware than all calls to DLL routines are
29822 slower since, as you will understand below, such calls are indirect.
29823
29824 To illustrate the remainder of this section, suppose that an application
29825 wants to use the services of a DLL @file{API.dll}. To use the services
29826 provided by @file{API.dll} you must statically link against the DLL or
29827 an import library which contains a jump table with an entry for each
29828 routine and variable exported by the DLL. In the Microsoft world this
29829 import library is called @file{API.lib}. When using GNAT this import
29830 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
29831 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
29832
29833 After you have linked your application with the DLL or the import library
29834 and you run your application, here is what happens:
29835
29836 @enumerate
29837 @item
29838 Your application is loaded into memory.
29839
29840 @item
29841 The DLL @file{API.dll} is mapped into the address space of your
29842 application. This means that:
29843
29844 @itemize @bullet
29845 @item
29846 The DLL will use the stack of the calling thread.
29847
29848 @item
29849 The DLL will use the virtual address space of the calling process.
29850
29851 @item
29852 The DLL will allocate memory from the virtual address space of the calling
29853 process.
29854
29855 @item
29856 Handles (pointers) can be safely exchanged between routines in the DLL
29857 routines and routines in the application using the DLL.
29858 @end itemize
29859
29860 @item
29861 The entries in the jump table (from the import library @file{libAPI.dll.a}
29862 or @file{API.lib} or automatically created when linking against a DLL)
29863 which is part of your application are initialized with the addresses
29864 of the routines and variables in @file{API.dll}.
29865
29866 @item
29867 If present in @file{API.dll}, routines @code{DllMain} or
29868 @code{DllMainCRTStartup} are invoked. These routines typically contain
29869 the initialization code needed for the well-being of the routines and
29870 variables exported by the DLL.
29871 @end enumerate
29872
29873 @noindent
29874 There is an additional point which is worth mentioning. In the Windows
29875 world there are two kind of DLLs: relocatable and non-relocatable
29876 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
29877 in the target application address space. If the addresses of two
29878 non-relocatable DLLs overlap and these happen to be used by the same
29879 application, a conflict will occur and the application will run
29880 incorrectly. Hence, when possible, it is always preferable to use and
29881 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
29882 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
29883 User's Guide) removes the debugging symbols from the DLL but the DLL can
29884 still be relocated.
29885
29886 As a side note, an interesting difference between Microsoft DLLs and
29887 Unix shared libraries, is the fact that on most Unix systems all public
29888 routines are exported by default in a Unix shared library, while under
29889 Windows it is possible (but not required) to list exported routines in
29890 a definition file (@pxref{The Definition File}).
29891
29892 @node Using DLLs with GNAT
29893 @section Using DLLs with GNAT
29894
29895 @menu
29896 * Creating an Ada Spec for the DLL Services::
29897 * Creating an Import Library::
29898 @end menu
29899
29900 @noindent
29901 To use the services of a DLL, say @file{API.dll}, in your Ada application
29902 you must have:
29903
29904 @enumerate
29905 @item
29906 The Ada spec for the routines and/or variables you want to access in
29907 @file{API.dll}. If not available this Ada spec must be built from the C/C++
29908 header files provided with the DLL.
29909
29910 @item
29911 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
29912 mentioned an import library is a statically linked library containing the
29913 import table which will be filled at load time to point to the actual
29914 @file{API.dll} routines. Sometimes you don't have an import library for the
29915 DLL you want to use. The following sections will explain how to build
29916 one. Note that this is optional.
29917
29918 @item
29919 The actual DLL, @file{API.dll}.
29920 @end enumerate
29921
29922 @noindent
29923 Once you have all the above, to compile an Ada application that uses the
29924 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
29925 you simply issue the command
29926
29927 @smallexample
29928 $ gnatmake my_ada_app -largs -lAPI
29929 @end smallexample
29930
29931 @noindent
29932 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
29933 tells the GNAT linker to look for an import library. The linker will
29934 look for a library name in this specific order:
29935
29936 @enumerate
29937 @item @file{libAPI.dll.a}
29938 @item @file{API.dll.a}
29939 @item @file{libAPI.a}
29940 @item @file{API.lib}
29941 @item @file{libAPI.dll}
29942 @item @file{API.dll}
29943 @end enumerate
29944
29945 The first three are the GNU style import libraries. The third is the
29946 Microsoft style import libraries. The last two are the actual DLL names.
29947
29948 Note that if the Ada package spec for @file{API.dll} contains the
29949 following pragma
29950
29951 @smallexample @c ada
29952 pragma Linker_Options ("-lAPI");
29953 @end smallexample
29954
29955 @noindent
29956 you do not have to add @option{-largs -lAPI} at the end of the
29957 @command{gnatmake} command.
29958
29959 If any one of the items above is missing you will have to create it
29960 yourself. The following sections explain how to do so using as an
29961 example a fictitious DLL called @file{API.dll}.
29962
29963 @node Creating an Ada Spec for the DLL Services
29964 @subsection Creating an Ada Spec for the DLL Services
29965
29966 @noindent
29967 A DLL typically comes with a C/C++ header file which provides the
29968 definitions of the routines and variables exported by the DLL. The Ada
29969 equivalent of this header file is a package spec that contains definitions
29970 for the imported entities. If the DLL you intend to use does not come with
29971 an Ada spec you have to generate one such spec yourself. For example if
29972 the header file of @file{API.dll} is a file @file{api.h} containing the
29973 following two definitions:
29974
29975 @smallexample
29976 @group
29977 @cartouche
29978 int some_var;
29979 int get (char *);
29980 @end cartouche
29981 @end group
29982 @end smallexample
29983
29984 @noindent
29985 then the equivalent Ada spec could be:
29986
29987 @smallexample @c ada
29988 @group
29989 @cartouche
29990 with Interfaces.C.Strings;
29991 package API is
29992    use Interfaces;
29993
29994    Some_Var : C.int;
29995    function Get (Str : C.Strings.Chars_Ptr) return C.int;
29996
29997 private
29998    pragma Import (C, Get);
29999    pragma Import (DLL, Some_Var);
30000 end API;
30001 @end cartouche
30002 @end group
30003 @end smallexample
30004
30005 @node Creating an Import Library
30006 @subsection Creating an Import Library
30007 @cindex Import library
30008
30009 @menu
30010 * The Definition File::
30011 * GNAT-Style Import Library::
30012 * Microsoft-Style Import Library::
30013 @end menu
30014
30015 @noindent
30016 If a Microsoft-style import library @file{API.lib} or a GNAT-style
30017 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
30018 with @file{API.dll} you can skip this section. You can also skip this
30019 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
30020 as in this case it is possible to link directly against the
30021 DLL. Otherwise read on.
30022
30023 @node The Definition File
30024 @subsubsection The Definition File
30025 @cindex Definition file
30026 @findex .def
30027
30028 @noindent
30029 As previously mentioned, and unlike Unix systems, the list of symbols
30030 that are exported from a DLL must be provided explicitly in Windows.
30031 The main goal of a definition file is precisely that: list the symbols
30032 exported by a DLL. A definition file (usually a file with a @code{.def}
30033 suffix) has the following structure:
30034
30035 @smallexample
30036 @group
30037 @cartouche
30038 @r{[}LIBRARY @var{name}@r{]}
30039 @r{[}DESCRIPTION @var{string}@r{]}
30040 EXPORTS
30041    @var{symbol1}
30042    @var{symbol2}
30043    @dots{}
30044 @end cartouche
30045 @end group
30046 @end smallexample
30047
30048 @table @code
30049 @item LIBRARY @var{name}
30050 This section, which is optional, gives the name of the DLL.
30051
30052 @item DESCRIPTION @var{string}
30053 This section, which is optional, gives a description string that will be
30054 embedded in the import library.
30055
30056 @item EXPORTS
30057 This section gives the list of exported symbols (procedures, functions or
30058 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
30059 section of @file{API.def} looks like:
30060
30061 @smallexample
30062 @group
30063 @cartouche
30064 EXPORTS
30065    some_var
30066    get
30067 @end cartouche
30068 @end group
30069 @end smallexample
30070 @end table
30071
30072 @noindent
30073 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
30074 (@pxref{Windows Calling Conventions}) for a Stdcall
30075 calling convention function in the exported symbols list.
30076
30077 @noindent
30078 There can actually be other sections in a definition file, but these
30079 sections are not relevant to the discussion at hand.
30080
30081 @node GNAT-Style Import Library
30082 @subsubsection GNAT-Style Import Library
30083
30084 @noindent
30085 To create a static import library from @file{API.dll} with the GNAT tools
30086 you should proceed as follows:
30087
30088 @enumerate
30089 @item
30090 Create the definition file @file{API.def} (@pxref{The Definition File}).
30091 For that use the @code{dll2def} tool as follows:
30092
30093 @smallexample
30094 $ dll2def API.dll > API.def
30095 @end smallexample
30096
30097 @noindent
30098 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
30099 to standard output the list of entry points in the DLL. Note that if
30100 some routines in the DLL have the @code{Stdcall} convention
30101 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
30102 suffix then you'll have to edit @file{api.def} to add it, and specify
30103 @option{-k} to @command{gnatdll} when creating the import library.
30104
30105 @noindent
30106 Here are some hints to find the right @code{@@}@var{nn} suffix.
30107
30108 @enumerate
30109 @item
30110 If you have the Microsoft import library (.lib), it is possible to get
30111 the right symbols by using Microsoft @code{dumpbin} tool (see the
30112 corresponding Microsoft documentation for further details).
30113
30114 @smallexample
30115 $ dumpbin /exports api.lib
30116 @end smallexample
30117
30118 @item
30119 If you have a message about a missing symbol at link time the compiler
30120 tells you what symbol is expected. You just have to go back to the
30121 definition file and add the right suffix.
30122 @end enumerate
30123
30124 @item
30125 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
30126 (@pxref{Using gnatdll}) as follows:
30127
30128 @smallexample
30129 $ gnatdll -e API.def -d API.dll
30130 @end smallexample
30131
30132 @noindent
30133 @code{gnatdll} takes as input a definition file @file{API.def} and the
30134 name of the DLL containing the services listed in the definition file
30135 @file{API.dll}. The name of the static import library generated is
30136 computed from the name of the definition file as follows: if the
30137 definition file name is @var{xyz}@code{.def}, the import library name will
30138 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
30139 @option{-e} could have been removed because the name of the definition
30140 file (before the ``@code{.def}'' suffix) is the same as the name of the
30141 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
30142 @end enumerate
30143
30144 @node Microsoft-Style Import Library
30145 @subsubsection Microsoft-Style Import Library
30146
30147 @noindent
30148 With GNAT you can either use a GNAT-style or Microsoft-style import
30149 library. A Microsoft import library is needed only if you plan to make an
30150 Ada DLL available to applications developed with Microsoft
30151 tools (@pxref{Mixed-Language Programming on Windows}).
30152
30153 To create a Microsoft-style import library for @file{API.dll} you
30154 should proceed as follows:
30155
30156 @enumerate
30157 @item
30158 Create the definition file @file{API.def} from the DLL. For this use either
30159 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
30160 tool (see the corresponding Microsoft documentation for further details).
30161
30162 @item
30163 Build the actual import library using Microsoft's @code{lib} utility:
30164
30165 @smallexample
30166 $ lib -machine:IX86 -def:API.def -out:API.lib
30167 @end smallexample
30168
30169 @noindent
30170 If you use the above command the definition file @file{API.def} must
30171 contain a line giving the name of the DLL:
30172
30173 @smallexample
30174 LIBRARY      "API"
30175 @end smallexample
30176
30177 @noindent
30178 See the Microsoft documentation for further details about the usage of
30179 @code{lib}.
30180 @end enumerate
30181
30182 @node Building DLLs with GNAT Project files
30183 @section Building DLLs with GNAT Project files
30184 @cindex DLLs, building
30185
30186 @noindent
30187 There is nothing specific to Windows in the build process.
30188 @pxref{Library Projects}.
30189
30190 @noindent
30191 Due to a system limitation, it is not possible under Windows to create threads
30192 when inside the @code{DllMain} routine which is used for auto-initialization
30193 of shared libraries, so it is not possible to have library level tasks in SALs.
30194
30195 @node Building DLLs with GNAT
30196 @section Building DLLs with GNAT
30197 @cindex DLLs, building
30198
30199 @noindent
30200 This section explain how to build DLLs using the GNAT built-in DLL
30201 support. With the following procedure it is straight forward to build
30202 and use DLLs with GNAT.
30203
30204 @enumerate
30205
30206 @item building object files
30207
30208 The first step is to build all objects files that are to be included
30209 into the DLL. This is done by using the standard @command{gnatmake} tool.
30210
30211 @item building the DLL
30212
30213 To build the DLL you must use @command{gcc}'s @option{-shared} and
30214 @option{-shared-libgcc} options. It is quite simple to use this method:
30215
30216 @smallexample
30217 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
30218 @end smallexample
30219
30220 It is important to note that in this case all symbols found in the
30221 object files are automatically exported. It is possible to restrict
30222 the set of symbols to export by passing to @command{gcc} a definition
30223 file, @pxref{The Definition File}. For example:
30224
30225 @smallexample
30226 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
30227 @end smallexample
30228
30229 If you use a definition file you must export the elaboration procedures
30230 for every package that required one. Elaboration procedures are named
30231 using the package name followed by "_E".
30232
30233 @item preparing DLL to be used
30234
30235 For the DLL to be used by client programs the bodies must be hidden
30236 from it and the .ali set with read-only attribute. This is very important
30237 otherwise GNAT will recompile all packages and will not actually use
30238 the code in the DLL. For example:
30239
30240 @smallexample
30241 $ mkdir apilib
30242 $ copy *.ads *.ali api.dll apilib
30243 $ attrib +R apilib\*.ali
30244 @end smallexample
30245
30246 @end enumerate
30247
30248 At this point it is possible to use the DLL by directly linking
30249 against it. Note that you must use the GNAT shared runtime when using
30250 GNAT shared libraries. This is achieved by using @option{-shared} binder's
30251 option.
30252
30253 @smallexample
30254 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
30255 @end smallexample
30256
30257 @node Building DLLs with gnatdll
30258 @section Building DLLs with gnatdll
30259 @cindex DLLs, building
30260
30261 @menu
30262 * Limitations When Using Ada DLLs from Ada::
30263 * Exporting Ada Entities::
30264 * Ada DLLs and Elaboration::
30265 * Ada DLLs and Finalization::
30266 * Creating a Spec for Ada DLLs::
30267 * Creating the Definition File::
30268 * Using gnatdll::
30269 @end menu
30270
30271 @noindent
30272 Note that it is preferred to use GNAT Project files
30273 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
30274 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
30275
30276 This section explains how to build DLLs containing Ada code using
30277 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
30278 remainder of this section.
30279
30280 The steps required to build an Ada DLL that is to be used by Ada as well as
30281 non-Ada applications are as follows:
30282
30283 @enumerate
30284 @item
30285 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
30286 @code{Stdcall} calling convention to avoid any Ada name mangling for the
30287 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
30288 skip this step if you plan to use the Ada DLL only from Ada applications.
30289
30290 @item
30291 Your Ada code must export an initialization routine which calls the routine
30292 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
30293 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
30294 routine exported by the Ada DLL must be invoked by the clients of the DLL
30295 to initialize the DLL.
30296
30297 @item
30298 When useful, the DLL should also export a finalization routine which calls
30299 routine @code{adafinal} generated by @command{gnatbind} to perform the
30300 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
30301 The finalization routine exported by the Ada DLL must be invoked by the
30302 clients of the DLL when the DLL services are no further needed.
30303
30304 @item
30305 You must provide a spec for the services exported by the Ada DLL in each
30306 of the programming languages to which you plan to make the DLL available.
30307
30308 @item
30309 You must provide a definition file listing the exported entities
30310 (@pxref{The Definition File}).
30311
30312 @item
30313 Finally you must use @code{gnatdll} to produce the DLL and the import
30314 library (@pxref{Using gnatdll}).
30315 @end enumerate
30316
30317 @noindent
30318 Note that a relocatable DLL stripped using the @code{strip}
30319 binutils tool will not be relocatable anymore. To build a DLL without
30320 debug information pass @code{-largs -s} to @code{gnatdll}. This
30321 restriction does not apply to a DLL built using a Library Project.
30322 @pxref{Library Projects}.
30323
30324 @node Limitations When Using Ada DLLs from Ada
30325 @subsection Limitations When Using Ada DLLs from Ada
30326
30327 @noindent
30328 When using Ada DLLs from Ada applications there is a limitation users
30329 should be aware of. Because on Windows the GNAT run time is not in a DLL of
30330 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
30331 each Ada DLL includes the services of the GNAT run time that are necessary
30332 to the Ada code inside the DLL. As a result, when an Ada program uses an
30333 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
30334 one in the main program.
30335
30336 It is therefore not possible to exchange GNAT run-time objects between the
30337 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
30338 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
30339 types, etc.
30340
30341 It is completely safe to exchange plain elementary, array or record types,
30342 Windows object handles, etc.
30343
30344 @node Exporting Ada Entities
30345 @subsection Exporting Ada Entities
30346 @cindex Export table
30347
30348 @noindent
30349 Building a DLL is a way to encapsulate a set of services usable from any
30350 application. As a result, the Ada entities exported by a DLL should be
30351 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
30352 any Ada name mangling. As an example here is an Ada package
30353 @code{API}, spec and body, exporting two procedures, a function, and a
30354 variable:
30355
30356 @smallexample @c ada
30357 @group
30358 @cartouche
30359 with Interfaces.C; use Interfaces;
30360 package API is
30361    Count : C.int := 0;
30362    function Factorial (Val : C.int) return C.int;
30363
30364    procedure Initialize_API;
30365    procedure Finalize_API;
30366    --  Initialization & Finalization routines. More in the next section.
30367 private
30368    pragma Export (C, Initialize_API);
30369    pragma Export (C, Finalize_API);
30370    pragma Export (C, Count);
30371    pragma Export (C, Factorial);
30372 end API;
30373 @end cartouche
30374 @end group
30375 @end smallexample
30376
30377 @smallexample @c ada
30378 @group
30379 @cartouche
30380 package body API is
30381    function Factorial (Val : C.int) return C.int is
30382       Fact : C.int := 1;
30383    begin
30384       Count := Count + 1;
30385       for K in 1 .. Val loop
30386          Fact := Fact * K;
30387       end loop;
30388       return Fact;
30389    end Factorial;
30390
30391    procedure Initialize_API is
30392       procedure Adainit;
30393       pragma Import (C, Adainit);
30394    begin
30395       Adainit;
30396    end Initialize_API;
30397
30398    procedure Finalize_API is
30399       procedure Adafinal;
30400       pragma Import (C, Adafinal);
30401    begin
30402       Adafinal;
30403    end Finalize_API;
30404 end API;
30405 @end cartouche
30406 @end group
30407 @end smallexample
30408
30409 @noindent
30410 If the Ada DLL you are building will only be used by Ada applications
30411 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
30412 convention. As an example, the previous package could be written as
30413 follows:
30414
30415 @smallexample @c ada
30416 @group
30417 @cartouche
30418 package API is
30419    Count : Integer := 0;
30420    function Factorial (Val : Integer) return Integer;
30421
30422    procedure Initialize_API;
30423    procedure Finalize_API;
30424    --  Initialization and Finalization routines.
30425 end API;
30426 @end cartouche
30427 @end group
30428 @end smallexample
30429
30430 @smallexample @c ada
30431 @group
30432 @cartouche
30433 package body API is
30434    function Factorial (Val : Integer) return Integer is
30435       Fact : Integer := 1;
30436    begin
30437       Count := Count + 1;
30438       for K in 1 .. Val loop
30439          Fact := Fact * K;
30440       end loop;
30441       return Fact;
30442    end Factorial;
30443
30444    @dots{}
30445    --  The remainder of this package body is unchanged.
30446 end API;
30447 @end cartouche
30448 @end group
30449 @end smallexample
30450
30451 @noindent
30452 Note that if you do not export the Ada entities with a @code{C} or
30453 @code{Stdcall} convention you will have to provide the mangled Ada names
30454 in the definition file of the Ada DLL
30455 (@pxref{Creating the Definition File}).
30456
30457 @node Ada DLLs and Elaboration
30458 @subsection Ada DLLs and Elaboration
30459 @cindex DLLs and elaboration
30460
30461 @noindent
30462 The DLL that you are building contains your Ada code as well as all the
30463 routines in the Ada library that are needed by it. The first thing a
30464 user of your DLL must do is elaborate the Ada code
30465 (@pxref{Elaboration Order Handling in GNAT}).
30466
30467 To achieve this you must export an initialization routine
30468 (@code{Initialize_API} in the previous example), which must be invoked
30469 before using any of the DLL services. This elaboration routine must call
30470 the Ada elaboration routine @code{adainit} generated by the GNAT binder
30471 (@pxref{Binding with Non-Ada Main Programs}). See the body of
30472 @code{Initialize_Api} for an example. Note that the GNAT binder is
30473 automatically invoked during the DLL build process by the @code{gnatdll}
30474 tool (@pxref{Using gnatdll}).
30475
30476 When a DLL is loaded, Windows systematically invokes a routine called
30477 @code{DllMain}. It would therefore be possible to call @code{adainit}
30478 directly from @code{DllMain} without having to provide an explicit
30479 initialization routine. Unfortunately, it is not possible to call
30480 @code{adainit} from the @code{DllMain} if your program has library level
30481 tasks because access to the @code{DllMain} entry point is serialized by
30482 the system (that is, only a single thread can execute ``through'' it at a
30483 time), which means that the GNAT run time will deadlock waiting for the
30484 newly created task to complete its initialization.
30485
30486 @node Ada DLLs and Finalization
30487 @subsection Ada DLLs and Finalization
30488 @cindex DLLs and finalization
30489
30490 @noindent
30491 When the services of an Ada DLL are no longer needed, the client code should
30492 invoke the DLL finalization routine, if available. The DLL finalization
30493 routine is in charge of releasing all resources acquired by the DLL. In the
30494 case of the Ada code contained in the DLL, this is achieved by calling
30495 routine @code{adafinal} generated by the GNAT binder
30496 (@pxref{Binding with Non-Ada Main Programs}).
30497 See the body of @code{Finalize_Api} for an
30498 example. As already pointed out the GNAT binder is automatically invoked
30499 during the DLL build process by the @code{gnatdll} tool
30500 (@pxref{Using gnatdll}).
30501
30502 @node Creating a Spec for Ada DLLs
30503 @subsection Creating a Spec for Ada DLLs
30504
30505 @noindent
30506 To use the services exported by the Ada DLL from another programming
30507 language (e.g.@: C), you have to translate the specs of the exported Ada
30508 entities in that language. For instance in the case of @code{API.dll},
30509 the corresponding C header file could look like:
30510
30511 @smallexample
30512 @group
30513 @cartouche
30514 extern int *_imp__count;
30515 #define count (*_imp__count)
30516 int factorial (int);
30517 @end cartouche
30518 @end group
30519 @end smallexample
30520
30521 @noindent
30522 It is important to understand that when building an Ada DLL to be used by
30523 other Ada applications, you need two different specs for the packages
30524 contained in the DLL: one for building the DLL and the other for using
30525 the DLL. This is because the @code{DLL} calling convention is needed to
30526 use a variable defined in a DLL, but when building the DLL, the variable
30527 must have either the @code{Ada} or @code{C} calling convention. As an
30528 example consider a DLL comprising the following package @code{API}:
30529
30530 @smallexample @c ada
30531 @group
30532 @cartouche
30533 package API is
30534    Count : Integer := 0;
30535    @dots{}
30536    --  Remainder of the package omitted.
30537 end API;
30538 @end cartouche
30539 @end group
30540 @end smallexample
30541
30542 @noindent
30543 After producing a DLL containing package @code{API}, the spec that
30544 must be used to import @code{API.Count} from Ada code outside of the
30545 DLL is:
30546
30547 @smallexample @c ada
30548 @group
30549 @cartouche
30550 package API is
30551    Count : Integer;
30552    pragma Import (DLL, Count);
30553 end API;
30554 @end cartouche
30555 @end group
30556 @end smallexample
30557
30558 @node Creating the Definition File
30559 @subsection Creating the Definition File
30560
30561 @noindent
30562 The definition file is the last file needed to build the DLL. It lists
30563 the exported symbols. As an example, the definition file for a DLL
30564 containing only package @code{API} (where all the entities are exported
30565 with a @code{C} calling convention) is:
30566
30567 @smallexample
30568 @group
30569 @cartouche
30570 EXPORTS
30571     count
30572     factorial
30573     finalize_api
30574     initialize_api
30575 @end cartouche
30576 @end group
30577 @end smallexample
30578
30579 @noindent
30580 If the @code{C} calling convention is missing from package @code{API},
30581 then the definition file contains the mangled Ada names of the above
30582 entities, which in this case are:
30583
30584 @smallexample
30585 @group
30586 @cartouche
30587 EXPORTS
30588     api__count
30589     api__factorial
30590     api__finalize_api
30591     api__initialize_api
30592 @end cartouche
30593 @end group
30594 @end smallexample
30595
30596 @node Using gnatdll
30597 @subsection Using @code{gnatdll}
30598 @findex gnatdll
30599
30600 @menu
30601 * gnatdll Example::
30602 * gnatdll behind the Scenes::
30603 * Using dlltool::
30604 @end menu
30605
30606 @noindent
30607 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
30608 and non-Ada sources that make up your DLL have been compiled.
30609 @code{gnatdll} is actually in charge of two distinct tasks: build the
30610 static import library for the DLL and the actual DLL. The form of the
30611 @code{gnatdll} command is
30612
30613 @smallexample
30614 @cartouche
30615 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
30616 @c Expanding @ovar macro inline (explanation in macro def comments)
30617 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
30618 @end cartouche
30619 @end smallexample
30620
30621 @noindent
30622 where @var{list-of-files} is a list of ALI and object files. The object
30623 file list must be the exact list of objects corresponding to the non-Ada
30624 sources whose services are to be included in the DLL. The ALI file list
30625 must be the exact list of ALI files for the corresponding Ada sources
30626 whose services are to be included in the DLL. If @var{list-of-files} is
30627 missing, only the static import library is generated.
30628
30629 @noindent
30630 You may specify any of the following switches to @code{gnatdll}:
30631
30632 @table @code
30633 @c @item -a@ovar{address}
30634 @c Expanding @ovar macro inline (explanation in macro def comments)
30635 @item -a@r{[}@var{address}@r{]}
30636 @cindex @option{-a} (@code{gnatdll})
30637 Build a non-relocatable DLL at @var{address}. If @var{address} is not
30638 specified the default address @var{0x11000000} will be used. By default,
30639 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
30640 advise the reader to build relocatable DLL.
30641
30642 @item -b @var{address}
30643 @cindex @option{-b} (@code{gnatdll})
30644 Set the relocatable DLL base address. By default the address is
30645 @code{0x11000000}.
30646
30647 @item -bargs @var{opts}
30648 @cindex @option{-bargs} (@code{gnatdll})
30649 Binder options. Pass @var{opts} to the binder.
30650
30651 @item -d @var{dllfile}
30652 @cindex @option{-d} (@code{gnatdll})
30653 @var{dllfile} is the name of the DLL. This switch must be present for
30654 @code{gnatdll} to do anything. The name of the generated import library is
30655 obtained algorithmically from @var{dllfile} as shown in the following
30656 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
30657 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
30658 by option @option{-e}) is obtained algorithmically from @var{dllfile}
30659 as shown in the following example:
30660 if @var{dllfile} is @code{xyz.dll}, the definition
30661 file used is @code{xyz.def}.
30662
30663 @item -e @var{deffile}
30664 @cindex @option{-e} (@code{gnatdll})
30665 @var{deffile} is the name of the definition file.
30666
30667 @item -g
30668 @cindex @option{-g} (@code{gnatdll})
30669 Generate debugging information. This information is stored in the object
30670 file and copied from there to the final DLL file by the linker,
30671 where it can be read by the debugger. You must use the
30672 @option{-g} switch if you plan on using the debugger or the symbolic
30673 stack traceback.
30674
30675 @item -h
30676 @cindex @option{-h} (@code{gnatdll})
30677 Help mode. Displays @code{gnatdll} switch usage information.
30678
30679 @item -Idir
30680 @cindex @option{-I} (@code{gnatdll})
30681 Direct @code{gnatdll} to search the @var{dir} directory for source and
30682 object files needed to build the DLL.
30683 (@pxref{Search Paths and the Run-Time Library (RTL)}).
30684
30685 @item -k
30686 @cindex @option{-k} (@code{gnatdll})
30687 Removes the @code{@@}@var{nn} suffix from the import library's exported
30688 names, but keeps them for the link names. You must specify this
30689 option if you want to use a @code{Stdcall} function in a DLL for which
30690 the @code{@@}@var{nn} suffix has been removed. This is the case for most
30691 of the Windows NT DLL for example. This option has no effect when
30692 @option{-n} option is specified.
30693
30694 @item -l @var{file}
30695 @cindex @option{-l} (@code{gnatdll})
30696 The list of ALI and object files used to build the DLL are listed in
30697 @var{file}, instead of being given in the command line. Each line in
30698 @var{file} contains the name of an ALI or object file.
30699
30700 @item -n
30701 @cindex @option{-n} (@code{gnatdll})
30702 No Import. Do not create the import library.
30703
30704 @item -q
30705 @cindex @option{-q} (@code{gnatdll})
30706 Quiet mode. Do not display unnecessary messages.
30707
30708 @item -v
30709 @cindex @option{-v} (@code{gnatdll})
30710 Verbose mode. Display extra information.
30711
30712 @item -largs @var{opts}
30713 @cindex @option{-largs} (@code{gnatdll})
30714 Linker options. Pass @var{opts} to the linker.
30715 @end table
30716
30717 @node gnatdll Example
30718 @subsubsection @code{gnatdll} Example
30719
30720 @noindent
30721 As an example the command to build a relocatable DLL from @file{api.adb}
30722 once @file{api.adb} has been compiled and @file{api.def} created is
30723
30724 @smallexample
30725 $ gnatdll -d api.dll api.ali
30726 @end smallexample
30727
30728 @noindent
30729 The above command creates two files: @file{libapi.dll.a} (the import
30730 library) and @file{api.dll} (the actual DLL). If you want to create
30731 only the DLL, just type:
30732
30733 @smallexample
30734 $ gnatdll -d api.dll -n api.ali
30735 @end smallexample
30736
30737 @noindent
30738 Alternatively if you want to create just the import library, type:
30739
30740 @smallexample
30741 $ gnatdll -d api.dll
30742 @end smallexample
30743
30744 @node gnatdll behind the Scenes
30745 @subsubsection @code{gnatdll} behind the Scenes
30746
30747 @noindent
30748 This section details the steps involved in creating a DLL. @code{gnatdll}
30749 does these steps for you. Unless you are interested in understanding what
30750 goes on behind the scenes, you should skip this section.
30751
30752 We use the previous example of a DLL containing the Ada package @code{API},
30753 to illustrate the steps necessary to build a DLL. The starting point is a
30754 set of objects that will make up the DLL and the corresponding ALI
30755 files. In the case of this example this means that @file{api.o} and
30756 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
30757 the following:
30758
30759 @enumerate
30760 @item
30761 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
30762 the information necessary to generate relocation information for the
30763 DLL.
30764
30765 @smallexample
30766 @group
30767 $ gnatbind -n api
30768 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
30769 @end group
30770 @end smallexample
30771
30772 @noindent
30773 In addition to the base file, the @command{gnatlink} command generates an
30774 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
30775 asks @command{gnatlink} to generate the routines @code{DllMain} and
30776 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
30777 is loaded into memory.
30778
30779 @item
30780 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
30781 export table (@file{api.exp}). The export table contains the relocation
30782 information in a form which can be used during the final link to ensure
30783 that the Windows loader is able to place the DLL anywhere in memory.
30784
30785 @smallexample
30786 @group
30787 $ dlltool --dllname api.dll --def api.def --base-file api.base \
30788           --output-exp api.exp
30789 @end group
30790 @end smallexample
30791
30792 @item
30793 @code{gnatdll} builds the base file using the new export table. Note that
30794 @command{gnatbind} must be called once again since the binder generated file
30795 has been deleted during the previous call to @command{gnatlink}.
30796
30797 @smallexample
30798 @group
30799 $ gnatbind -n api
30800 $ gnatlink api -o api.jnk api.exp -mdll
30801       -Wl,--base-file,api.base
30802 @end group
30803 @end smallexample
30804
30805 @item
30806 @code{gnatdll} builds the new export table using the new base file and
30807 generates the DLL import library @file{libAPI.dll.a}.
30808
30809 @smallexample
30810 @group
30811 $ dlltool --dllname api.dll --def api.def --base-file api.base \
30812           --output-exp api.exp --output-lib libAPI.a
30813 @end group
30814 @end smallexample
30815
30816 @item
30817 Finally @code{gnatdll} builds the relocatable DLL using the final export
30818 table.
30819
30820 @smallexample
30821 @group
30822 $ gnatbind -n api
30823 $ gnatlink api api.exp -o api.dll -mdll
30824 @end group
30825 @end smallexample
30826 @end enumerate
30827
30828 @node Using dlltool
30829 @subsubsection Using @code{dlltool}
30830
30831 @noindent
30832 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
30833 DLLs and static import libraries. This section summarizes the most
30834 common @code{dlltool} switches. The form of the @code{dlltool} command
30835 is
30836
30837 @smallexample
30838 @c $ dlltool @ovar{switches}
30839 @c Expanding @ovar macro inline (explanation in macro def comments)
30840 $ dlltool @r{[}@var{switches}@r{]}
30841 @end smallexample
30842
30843 @noindent
30844 @code{dlltool} switches include:
30845
30846 @table @option
30847 @item --base-file @var{basefile}
30848 @cindex @option{--base-file} (@command{dlltool})
30849 Read the base file @var{basefile} generated by the linker. This switch
30850 is used to create a relocatable DLL.
30851
30852 @item --def @var{deffile}
30853 @cindex @option{--def} (@command{dlltool})
30854 Read the definition file.
30855
30856 @item --dllname @var{name}
30857 @cindex @option{--dllname} (@command{dlltool})
30858 Gives the name of the DLL. This switch is used to embed the name of the
30859 DLL in the static import library generated by @code{dlltool} with switch
30860 @option{--output-lib}.
30861
30862 @item -k
30863 @cindex @option{-k} (@command{dlltool})
30864 Kill @code{@@}@var{nn} from exported names
30865 (@pxref{Windows Calling Conventions}
30866 for a discussion about @code{Stdcall}-style symbols.
30867
30868 @item --help
30869 @cindex @option{--help} (@command{dlltool})
30870 Prints the @code{dlltool} switches with a concise description.
30871
30872 @item --output-exp @var{exportfile}
30873 @cindex @option{--output-exp} (@command{dlltool})
30874 Generate an export file @var{exportfile}. The export file contains the
30875 export table (list of symbols in the DLL) and is used to create the DLL.
30876
30877 @item --output-lib @var{libfile}
30878 @cindex @option{--output-lib} (@command{dlltool})
30879 Generate a static import library @var{libfile}.
30880
30881 @item -v
30882 @cindex @option{-v} (@command{dlltool})
30883 Verbose mode.
30884
30885 @item --as @var{assembler-name}
30886 @cindex @option{--as} (@command{dlltool})
30887 Use @var{assembler-name} as the assembler. The default is @code{as}.
30888 @end table
30889
30890 @node GNAT and Windows Resources
30891 @section GNAT and Windows Resources
30892 @cindex Resources, windows
30893
30894 @menu
30895 * Building Resources::
30896 * Compiling Resources::
30897 * Using Resources::
30898 @end menu
30899
30900 @noindent
30901 Resources are an easy way to add Windows specific objects to your
30902 application. The objects that can be added as resources include:
30903
30904 @itemize @bullet
30905 @item menus
30906
30907 @item accelerators
30908
30909 @item dialog boxes
30910
30911 @item string tables
30912
30913 @item bitmaps
30914
30915 @item cursors
30916
30917 @item icons
30918
30919 @item fonts
30920
30921 @item version information
30922 @end itemize
30923
30924 For example, a version information resource can be defined as follow and
30925 embedded into an executable or DLL:
30926
30927 A version information resource can be used to embed information into an
30928 executable or a DLL. These information can be viewed using the file properties
30929 from the Windows Explorer. Here is an example of a version information
30930 resource:
30931
30932 @smallexample
30933 @group
30934 1 VERSIONINFO
30935 FILEVERSION     1,0,0,0
30936 PRODUCTVERSION  1,0,0,0
30937 BEGIN
30938   BLOCK "StringFileInfo"
30939   BEGIN
30940     BLOCK "080904E4"
30941     BEGIN
30942       VALUE "CompanyName", "My Company Name"
30943       VALUE "FileDescription", "My application"
30944       VALUE "FileVersion", "1.0"
30945       VALUE "InternalName", "my_app"
30946       VALUE "LegalCopyright", "My Name"
30947       VALUE "OriginalFilename", "my_app.exe"
30948       VALUE "ProductName", "My App"
30949       VALUE "ProductVersion", "1.0"
30950     END
30951   END
30952
30953   BLOCK "VarFileInfo"
30954   BEGIN
30955     VALUE "Translation", 0x809, 1252
30956   END
30957 END
30958 @end group
30959 @end smallexample
30960
30961 The value @code{0809} (langID) is for the U.K English language and
30962 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
30963 multilingual.
30964
30965 @noindent
30966 This section explains how to build, compile and use resources. Note that this
30967 section does not cover all resource objects, for a complete description see
30968 the corresponding Microsoft documentation.
30969
30970 @node Building Resources
30971 @subsection Building Resources
30972 @cindex Resources, building
30973
30974 @noindent
30975 A resource file is an ASCII file. By convention resource files have an
30976 @file{.rc} extension.
30977 The easiest way to build a resource file is to use Microsoft tools
30978 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
30979 @code{dlgedit.exe} to build dialogs.
30980 It is always possible to build an @file{.rc} file yourself by writing a
30981 resource script.
30982
30983 It is not our objective to explain how to write a resource file. A
30984 complete description of the resource script language can be found in the
30985 Microsoft documentation.
30986
30987 @node Compiling Resources
30988 @subsection Compiling Resources
30989 @findex rc
30990 @findex windres
30991 @cindex Resources, compiling
30992
30993 @noindent
30994 This section describes how to build a GNAT-compatible (COFF) object file
30995 containing the resources. This is done using the Resource Compiler
30996 @code{windres} as follows:
30997
30998 @smallexample
30999 $ windres -i myres.rc -o myres.o
31000 @end smallexample
31001
31002 @noindent
31003 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
31004 file. You can specify an alternate preprocessor (usually named
31005 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
31006 parameter. A list of all possible options may be obtained by entering
31007 the command @code{windres} @option{--help}.
31008
31009 It is also possible to use the Microsoft resource compiler @code{rc.exe}
31010 to produce a @file{.res} file (binary resource file). See the
31011 corresponding Microsoft documentation for further details. In this case
31012 you need to use @code{windres} to translate the @file{.res} file to a
31013 GNAT-compatible object file as follows:
31014
31015 @smallexample
31016 $ windres -i myres.res -o myres.o
31017 @end smallexample
31018
31019 @node Using Resources
31020 @subsection Using Resources
31021 @cindex Resources, using
31022
31023 @noindent
31024 To include the resource file in your program just add the
31025 GNAT-compatible object file for the resource(s) to the linker
31026 arguments. With @command{gnatmake} this is done by using the @option{-largs}
31027 option:
31028
31029 @smallexample
31030 $ gnatmake myprog -largs myres.o
31031 @end smallexample
31032
31033 @node Debugging a DLL
31034 @section Debugging a DLL
31035 @cindex DLL debugging
31036
31037 @menu
31038 * Program and DLL Both Built with GCC/GNAT::
31039 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
31040 @end menu
31041
31042 @noindent
31043 Debugging a DLL is similar to debugging a standard program. But
31044 we have to deal with two different executable parts: the DLL and the
31045 program that uses it. We have the following four possibilities:
31046
31047 @enumerate 1
31048 @item
31049 The program and the DLL are built with @code{GCC/GNAT}.
31050 @item
31051 The program is built with foreign tools and the DLL is built with
31052 @code{GCC/GNAT}.
31053 @item
31054 The program is built with @code{GCC/GNAT} and the DLL is built with
31055 foreign tools.
31056 @end enumerate
31057
31058 @noindent
31059 In this section we address only cases one and two above.
31060 There is no point in trying to debug
31061 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
31062 information in it. To do so you must use a debugger compatible with the
31063 tools suite used to build the DLL.
31064
31065 @node Program and DLL Both Built with GCC/GNAT
31066 @subsection Program and DLL Both Built with GCC/GNAT
31067
31068 @noindent
31069 This is the simplest case. Both the DLL and the program have @code{GDB}
31070 compatible debugging information. It is then possible to break anywhere in
31071 the process. Let's suppose here that the main procedure is named
31072 @code{ada_main} and that in the DLL there is an entry point named
31073 @code{ada_dll}.
31074
31075 @noindent
31076 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
31077 program must have been built with the debugging information (see GNAT -g
31078 switch). Here are the step-by-step instructions for debugging it:
31079
31080 @enumerate 1
31081 @item Launch @code{GDB} on the main program.
31082
31083 @smallexample
31084 $ gdb -nw ada_main
31085 @end smallexample
31086
31087 @item Start the program and stop at the beginning of the main procedure
31088
31089 @smallexample
31090 (gdb) start
31091 @end smallexample
31092
31093 @noindent
31094 This step is required to be able to set a breakpoint inside the DLL. As long
31095 as the program is not run, the DLL is not loaded. This has the
31096 consequence that the DLL debugging information is also not loaded, so it is not
31097 possible to set a breakpoint in the DLL.
31098
31099 @item Set a breakpoint inside the DLL
31100
31101 @smallexample
31102 (gdb) break ada_dll
31103 (gdb) cont
31104 @end smallexample
31105
31106 @end enumerate
31107
31108 @noindent
31109 At this stage a breakpoint is set inside the DLL. From there on
31110 you can use the standard approach to debug the whole program
31111 (@pxref{Running and Debugging Ada Programs}).
31112
31113 @ignore
31114 @c This used to work, probably because the DLLs were non-relocatable
31115 @c keep this section around until the problem is sorted out.
31116
31117 To break on the @code{DllMain} routine it is not possible to follow
31118 the procedure above. At the time the program stop on @code{ada_main}
31119 the @code{DllMain} routine as already been called. Either you can use
31120 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
31121
31122 @enumerate 1
31123 @item Launch @code{GDB} on the main program.
31124
31125 @smallexample
31126 $ gdb ada_main
31127 @end smallexample
31128
31129 @item Load DLL symbols
31130
31131 @smallexample
31132 (gdb) add-sym api.dll
31133 @end smallexample
31134
31135 @item Set a breakpoint inside the DLL
31136
31137 @smallexample
31138 (gdb) break ada_dll.adb:45
31139 @end smallexample
31140
31141 Note that at this point it is not possible to break using the routine symbol
31142 directly as the program is not yet running. The solution is to break
31143 on the proper line (break in @file{ada_dll.adb} line 45).
31144
31145 @item Start the program
31146
31147 @smallexample
31148 (gdb) run
31149 @end smallexample
31150
31151 @end enumerate
31152 @end ignore
31153
31154 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
31155 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
31156
31157 @menu
31158 * Debugging the DLL Directly::
31159 * Attaching to a Running Process::
31160 @end menu
31161
31162 @noindent
31163 In this case things are slightly more complex because it is not possible to
31164 start the main program and then break at the beginning to load the DLL and the
31165 associated DLL debugging information. It is not possible to break at the
31166 beginning of the program because there is no @code{GDB} debugging information,
31167 and therefore there is no direct way of getting initial control. This
31168 section addresses this issue by describing some methods that can be used
31169 to break somewhere in the DLL to debug it.
31170
31171 @noindent
31172 First suppose that the main procedure is named @code{main} (this is for
31173 example some C code built with Microsoft Visual C) and that there is a
31174 DLL named @code{test.dll} containing an Ada entry point named
31175 @code{ada_dll}.
31176
31177 @noindent
31178 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
31179 been built with debugging information (see GNAT -g option).
31180
31181 @node Debugging the DLL Directly
31182 @subsubsection Debugging the DLL Directly
31183
31184 @enumerate 1
31185 @item
31186 Find out the executable starting address
31187
31188 @smallexample
31189 $ objdump --file-header main.exe
31190 @end smallexample
31191
31192 The starting address is reported on the last line. For example:
31193
31194 @smallexample
31195 main.exe:     file format pei-i386
31196 architecture: i386, flags 0x0000010a:
31197 EXEC_P, HAS_DEBUG, D_PAGED
31198 start address 0x00401010
31199 @end smallexample
31200
31201 @item
31202 Launch the debugger on the executable.
31203
31204 @smallexample
31205 $ gdb main.exe
31206 @end smallexample
31207
31208 @item
31209 Set a breakpoint at the starting address, and launch the program.
31210
31211 @smallexample
31212 $ (gdb) break *0x00401010
31213 $ (gdb) run
31214 @end smallexample
31215
31216 The program will stop at the given address.
31217
31218 @item
31219 Set a breakpoint on a DLL subroutine.
31220
31221 @smallexample
31222 (gdb) break ada_dll.adb:45
31223 @end smallexample
31224
31225 Or if you want to break using a symbol on the DLL, you need first to
31226 select the Ada language (language used by the DLL).
31227
31228 @smallexample
31229 (gdb) set language ada
31230 (gdb) break ada_dll
31231 @end smallexample
31232
31233 @item
31234 Continue the program.
31235
31236 @smallexample
31237 (gdb) cont
31238 @end smallexample
31239
31240 @noindent
31241 This will run the program until it reaches the breakpoint that has been
31242 set. From that point you can use the standard way to debug a program
31243 as described in (@pxref{Running and Debugging Ada Programs}).
31244
31245 @end enumerate
31246
31247 @noindent
31248 It is also possible to debug the DLL by attaching to a running process.
31249
31250 @node Attaching to a Running Process
31251 @subsubsection Attaching to a Running Process
31252 @cindex DLL debugging, attach to process
31253
31254 @noindent
31255 With @code{GDB} it is always possible to debug a running process by
31256 attaching to it. It is possible to debug a DLL this way. The limitation
31257 of this approach is that the DLL must run long enough to perform the
31258 attach operation. It may be useful for instance to insert a time wasting
31259 loop in the code of the DLL to meet this criterion.
31260
31261 @enumerate 1
31262
31263 @item Launch the main program @file{main.exe}.
31264
31265 @smallexample
31266 $ main
31267 @end smallexample
31268
31269 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
31270 that the process PID for @file{main.exe} is 208.
31271
31272 @item Launch gdb.
31273
31274 @smallexample
31275 $ gdb
31276 @end smallexample
31277
31278 @item Attach to the running process to be debugged.
31279
31280 @smallexample
31281 (gdb) attach 208
31282 @end smallexample
31283
31284 @item Load the process debugging information.
31285
31286 @smallexample
31287 (gdb) symbol-file main.exe
31288 @end smallexample
31289
31290 @item Break somewhere in the DLL.
31291
31292 @smallexample
31293 (gdb) break ada_dll
31294 @end smallexample
31295
31296 @item Continue process execution.
31297
31298 @smallexample
31299 (gdb) cont
31300 @end smallexample
31301
31302 @end enumerate
31303
31304 @noindent
31305 This last step will resume the process execution, and stop at
31306 the breakpoint we have set. From there you can use the standard
31307 approach to debug a program as described in
31308 (@pxref{Running and Debugging Ada Programs}).
31309
31310 @node Setting Stack Size from gnatlink
31311 @section Setting Stack Size from @command{gnatlink}
31312
31313 @noindent
31314 It is possible to specify the program stack size at link time. On modern
31315 versions of Windows, starting with XP, this is mostly useful to set the size of
31316 the main stack (environment task). The other task stacks are set with pragma
31317 Storage_Size or with the @command{gnatbind -d} command.
31318
31319 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
31320 reserve size of individual tasks, the link-time stack size applies to all
31321 tasks, and pragma Storage_Size has no effect.
31322 In particular, Stack Overflow checks are made against this
31323 link-time specified size.
31324
31325 This setting can be done with
31326 @command{gnatlink} using either:
31327
31328 @itemize @bullet
31329
31330 @item using @option{-Xlinker} linker option
31331
31332 @smallexample
31333 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
31334 @end smallexample
31335
31336 This sets the stack reserve size to 0x10000 bytes and the stack commit
31337 size to 0x1000 bytes.
31338
31339 @item using @option{-Wl} linker option
31340
31341 @smallexample
31342 $ gnatlink hello -Wl,--stack=0x1000000
31343 @end smallexample
31344
31345 This sets the stack reserve size to 0x1000000 bytes. Note that with
31346 @option{-Wl} option it is not possible to set the stack commit size
31347 because the coma is a separator for this option.
31348
31349 @end itemize
31350
31351 @node Setting Heap Size from gnatlink
31352 @section Setting Heap Size from @command{gnatlink}
31353
31354 @noindent
31355 Under Windows systems, it is possible to specify the program heap size from
31356 @command{gnatlink} using either:
31357
31358 @itemize @bullet
31359
31360 @item using @option{-Xlinker} linker option
31361
31362 @smallexample
31363 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
31364 @end smallexample
31365
31366 This sets the heap reserve size to 0x10000 bytes and the heap commit
31367 size to 0x1000 bytes.
31368
31369 @item using @option{-Wl} linker option
31370
31371 @smallexample
31372 $ gnatlink hello -Wl,--heap=0x1000000
31373 @end smallexample
31374
31375 This sets the heap reserve size to 0x1000000 bytes. Note that with
31376 @option{-Wl} option it is not possible to set the heap commit size
31377 because the coma is a separator for this option.
31378
31379 @end itemize
31380
31381 @node Mac OS Topics
31382 @appendix Mac OS Topics
31383 @cindex OS X
31384
31385 @noindent
31386 This chapter describes topics that are specific to Apple's OS X
31387 platform.
31388
31389 @menu
31390 * Codesigning the Debugger::
31391 @end menu
31392
31393 @node Codesigning the Debugger
31394 @section Codesigning the Debugger
31395
31396 @noindent
31397 The Darwin Kernel requires the debugger to have special permissions
31398 before it is allowed to control other processes. These permissions
31399 are granted by codesigning the GDB executable. Without these
31400 permissions, the debugger will report error messages such as:
31401
31402 @smallexample
31403 Starting program: /x/y/foo
31404 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
31405  (please check gdb is codesigned - see taskgated(8))
31406 @end smallexample
31407
31408 Codesigning requires a certificate.  The following procedure explains
31409 how to create one:
31410
31411 @itemize @bullet
31412 @item Start the Keychain Access application (in
31413 /Applications/Utilities/Keychain Access.app)
31414
31415 @item Select the Keychain Access -> Certificate Assistant ->
31416 Create a Certificate... menu
31417
31418 @item Then:
31419
31420 @itemize @bullet
31421 @item Choose a name for the new certificate (this procedure will use
31422 "gdb-cert" as an example)
31423
31424 @item Set "Identity Type" to "Self Signed Root"
31425
31426 @item Set "Certificate Type" to "Code Signing"
31427
31428 @item Activate the "Let me override defaults" option
31429
31430 @end itemize
31431
31432 @item Click several times on "Continue" until the "Specify a Location
31433 For The Certificate" screen appears, then set "Keychain" to "System"
31434
31435 @item Click on "Continue" until the certificate is created
31436
31437 @item Finally, in the view, double-click on the new certificate,
31438 and set "When using this certificate" to "Always Trust"
31439
31440 @item Exit the Keychain Access application and restart the computer
31441 (this is unfortunately required)
31442
31443 @end itemize
31444
31445 Once a certificate has been created, the debugger can be codesigned
31446 as follow. In a Terminal, run the following command...
31447
31448 @smallexample
31449 codesign -f -s  "gdb-cert"  <gnat_install_prefix>/bin/gdb
31450 @end smallexample
31451
31452 ... where "gdb-cert" should be replaced by the actual certificate
31453 name chosen above, and <gnat_install_prefix> should be replaced by
31454 the location where you installed GNAT.
31455
31456 @c **********************************
31457 @c * GNU Free Documentation License *
31458 @c **********************************
31459 @include fdl.texi
31460 @c GNU Free Documentation License
31461
31462 @node Index
31463 @unnumbered Index
31464
31465 @printindex cp
31466
31467 @contents
31468 @c Put table of contents at end, otherwise it precedes the "title page" in
31469 @c the .txt version
31470 @c Edit the pdf file to move the contents to the beginning, after the title
31471 @c page
31472
31473 @bye