[multiple changes]
[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-2014, Free Software Foundation, Inc. o
11 @c o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
13
14 @setfilename gnat_ugn.info
15
16 @copying
17 Copyright @copyright{} 1995-2014 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 -fdump-xref
3575 @cindex @option{-fdump-xref} (@command{gcc})
3576 Generates cross reference information in GLI files for C and C++ sources.
3577 The GLI files have the same syntax as the ALI files for Ada, and can be used
3578 for source navigation in IDEs and on the command line using e.g. gnatxref
3579 and the @option{--ext=gli} switch.
3580
3581 @item -flto@r{[}=n@r{]}
3582 @cindex @option{-flto} (@command{gcc})
3583 Enables Link Time Optimization. This switch must be used in conjunction
3584 with the traditional @option{-Ox} switches and instructs the compiler to
3585 defer most optimizations until the link stage. The advantage of this
3586 approach is that the compiler can do a whole-program analysis and choose
3587 the best interprocedural optimization strategy based on a complete view
3588 of the program, instead of a fragmentary view with the usual approach.
3589 This can also speed up the compilation of huge programs and reduce the
3590 size of the final executable, compared with a per-unit compilation with
3591 full inlining across modules enabled with the @option{-gnatn2} switch.
3592 The drawback of this approach is that it may require much more memory.
3593 The switch, as well as the accompanying @option{-Ox} switches, must be
3594 specified both for the compilation and the link phases.
3595 If the @var{n} parameter is specified, the optimization and final code
3596 generation at link time are executed using @var{n} parallel jobs by
3597 means of an installed @command{make} program.
3598
3599 @item -fno-inline
3600 @cindex @option{-fno-inline} (@command{gcc})
3601 Suppresses all inlining, even if other optimization or inlining
3602 switches are set. This includes suppression of inlining that
3603 results from the use of the pragma @code{Inline_Always}.
3604 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3605 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3606 effects if this switch is present. Note that inlining can also
3607 be suppressed on a finer-grained basis with pragma @code{No_Inline}.
3608
3609 @item -fno-inline-functions
3610 @cindex @option{-fno-inline-functions} (@command{gcc})
3611 Suppresses automatic inlining of subprograms, which is enabled
3612 if @option{-O3} is used.
3613
3614 @item -fno-inline-small-functions
3615 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3616 Suppresses automatic inlining of small subprograms, which is enabled
3617 if @option{-O2} is used.
3618
3619 @item -fno-inline-functions-called-once
3620 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3621 Suppresses inlining of subprograms local to the unit and called once
3622 from within it, which is enabled if @option{-O1} is used.
3623
3624 @item -fno-ivopts
3625 @cindex @option{-fno-ivopts} (@command{gcc})
3626 Suppresses high-level loop induction variable optimizations, which are
3627 enabled if @option{-O1} is used. These optimizations are generally
3628 profitable but, for some specific cases of loops with numerous uses
3629 of the iteration variable that follow a common pattern, they may end
3630 up destroying the regularity that could be exploited at a lower level
3631 and thus producing inferior code.
3632
3633 @item -fno-strict-aliasing
3634 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3635 Causes the compiler to avoid assumptions regarding non-aliasing
3636 of objects of different types. See
3637 @ref{Optimization and Strict Aliasing} for details.
3638
3639 @item -fstack-check
3640 @cindex @option{-fstack-check} (@command{gcc})
3641 Activates stack checking.
3642 See @ref{Stack Overflow Checking} for details.
3643
3644 @item -fstack-usage
3645 @cindex @option{-fstack-usage} (@command{gcc})
3646 Makes the compiler output stack usage information for the program, on a
3647 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
3648
3649 @item ^-g^/DEBUG^
3650 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3651 Generate debugging information. This information is stored in the object
3652 file and copied from there to the final executable file by the linker,
3653 where it can be read by the debugger. You must use the
3654 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3655
3656 @item -gnat83
3657 @cindex @option{-gnat83} (@command{gcc})
3658 Enforce Ada 83 restrictions.
3659
3660 @item -gnat95
3661 @cindex @option{-gnat95} (@command{gcc})
3662 Enforce Ada 95 restrictions.
3663
3664 @item -gnat05
3665 @cindex @option{-gnat05} (@command{gcc})
3666 Allow full Ada 2005 features.
3667
3668 @item -gnat2005
3669 @cindex @option{-gnat2005} (@command{gcc})
3670 Allow full Ada 2005 features (same as @option{-gnat05})
3671
3672 @item -gnat12
3673 @cindex @option{-gnat12} (@command{gcc})
3674
3675 @item -gnat2012
3676 @cindex @option{-gnat2012} (@command{gcc})
3677 Allow full Ada 2012 features (same as @option{-gnat12})
3678
3679 @item -gnata
3680 @cindex @option{-gnata} (@command{gcc})
3681 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3682 activated. Note that these pragmas can also be controlled using the
3683 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3684 It also activates pragmas @code{Check}, @code{Precondition}, and
3685 @code{Postcondition}. Note that these pragmas can also be controlled
3686 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
3687 also activates all assertions defined in the RM as aspects: preconditions,
3688 postconditions, type invariants and (sub)type predicates. In all Ada modes,
3689 corresponding pragmas for type invariants and (sub)type predicates are
3690 also activated.
3691
3692 @item -gnatA
3693 @cindex @option{-gnatA} (@command{gcc})
3694 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
3695 it will be ignored.
3696
3697 @item -gnatb
3698 @cindex @option{-gnatb} (@command{gcc})
3699 Generate brief messages to @file{stderr} even if verbose mode set.
3700
3701 @item -gnatB
3702 @cindex @option{-gnatB} (@command{gcc})
3703 Assume no invalid (bad) values except for 'Valid attribute use
3704 (@pxref{Validity Checking}).
3705
3706 @item -gnatc
3707 @cindex @option{-gnatc} (@command{gcc})
3708 Check syntax and semantics only (no code generation attempted). When the
3709 compiler is invoked by @command{gnatmake}, if the switch @option{-gnatc} is
3710 only given to the compiler (after @option{-cargs} or in package Compiler of
3711 the project file, @command{gnatmake} will fail because it will not find the
3712 object file after compilation. If @command{gnatmake} is called with
3713 @option{-gnatc} as a builder switch (before @option{-cargs} or in package
3714 Builder of the project file) then @command{gnatmake} will not fail because
3715 it will not look for the object files after compilation, and it will not try
3716 to build and link. This switch may not be given if a previous @code{-gnatR}
3717 switch has been given, since @code{-gnatR} requires that the code generator
3718 be called to complete determination of representation information.
3719
3720 @item -gnatC
3721 @cindex @option{-gnatC} (@command{gcc})
3722 Generate CodePeer information (no code generation attempted).
3723 This switch will generate an intermediate representation suitable for
3724 use by CodePeer (@file{.scil} files). This switch is not compatible with
3725 code generation (it will, among other things, disable some switches such
3726 as -gnatn, and enable others such as -gnata).
3727
3728 @item -gnatd
3729 @cindex @option{-gnatd} (@command{gcc})
3730 Specify debug options for the compiler. The string of characters after
3731 the @option{-gnatd} specify the specific debug options. The possible
3732 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3733 compiler source file @file{debug.adb} for details of the implemented
3734 debug options. Certain debug options are relevant to applications
3735 programmers, and these are documented at appropriate points in this
3736 users guide.
3737
3738 @ifclear vms
3739 @item -gnatD
3740 @cindex @option{-gnatD[nn]} (@command{gcc})
3741 @end ifclear
3742 @ifset vms
3743 @item /XDEBUG /LXDEBUG=nnn
3744 @end ifset
3745 Create expanded source files for source level debugging. This switch
3746 also suppress generation of cross-reference information
3747 (see @option{-gnatx}). Note that this switch is not allowed if a previous
3748 -gnatR switch has been given, since these two switches are not compatible.
3749
3750 @item ^-gnateA^/ALIASING_CHECK^
3751 @cindex @option{-gnateA} (@command{gcc})
3752 Check that there is no aliasing between two parameters of the same subprogram.
3753
3754 @item -gnatec=@var{path}
3755 @cindex @option{-gnatec} (@command{gcc})
3756 Specify a configuration pragma file
3757 @ifclear vms
3758 (the equal sign is optional)
3759 @end ifclear
3760 (@pxref{The Configuration Pragmas Files}).
3761
3762 @item ^-gnated^/DISABLE_ATOMIC_SYNCHRONIZATION^
3763 @cindex @option{-gnated} (@command{gcc})
3764 Disable atomic synchronization
3765
3766 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
3767 @cindex @option{-gnateD} (@command{gcc})
3768 Defines a symbol, associated with @var{value}, for preprocessing.
3769 (@pxref{Integrated Preprocessing}).
3770
3771 @item -gnateE
3772 @cindex @option{-gnateE} (@command{gcc})
3773 Generate extra information in exception messages. In particular, display
3774 extra column information and the value and range associated with index and
3775 range check failures, and extra column information for access checks.
3776 In cases where the compiler is able to determine at compile time that
3777 a check will fail, it gives a warning, and the extra information is not
3778 produced at run time.
3779
3780 @item -gnatef
3781 @cindex @option{-gnatef} (@command{gcc})
3782 Display full source path name in brief error messages.
3783
3784 @item -gnateF
3785 @cindex @option{-gnateF} (@command{gcc})
3786 Check for overflow on all floating-point operations, including those
3787 for unconstrained predefined types. See description of pragma
3788 @code{Check_Float_Overflow} in GNAT RM.
3789
3790 @item -gnateG
3791 @cindex @option{-gnateG} (@command{gcc})
3792 Save result of preprocessing in a text file.
3793
3794 @item -gnatei@var{nnn}
3795 @cindex @option{-gnatei} (@command{gcc})
3796 Set maximum number of instantiations during compilation of a single unit to
3797 @var{nnn}. This may be useful in increasing the default maximum of 8000 for
3798 the rare case when a single unit legitimately exceeds this limit.
3799
3800 @item -gnateI@var{nnn}
3801 @cindex @option{-gnateI} (@command{gcc})
3802 Indicates that the source is a multi-unit source and that the index of the
3803 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
3804 to be a valid index in the multi-unit source.
3805
3806 @item -gnatem=@var{path}
3807 @cindex @option{-gnatem} (@command{gcc})
3808 Specify a mapping file
3809 @ifclear vms
3810 (the equal sign is optional)
3811 @end ifclear
3812 (@pxref{Units to Sources Mapping Files}).
3813
3814 @item -gnatep=@var{file}
3815 @cindex @option{-gnatep} (@command{gcc})
3816 Specify a preprocessing data file
3817 @ifclear vms
3818 (the equal sign is optional)
3819 @end ifclear
3820 (@pxref{Integrated Preprocessing}).
3821
3822 @item -gnateP
3823 @cindex @option{-gnateP} (@command{gcc})
3824 Turn categorization dependency errors into warnings.
3825 Ada requires that units that WITH one another have compatible categories, for
3826 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
3827 these errors become warnings (which can be ignored, or suppressed in the usual
3828 manner). This can be useful in some specialized circumstances such as the
3829 temporary use of special test software.
3830
3831 @item -gnateS
3832 @cindex @option{-gnateS} (@command{gcc})
3833 Synonym of @option{-fdump-scos}, kept for backwards compatibility.
3834
3835 @item -gnatet=@var{path}
3836 @cindex @option{-gnatet=file} (@command{gcc})
3837 Generate target dependent information. The format of the output file is
3838 described in the section about switch @option{-gnateT}.
3839
3840 @item -gnateT=@var{path}
3841 @cindex @option{-gnateT} (@command{gcc})
3842 Read target dependent information, such as endianness or sizes and alignments
3843 of base type. If this switch is passed, the default target dependent
3844 information of the compiler is replaced by the one read from the input file.
3845 This is used by tools other than the compiler, e.g. to do
3846 semantic analysis of programs that will run on some other target than
3847 the machine on which the tool is run.
3848
3849 The following target dependent values should be defined,
3850 where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
3851 positive integer value, and fields marked with a question mark are
3852 boolean fields, where a value of 0 is False, and a value of 1 is True:
3853
3854 @smallexample
3855 Bits_BE : Nat; -- Bits stored big-endian?
3856 Bits_Per_Unit : Pos; -- Bits in a storage unit
3857 Bits_Per_Word : Pos; -- Bits in a word
3858 Bytes_BE : Nat; -- Bytes stored big-endian?
3859 Char_Size : Pos; -- Standard.Character'Size
3860 Double_Float_Alignment : Nat; -- Alignment of double float
3861 Double_Scalar_Alignment : Nat; -- Alignment of double length scalar
3862 Double_Size : Pos; -- Standard.Long_Float'Size
3863 Float_Size : Pos; -- Standard.Float'Size
3864 Float_Words_BE : Nat; -- Float words stored big-endian?
3865 Int_Size : Pos; -- Standard.Integer'Size
3866 Long_Double_Size : Pos; -- Standard.Long_Long_Float'Size
3867 Long_Long_Size : Pos; -- Standard.Long_Long_Integer'Size
3868 Long_Size : Pos; -- Standard.Long_Integer'Size
3869 Maximum_Alignment : Pos; -- Maximum permitted alignment
3870 Max_Unaligned_Field : Pos; -- Maximum size for unaligned bit field
3871 Pointer_Size : Pos; -- System.Address'Size
3872 Short_Size : Pos; -- Standard.Short_Integer'Size
3873 Strict_Alignment : Nat; -- Strict alignment?
3874 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
3875 Wchar_T_Size : Pos; -- Interfaces.C.wchar_t'Size
3876 Words_BE : Nat; -- Words stored big-endian?
3877 @end smallexample
3878
3879 The format of the input file is as follows. First come the values of
3880 the variables defined above, with one line per value:
3881
3882 @smallexample
3883 name value
3884 @end smallexample
3885
3886 where @code{name} is the name of the parameter, spelled out in full,
3887 and cased as in the above list, and @code{value} is an unsigned decimal
3888 integer. Two or more blanks separates the name from the value.
3889
3890 All the variables must be present, in alphabetical order (i.e. the
3891 same order as the list above).
3892
3893 Then there is a blank line to separate the two parts of the file. Then
3894 come the lines showing the floating-point types to be registered, with
3895 one line per registered mode:
3896
3897 @smallexample
3898 name digs float_rep size alignment
3899 @end smallexample
3900
3901 where @code{name} is the string name of the type (which can have
3902 single spaces embedded in the name (e.g. long double), @code{digs} is
3903 the number of digits for the floating-point type, @code{float_rep} is
3904 the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
3905 AAMP), @code{size} is the size in bits, @code{alignment} is the
3906 alignment in bits. The name is followed by at least two blanks, fields
3907 are separated by at least one blank, and a LF character immediately
3908 follows the alignment field.
3909
3910 Here is an example of target parametrization file:
3911
3912 @smallexample
3913 Bits_BE 0
3914 Bits_Per_Unit 8
3915 Bits_Per_Word 64
3916 Bytes_BE 0
3917 Char_Size 8
3918 Double_Float_Alignment 0
3919 Double_Scalar_Alignment 0
3920 Double_Size 64
3921 Float_Size 32
3922 Float_Words_BE 0
3923 Int_Size 64
3924 Long_Double_Size 128
3925 Long_Long_Size 64
3926 Long_Size 64
3927 Maximum_Alignment 16
3928 Max_Unaligned_Field 64
3929 Pointer_Size 64
3930 Short_Size 16
3931 Strict_Alignment 0
3932 System_Allocator_Alignment 16
3933 Wchar_T_Size 32
3934 Words_BE 0
3935
3936 float 15 I 64 64
3937 double 15 I 64 64
3938 long double 18 I 80 128
3939 TF 33 I 128 128
3940 @end smallexample
3941
3942 @item -gnateu
3943 @cindex @option{-gnateu} (@command{gcc})
3944 Ignore unrecognized validity, warning, and style switches that
3945 appear after this switch is given. This may be useful when
3946 compiling sources developed on a later version of the compiler
3947 with an earlier version. Of course the earlier version must
3948 support this switch.
3949
3950 @item ^-gnateV^/PARAMETER_VALIDITY_CHECK^
3951 @cindex @option{-gnateV} (@command{gcc})
3952 Check validity of subprogram parameters.
3953
3954 @item ^-gnateY^/IGNORE_SUPPRESS_SYLE_CHECK_PRAGMAS^
3955 @cindex @option{-gnateY} (@command{gcc})
3956 Ignore all STYLE_CHECKS pragmas. Full legality checks
3957 are still carried out, but the pragmas have no effect
3958 on what style checks are active. This allows all style
3959 checking options to be controlled from the command line.
3960
3961 @item -gnatE
3962 @cindex @option{-gnatE} (@command{gcc})
3963 Full dynamic elaboration checks.
3964
3965 @item -gnatf
3966 @cindex @option{-gnatf} (@command{gcc})
3967 Full errors. Multiple errors per line, all undefined references, do not
3968 attempt to suppress cascaded errors.
3969
3970 @item -gnatF
3971 @cindex @option{-gnatF} (@command{gcc})
3972 Externals names are folded to all uppercase.
3973
3974 @item ^-gnatg^/GNAT_INTERNAL^
3975 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
3976 Internal GNAT implementation mode. This should not be used for
3977 applications programs, it is intended only for use by the compiler
3978 and its run-time library. For documentation, see the GNAT sources.
3979 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
3980 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
3981 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
3982 so that all standard warnings and all standard style options are turned on.
3983 All warnings and style messages are treated as errors.
3984
3985 @ifclear vms
3986 @item -gnatG=nn
3987 @cindex @option{-gnatG[nn]} (@command{gcc})
3988 @end ifclear
3989 @ifset vms
3990 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
3991 @end ifset
3992 List generated expanded code in source form.
3993
3994 @item ^-gnath^/HELP^
3995 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3996 Output usage information. The output is written to @file{stdout}.
3997
3998 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3999 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4000 Identifier character set
4001 @ifclear vms
4002 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4003 @end ifclear
4004 For details of the possible selections for @var{c},
4005 see @ref{Character Set Control}.
4006
4007 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4008 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4009 Ignore representation clauses. When this switch is used,
4010 representation clauses are treated as comments. This is useful
4011 when initially porting code where you want to ignore rep clause
4012 problems, and also for compiling foreign code (particularly
4013 for use with ASIS). The representation clauses that are ignored
4014 are: enumeration_representation_clause, record_representation_clause,
4015 and attribute_definition_clause for the following attributes:
4016 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4017 Object_Size, Size, Small, Stream_Size, and Value_Size.
4018 Note that this option should be used only for compiling -- the
4019 code is likely to malfunction at run time.
4020
4021 @item -gnatjnn
4022 @cindex @option{-gnatjnn} (@command{gcc})
4023 Reformat error messages to fit on nn character lines
4024
4025 @item -gnatk=@var{n}
4026 @cindex @option{-gnatk} (@command{gcc})
4027 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4028
4029 @item -gnatl
4030 @cindex @option{-gnatl} (@command{gcc})
4031 Output full source listing with embedded error messages.
4032
4033 @item -gnatL
4034 @cindex @option{-gnatL} (@command{gcc})
4035 Used in conjunction with -gnatG or -gnatD to intersperse original
4036 source lines (as comment lines with line numbers) in the expanded
4037 source output.
4038
4039 @item -gnatm=@var{n}
4040 @cindex @option{-gnatm} (@command{gcc})
4041 Limit number of detected error or warning messages to @var{n}
4042 where @var{n} is in the range 1..999999. The default setting if
4043 no switch is given is 9999. If the number of warnings reaches this
4044 limit, then a message is output and further warnings are suppressed,
4045 but the compilation is continued. If the number of error messages
4046 reaches this limit, then a message is output and the compilation
4047 is abandoned. The equal sign here is optional. A value of zero
4048 means that no limit applies.
4049
4050 @item -gnatn[12]
4051 @cindex @option{-gnatn} (@command{gcc})
4052 Activate inlining for subprograms for which pragma @code{Inline} is
4053 specified. This inlining is performed by the GCC back-end. An optional
4054 digit sets the inlining level: 1 for moderate inlining across modules
4055 or 2 for full inlining across modules. If no inlining level is specified,
4056 the compiler will pick it based on the optimization level.
4057
4058 @item -gnatN
4059 @cindex @option{-gnatN} (@command{gcc})
4060 Activate front end inlining for subprograms for which
4061 pragma @code{Inline} is specified. This inlining is performed
4062 by the front end and will be visible in the
4063 @option{-gnatG} output.
4064
4065 When using a gcc-based back end (in practice this means using any version
4066 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4067 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4068 Historically front end inlining was more extensive than the gcc back end
4069 inlining, but that is no longer the case.
4070
4071 @item -gnato??
4072 @cindex @option{-gnato??} (@command{gcc})
4073 Set default mode for handling generation of code to avoid intermediate
4074 arithmetic overflow. Here `@code{??}' is two digits, a
4075 single digit, or nothing. Each digit is one of the digits `@code{1}'
4076 through `@code{3}':
4077
4078 @itemize @bullet
4079 @item @code{1}:
4080 all intermediate overflows checked against base type (@code{STRICT})
4081 @item @code{2}:
4082 minimize intermediate overflows (@code{MINIMIZED})
4083 @item @code{3}:
4084 eliminate intermediate overflows (@code{ELIMINATED})
4085 @end itemize
4086
4087 If only one digit appears then it applies to all
4088 cases; if two digits are given, then the first applies outside
4089 assertions, and the second within assertions.
4090
4091 If no digits follow the @option{-gnato}, then it is equivalent to
4092 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
4093 causing all intermediate overflows to be handled in strict mode.
4094
4095 This switch also causes arithmetic overflow checking to be performed
4096 (as though pragma @code{Unsuppress (Overflow_Mode)} has been specified.
4097
4098 The default if no option @option{-gnato} is given is that overflow handling
4099 is in @code{STRICT} mode (computations done using the base type), and that
4100 overflow checking is suppressed.
4101
4102 Note that division by zero is a separate check that is not
4103 controlled by this switch (division by zero checking is on by default).
4104
4105 See also @ref{Specifying the Desired Mode}.
4106
4107 @item -gnatp
4108 @cindex @option{-gnatp} (@command{gcc})
4109 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4110 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4111
4112 @item -gnat-p
4113 @cindex @option{-gnat-p} (@command{gcc})
4114 Cancel effect of previous @option{-gnatp} switch.
4115
4116 @item -gnatP
4117 @cindex @option{-gnatP} (@command{gcc})
4118 Enable polling. This is required on some systems (notably Windows NT) to
4119 obtain asynchronous abort and asynchronous transfer of control capability.
4120 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4121 details.
4122
4123 @item -gnatq
4124 @cindex @option{-gnatq} (@command{gcc})
4125 Don't quit. Try semantics, even if parse errors.
4126
4127 @item -gnatQ
4128 @cindex @option{-gnatQ} (@command{gcc})
4129 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4130
4131 @item -gnatr
4132 @cindex @option{-gnatr} (@command{gcc})
4133 Treat pragma Restrictions as Restriction_Warnings.
4134
4135 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4136 @cindex @option{-gnatR} (@command{gcc})
4137 Output representation information for declared types and objects.
4138 Note that this switch is not allowed if a previous @code{-gnatD} switch has
4139 been given, since these two switches are not compatible. It is also not allowed
4140 if a previous @code{-gnatc} switch has been given, since we must be generating
4141 code to be able to determine representation information.
4142
4143 @item ^-gnatRm[s]^/REPRESENTATION_INFO^
4144 Output convention and parameter passing mechanisms for all subprograms.
4145 This form is also incompatible with the use of @code{-gnatc}.
4146
4147 @item -gnats
4148 @cindex @option{-gnats} (@command{gcc})
4149 Syntax check only.
4150
4151 @item -gnatS
4152 @cindex @option{-gnatS} (@command{gcc})
4153 Print package Standard.
4154
4155 @item -gnatt
4156 @cindex @option{-gnatt} (@command{gcc})
4157 Generate tree output file.
4158
4159 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4160 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4161 All compiler tables start at @var{nnn} times usual starting size.
4162
4163 @item -gnatu
4164 @cindex @option{-gnatu} (@command{gcc})
4165 List units for this compilation.
4166
4167 @item -gnatU
4168 @cindex @option{-gnatU} (@command{gcc})
4169 Tag all error messages with the unique string ``error:''
4170
4171 @item -gnatv
4172 @cindex @option{-gnatv} (@command{gcc})
4173 Verbose mode. Full error output with source lines to @file{stdout}.
4174
4175 @item -gnatV
4176 @cindex @option{-gnatV} (@command{gcc})
4177 Control level of validity checking (@pxref{Validity Checking}).
4178
4179 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4180 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4181 Warning mode where
4182 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4183 the exact warnings that
4184 are enabled or disabled (@pxref{Warning Message Control}).
4185
4186 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4187 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4188 Wide character encoding method
4189 @ifclear vms
4190 (@var{e}=n/h/u/s/e/8).
4191 @end ifclear
4192 @ifset vms
4193 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4194 @end ifset
4195
4196 @item -gnatx
4197 @cindex @option{-gnatx} (@command{gcc})
4198 Suppress generation of cross-reference information.
4199
4200 @item -gnatX
4201 @cindex @option{-gnatX} (@command{gcc})
4202 Enable GNAT implementation extensions and latest Ada version.
4203
4204 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4205 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4206 Enable built-in style checks (@pxref{Style Checking}).
4207
4208 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4209 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4210 Distribution stub generation and compilation
4211 @ifclear vms
4212 (@var{m}=r/c for receiver/caller stubs).
4213 @end ifclear
4214 @ifset vms
4215 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4216 to be generated and compiled).
4217 @end ifset
4218
4219 @item ^-I^/SEARCH=^@var{dir}
4220 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4221 @cindex RTL
4222 Direct GNAT to search the @var{dir} directory for source files needed by
4223 the current compilation
4224 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4225
4226 @item ^-I-^/NOCURRENT_DIRECTORY^
4227 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4228 @cindex RTL
4229 Except for the source file named in the command line, do not look for source
4230 files in the directory containing the source file named in the command line
4231 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4232
4233 @ifclear vms
4234 @item -mbig-switch
4235 @cindex @option{-mbig-switch} (@command{gcc})
4236 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4237 This standard gcc switch causes the compiler to use larger offsets in its
4238 jump table representation for @code{case} statements.
4239 This may result in less efficient code, but is sometimes necessary
4240 (for example on HP-UX targets)
4241 @cindex HP-UX and @option{-mbig-switch} option
4242 in order to compile large and/or nested @code{case} statements.
4243
4244 @item -o @var{file}
4245 @cindex @option{-o} (@command{gcc})
4246 This switch is used in @command{gcc} to redirect the generated object file
4247 and its associated ALI file. Beware of this switch with GNAT, because it may
4248 cause the object file and ALI file to have different names which in turn
4249 may confuse the binder and the linker.
4250 @end ifclear
4251
4252 @item -nostdinc
4253 @cindex @option{-nostdinc} (@command{gcc})
4254 Inhibit the search of the default location for the GNAT Run Time
4255 Library (RTL) source files.
4256
4257 @item -nostdlib
4258 @cindex @option{-nostdlib} (@command{gcc})
4259 Inhibit the search of the default location for the GNAT Run Time
4260 Library (RTL) ALI files.
4261
4262 @ifclear vms
4263 @c @item -O@ovar{n}
4264 @c Expanding @ovar macro inline (explanation in macro def comments)
4265 @item -O@r{[}@var{n}@r{]}
4266 @cindex @option{-O} (@command{gcc})
4267 @var{n} controls the optimization level.
4268
4269 @table @asis
4270 @item n = 0
4271 No optimization, the default setting if no @option{-O} appears
4272
4273 @item n = 1
4274 Normal optimization, the default if you specify @option{-O} without
4275 an operand. A good compromise between code quality and compilation
4276 time.
4277
4278 @item n = 2
4279 Extensive optimization, may improve execution time, possibly at the cost of
4280 substantially increased compilation time.
4281
4282 @item n = 3
4283 Same as @option{-O2}, and also includes inline expansion for small subprograms
4284 in the same unit.
4285
4286 @item n = s
4287 Optimize space usage
4288 @end table
4289
4290 @noindent
4291 See also @ref{Optimization Levels}.
4292 @end ifclear
4293
4294 @ifset vms
4295 @item /NOOPTIMIZE
4296 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4297 Equivalent to @option{/OPTIMIZE=NONE}.
4298 This is the default behavior in the absence of an @option{/OPTIMIZE}
4299 qualifier.
4300
4301 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4302 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4303 Selects the level of optimization for your program. The supported
4304 keywords are as follows:
4305 @table @code
4306 @item ALL
4307 Perform most optimizations, including those that
4308 are expensive.
4309 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4310 without keyword options.
4311
4312 @item NONE
4313 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4314
4315 @item SOME
4316 Perform some optimizations, but omit ones that are costly.
4317
4318 @item DEVELOPMENT
4319 Same as @code{SOME}.
4320
4321 @item INLINING
4322 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4323 automatic inlining of small subprograms within a unit
4324
4325 @item UNROLL_LOOPS
4326 Try to unroll loops. This keyword may be specified together with
4327 any keyword above other than @code{NONE}. Loop unrolling
4328 usually, but not always, improves the performance of programs.
4329
4330 @item SPACE
4331 Optimize space usage
4332 @end table
4333
4334 @noindent
4335 See also @ref{Optimization Levels}.
4336 @end ifset
4337
4338 @ifclear vms
4339 @item -pass-exit-codes
4340 @cindex @option{-pass-exit-codes} (@command{gcc})
4341 Catch exit codes from the compiler and use the most meaningful as
4342 exit status.
4343 @end ifclear
4344
4345 @item --RTS=@var{rts-path}
4346 @cindex @option{--RTS} (@command{gcc})
4347 Specifies the default location of the runtime library. Same meaning as the
4348 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4349
4350 @item ^-S^/ASM^
4351 @cindex @option{^-S^/ASM^} (@command{gcc})
4352 ^Used in place of @option{-c} to^Used to^
4353 cause the assembler source file to be
4354 generated, using @file{^.s^.S^} as the extension,
4355 instead of the object file.
4356 This may be useful if you need to examine the generated assembly code.
4357
4358 @item ^-fverbose-asm^/VERBOSE_ASM^
4359 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4360 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4361 to cause the generated assembly code file to be annotated with variable
4362 names, making it significantly easier to follow.
4363
4364 @item ^-v^/VERBOSE^
4365 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4366 Show commands generated by the @command{gcc} driver. Normally used only for
4367 debugging purposes or if you need to be sure what version of the
4368 compiler you are executing.
4369
4370 @ifclear vms
4371 @item -V @var{ver}
4372 @cindex @option{-V} (@command{gcc})
4373 Execute @var{ver} version of the compiler. This is the @command{gcc}
4374 version, not the GNAT version.
4375 @end ifclear
4376
4377 @item ^-w^/NO_BACK_END_WARNINGS^
4378 @cindex @option{-w} (@command{gcc})
4379 Turn off warnings generated by the back end of the compiler. Use of
4380 this switch also causes the default for front end warnings to be set
4381 to suppress (as though @option{-gnatws} had appeared at the start of
4382 the options).
4383
4384 @end table
4385
4386 @ifclear vms
4387 @c Combining qualifiers does not work on VMS
4388 You may combine a sequence of GNAT switches into a single switch. For
4389 example, the combined switch
4390
4391 @cindex Combining GNAT switches
4392 @smallexample
4393 -gnatofi3
4394 @end smallexample
4395
4396 @noindent
4397 is equivalent to specifying the following sequence of switches:
4398
4399 @smallexample
4400 -gnato -gnatf -gnati3
4401 @end smallexample
4402 @end ifclear
4403
4404 @noindent
4405 The following restrictions apply to the combination of switches
4406 in this manner:
4407
4408 @itemize @bullet
4409 @item
4410 The switch @option{-gnatc} if combined with other switches must come
4411 first in the string.
4412
4413 @item
4414 The switch @option{-gnats} if combined with other switches must come
4415 first in the string.
4416
4417 @item
4418 The switches
4419 ^^@option{/DISTRIBUTION_STUBS=},^
4420 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4421 switches, and only one of them may appear in the command line.
4422
4423 @item
4424 The switch @option{-gnat-p} may not be combined with any other switch.
4425
4426 @ifclear vms
4427 @item
4428 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4429 switch), then all further characters in the switch are interpreted
4430 as style modifiers (see description of @option{-gnaty}).
4431
4432 @item
4433 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4434 switch), then all further characters in the switch are interpreted
4435 as debug flags (see description of @option{-gnatd}).
4436
4437 @item
4438 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4439 switch), then all further characters in the switch are interpreted
4440 as warning mode modifiers (see description of @option{-gnatw}).
4441
4442 @item
4443 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4444 switch), then all further characters in the switch are interpreted
4445 as validity checking options (@pxref{Validity Checking}).
4446
4447 @item
4448 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4449 a combined list of options.
4450 @end ifclear
4451 @end itemize
4452
4453 @node Output and Error Message Control
4454 @subsection Output and Error Message Control
4455 @findex stderr
4456
4457 @noindent
4458 The standard default format for error messages is called ``brief format''.
4459 Brief format messages are written to @file{stderr} (the standard error
4460 file) and have the following form:
4461
4462 @smallexample
4463 e.adb:3:04: Incorrect spelling of keyword "function"
4464 e.adb:4:20: ";" should be "is"
4465 @end smallexample
4466
4467 @noindent
4468 The first integer after the file name is the line number in the file,
4469 and the second integer is the column number within the line.
4470 @ifclear vms
4471 @code{GPS} can parse the error messages
4472 and point to the referenced character.
4473 @end ifclear
4474 The following switches provide control over the error message
4475 format:
4476
4477 @table @option
4478 @c !sort!
4479 @item -gnatv
4480 @cindex @option{-gnatv} (@command{gcc})
4481 @findex stdout
4482 @ifclear vms
4483 The v stands for verbose.
4484 @end ifclear
4485 The effect of this setting is to write long-format error
4486 messages to @file{stdout} (the standard output file.
4487 The same program compiled with the
4488 @option{-gnatv} switch would generate:
4489
4490 @smallexample
4491 @cartouche
4492 3. funcion X (Q : Integer)
4493 |
4494 >>> Incorrect spelling of keyword "function"
4495 4. return Integer;
4496 |
4497 >>> ";" should be "is"
4498 @end cartouche
4499 @end smallexample
4500
4501 @noindent
4502 The vertical bar indicates the location of the error, and the @samp{>>>}
4503 prefix can be used to search for error messages. When this switch is
4504 used the only source lines output are those with errors.
4505
4506 @item -gnatl
4507 @cindex @option{-gnatl} (@command{gcc})
4508 @ifclear vms
4509 The @code{l} stands for list.
4510 @end ifclear
4511 This switch causes a full listing of
4512 the file to be generated. In the case where a body is
4513 compiled, the corresponding spec is also listed, along
4514 with any subunits. Typical output from compiling a package
4515 body @file{p.adb} might look like:
4516
4517 @smallexample @c ada
4518 @cartouche
4519 Compiling: p.adb
4520
4521 1. package body p is
4522 2. procedure a;
4523 3. procedure a is separate;
4524 4. begin
4525 5. null
4526 |
4527 >>> missing ";"
4528
4529 6. end;
4530
4531 Compiling: p.ads
4532
4533 1. package p is
4534 2. pragma Elaborate_Body
4535 |
4536 >>> missing ";"
4537
4538 3. end p;
4539
4540 Compiling: p-a.adb
4541
4542 1. separate p
4543 |
4544 >>> missing "("
4545
4546 2. procedure a is
4547 3. begin
4548 4. null
4549 |
4550 >>> missing ";"
4551
4552 5. end;
4553 @end cartouche
4554 @end smallexample
4555
4556 @noindent
4557 @findex stderr
4558 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4559 standard output is redirected, a brief summary is written to
4560 @file{stderr} (standard error) giving the number of error messages and
4561 warning messages generated.
4562
4563 @item ^-gnatl^/OUTPUT_FILE^=file
4564 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4565 This has the same effect as @option{-gnatl} except that the output is
4566 written to a file instead of to standard output. If the given name
4567 @file{fname} does not start with a period, then it is the full name
4568 of the file to be written. If @file{fname} is an extension, it is
4569 appended to the name of the file being compiled. For example, if
4570 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4571 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4572
4573 @item -gnatU
4574 @cindex @option{-gnatU} (@command{gcc})
4575 This switch forces all error messages to be preceded by the unique
4576 string ``error:''. This means that error messages take a few more
4577 characters in space, but allows easy searching for and identification
4578 of error messages.
4579
4580 @item -gnatb
4581 @cindex @option{-gnatb} (@command{gcc})
4582 @ifclear vms
4583 The @code{b} stands for brief.
4584 @end ifclear
4585 This switch causes GNAT to generate the
4586 brief format error messages to @file{stderr} (the standard error
4587 file) as well as the verbose
4588 format message or full listing (which as usual is written to
4589 @file{stdout} (the standard output file).
4590
4591 @item -gnatm=@var{n}
4592 @cindex @option{-gnatm} (@command{gcc})
4593 @ifclear vms
4594 The @code{m} stands for maximum.
4595 @end ifclear
4596 @var{n} is a decimal integer in the
4597 range of 1 to 999999 and limits the number of error or warning
4598 messages to be generated. For example, using
4599 @option{-gnatm2} might yield
4600
4601 @smallexample
4602 e.adb:3:04: Incorrect spelling of keyword "function"
4603 e.adb:5:35: missing ".."
4604 fatal error: maximum number of errors detected
4605 compilation abandoned
4606 @end smallexample
4607
4608 @noindent
4609 The default setting if
4610 no switch is given is 9999. If the number of warnings reaches this
4611 limit, then a message is output and further warnings are suppressed,
4612 but the compilation is continued. If the number of error messages
4613 reaches this limit, then a message is output and the compilation
4614 is abandoned. A value of zero means that no limit applies.
4615
4616 @noindent
4617 Note that the equal sign is optional, so the switches
4618 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4619
4620 @item -gnatf
4621 @cindex @option{-gnatf} (@command{gcc})
4622 @cindex Error messages, suppressing
4623 @ifclear vms
4624 The @code{f} stands for full.
4625 @end ifclear
4626 Normally, the compiler suppresses error messages that are likely to be
4627 redundant. This switch causes all error
4628 messages to be generated. In particular, in the case of
4629 references to undefined variables. If a given variable is referenced
4630 several times, the normal format of messages is
4631 @smallexample
4632 e.adb:7:07: "V" is undefined (more references follow)
4633 @end smallexample
4634
4635 @noindent
4636 where the parenthetical comment warns that there are additional
4637 references to the variable @code{V}. Compiling the same program with the
4638 @option{-gnatf} switch yields
4639
4640 @smallexample
4641 e.adb:7:07: "V" is undefined
4642 e.adb:8:07: "V" is undefined
4643 e.adb:8:12: "V" is undefined
4644 e.adb:8:16: "V" is undefined
4645 e.adb:9:07: "V" is undefined
4646 e.adb:9:12: "V" is undefined
4647 @end smallexample
4648
4649 @noindent
4650 The @option{-gnatf} switch also generates additional information for
4651 some error messages. Some examples are:
4652
4653 @itemize @bullet
4654 @item
4655 Details on possibly non-portable unchecked conversion
4656 @item
4657 List possible interpretations for ambiguous calls
4658 @item
4659 Additional details on incorrect parameters
4660 @end itemize
4661
4662 @item -gnatjnn
4663 @cindex @option{-gnatjnn} (@command{gcc})
4664 In normal operation mode (or if @option{-gnatj0} is used), then error messages
4665 with continuation lines are treated as though the continuation lines were
4666 separate messages (and so a warning with two continuation lines counts as
4667 three warnings, and is listed as three separate messages).
4668
4669 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4670 messages are output in a different manner. A message and all its continuation
4671 lines are treated as a unit, and count as only one warning or message in the
4672 statistics totals. Furthermore, the message is reformatted so that no line
4673 is longer than nn characters.
4674
4675 @item -gnatq
4676 @cindex @option{-gnatq} (@command{gcc})
4677 @ifclear vms
4678 The @code{q} stands for quit (really ``don't quit'').
4679 @end ifclear
4680 In normal operation mode, the compiler first parses the program and
4681 determines if there are any syntax errors. If there are, appropriate
4682 error messages are generated and compilation is immediately terminated.
4683 This switch tells
4684 GNAT to continue with semantic analysis even if syntax errors have been
4685 found. This may enable the detection of more errors in a single run. On
4686 the other hand, the semantic analyzer is more likely to encounter some
4687 internal fatal error when given a syntactically invalid tree.
4688
4689 @item -gnatQ
4690 @cindex @option{-gnatQ} (@command{gcc})
4691 In normal operation mode, the @file{ALI} file is not generated if any
4692 illegalities are detected in the program. The use of @option{-gnatQ} forces
4693 generation of the @file{ALI} file. This file is marked as being in
4694 error, so it cannot be used for binding purposes, but it does contain
4695 reasonably complete cross-reference information, and thus may be useful
4696 for use by tools (e.g., semantic browsing tools or integrated development
4697 environments) that are driven from the @file{ALI} file. This switch
4698 implies @option{-gnatq}, since the semantic phase must be run to get a
4699 meaningful ALI file.
4700
4701 In addition, if @option{-gnatt} is also specified, then the tree file is
4702 generated even if there are illegalities. It may be useful in this case
4703 to also specify @option{-gnatq} to ensure that full semantic processing
4704 occurs. The resulting tree file can be processed by ASIS, for the purpose
4705 of providing partial information about illegal units, but if the error
4706 causes the tree to be badly malformed, then ASIS may crash during the
4707 analysis.
4708
4709 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4710 being in error, @command{gnatmake} will attempt to recompile the source when it
4711 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4712
4713 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4714 since ALI files are never generated if @option{-gnats} is set.
4715
4716 @end table
4717
4718 @node Warning Message Control
4719 @subsection Warning Message Control
4720 @cindex Warning messages
4721 @noindent
4722 In addition to error messages, which correspond to illegalities as defined
4723 in the Ada Reference Manual, the compiler detects two kinds of warning
4724 situations.
4725
4726 First, the compiler considers some constructs suspicious and generates a
4727 warning message to alert you to a possible error. Second, if the
4728 compiler detects a situation that is sure to raise an exception at
4729 run time, it generates a warning message. The following shows an example
4730 of warning messages:
4731 @smallexample
4732 e.adb:4:24: warning: creation of object may raise Storage_Error
4733 e.adb:10:17: warning: static value out of range
4734 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4735 @end smallexample
4736
4737 @noindent
4738 GNAT considers a large number of situations as appropriate
4739 for the generation of warning messages. As always, warnings are not
4740 definite indications of errors. For example, if you do an out-of-range
4741 assignment with the deliberate intention of raising a
4742 @code{Constraint_Error} exception, then the warning that may be
4743 issued does not indicate an error. Some of the situations for which GNAT
4744 issues warnings (at least some of the time) are given in the following
4745 list. This list is not complete, and new warnings are often added to
4746 subsequent versions of GNAT. The list is intended to give a general idea
4747 of the kinds of warnings that are generated.
4748
4749 @itemize @bullet
4750 @item
4751 Possible infinitely recursive calls
4752
4753 @item
4754 Out-of-range values being assigned
4755
4756 @item
4757 Possible order of elaboration problems
4758
4759 @item
4760 Assertions (pragma Assert) that are sure to fail
4761
4762 @item
4763 Unreachable code
4764
4765 @item
4766 Address clauses with possibly unaligned values, or where an attempt is
4767 made to overlay a smaller variable with a larger one.
4768
4769 @item
4770 Fixed-point type declarations with a null range
4771
4772 @item
4773 Direct_IO or Sequential_IO instantiated with a type that has access values
4774
4775 @item
4776 Variables that are never assigned a value
4777
4778 @item
4779 Variables that are referenced before being initialized
4780
4781 @item
4782 Task entries with no corresponding @code{accept} statement
4783
4784 @item
4785 Duplicate accepts for the same task entry in a @code{select}
4786
4787 @item
4788 Objects that take too much storage
4789
4790 @item
4791 Unchecked conversion between types of differing sizes
4792
4793 @item
4794 Missing @code{return} statement along some execution path in a function
4795
4796 @item
4797 Incorrect (unrecognized) pragmas
4798
4799 @item
4800 Incorrect external names
4801
4802 @item
4803 Allocation from empty storage pool
4804
4805 @item
4806 Potentially blocking operation in protected type
4807
4808 @item
4809 Suspicious parenthesization of expressions
4810
4811 @item
4812 Mismatching bounds in an aggregate
4813
4814 @item
4815 Attempt to return local value by reference
4816
4817 @item
4818 Premature instantiation of a generic body
4819
4820 @item
4821 Attempt to pack aliased components
4822
4823 @item
4824 Out of bounds array subscripts
4825
4826 @item
4827 Wrong length on string assignment
4828
4829 @item
4830 Violations of style rules if style checking is enabled
4831
4832 @item
4833 Unused @code{with} clauses
4834
4835 @item
4836 @code{Bit_Order} usage that does not have any effect
4837
4838 @item
4839 @code{Standard.Duration} used to resolve universal fixed expression
4840
4841 @item
4842 Dereference of possibly null value
4843
4844 @item
4845 Declaration that is likely to cause storage error
4846
4847 @item
4848 Internal GNAT unit @code{with}'ed by application unit
4849
4850 @item
4851 Values known to be out of range at compile time
4852
4853 @item
4854 Unreferenced labels and variables
4855
4856 @item
4857 Address overlays that could clobber memory
4858
4859 @item
4860 Unexpected initialization when address clause present
4861
4862 @item
4863 Bad alignment for address clause
4864
4865 @item
4866 Useless type conversions
4867
4868 @item
4869 Redundant assignment statements and other redundant constructs
4870
4871 @item
4872 Useless exception handlers
4873
4874 @item
4875 Accidental hiding of name by child unit
4876
4877 @item
4878 Access before elaboration detected at compile time
4879
4880 @item
4881 A range in a @code{for} loop that is known to be null or might be null
4882
4883 @end itemize
4884
4885 @noindent
4886 The following section lists compiler switches that are available
4887 to control the handling of warning messages. It is also possible
4888 to exercise much finer control over what warnings are issued and
4889 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
4890 gnat_rm, GNAT Reference manual}.
4891
4892 @table @option
4893 @c !sort!
4894 @item -gnatwa
4895 @emph{Activate most optional warnings.}
4896 @cindex @option{-gnatwa} (@command{gcc})
4897 This switch activates most optional warning messages. See the remaining list
4898 in this section for details on optional warning messages that can be
4899 individually controlled. The warnings that are not turned on by this
4900 switch are
4901 @option{-gnatwd} (implicit dereferencing),
4902 @option{-gnatwh} (hiding),
4903 @option{-gnatw.d} (tag warnings with -gnatw switch)
4904 @option{-gnatw.h} (holes (gaps) in record layouts)
4905 @option{-gnatw.i} (overlapping actuals),
4906 @option{-gnatw.k} (redefinition of names in standard),
4907 @option{-gnatwl} (elaboration warnings),
4908 @option{-gnatw.l} (inherited aspects),
4909 @option{-gnatw.o} (warn on values set by out parameters ignored),
4910 @option{-gnatwt} (tracking of deleted conditional code)
4911 and @option{-gnatw.u} (unordered enumeration),
4912 All other optional warnings are turned on.
4913
4914 @item -gnatwA
4915 @emph{Suppress all optional errors.}
4916 @cindex @option{-gnatwA} (@command{gcc})
4917 This switch suppresses all optional warning messages, see remaining list
4918 in this section for details on optional warning messages that can be
4919 individually controlled. Note that unlike switch @option{-gnatws}, the
4920 use of switch @option{-gnatwA} does not suppress warnings that are
4921 normally given unconditionally and cannot be individually controlled
4922 (for example, the warning about a missing exit path in a function).
4923 Also, again unlike switch @option{-gnatws}, warnings suppressed by
4924 the use of switch @option{-gnatwA} can be individually turned back
4925 on. For example the use of switch @option{-gnatwA} followed by
4926 switch @option{-gnatwd} will suppress all optional warnings except
4927 the warnings for implicit dereferencing.
4928
4929 @item -gnatw.a
4930 @emph{Activate warnings on failing assertions.}
4931 @cindex @option{-gnatw.a} (@command{gcc})
4932 @cindex Assert failures
4933 This switch activates warnings for assertions where the compiler can tell at
4934 compile time that the assertion will fail. Note that this warning is given
4935 even if assertions are disabled. The default is that such warnings are
4936 generated.
4937
4938 @item -gnatw.A
4939 @emph{Suppress warnings on failing assertions.}
4940 @cindex @option{-gnatw.A} (@command{gcc})
4941 @cindex Assert failures
4942 This switch suppresses warnings for assertions where the compiler can tell at
4943 compile time that the assertion will fail.
4944
4945 @item -gnatwb
4946 @emph{Activate warnings on bad fixed values.}
4947 @cindex @option{-gnatwb} (@command{gcc})
4948 @cindex Bad fixed values
4949 @cindex Fixed-point Small value
4950 @cindex Small value
4951 This switch activates warnings for static fixed-point expressions whose
4952 value is not an exact multiple of Small. Such values are implementation
4953 dependent, since an implementation is free to choose either of the multiples
4954 that surround the value. GNAT always chooses the closer one, but this is not
4955 required behavior, and it is better to specify a value that is an exact
4956 multiple, ensuring predictable execution. The default is that such warnings
4957 are not generated.
4958
4959 @item -gnatwB
4960 @emph{Suppress warnings on bad fixed values.}
4961 @cindex @option{-gnatwB} (@command{gcc})
4962 This switch suppresses warnings for static fixed-point expressions whose
4963 value is not an exact multiple of Small.
4964
4965 @item -gnatw.b
4966 @emph{Activate warnings on biased representation.}
4967 @cindex @option{-gnatw.b} (@command{gcc})
4968 @cindex Biased representation
4969 This switch activates warnings when a size clause, value size clause, component
4970 clause, or component size clause forces the use of biased representation for an
4971 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
4972 to represent 10/11). The default is that such warnings are generated.
4973
4974 @item -gnatw.B
4975 @emph{Suppress warnings on biased representation.}
4976 @cindex @option{-gnatwB} (@command{gcc})
4977 This switch suppresses warnings for representation clauses that force the use
4978 of biased representation.
4979
4980 @item -gnatwc
4981 @emph{Activate warnings on conditionals.}
4982 @cindex @option{-gnatwc} (@command{gcc})
4983 @cindex Conditionals, constant
4984 This switch activates warnings for conditional expressions used in
4985 tests that are known to be True or False at compile time. The default
4986 is that such warnings are not generated.
4987 Note that this warning does
4988 not get issued for the use of boolean variables or constants whose
4989 values are known at compile time, since this is a standard technique
4990 for conditional compilation in Ada, and this would generate too many
4991 false positive warnings.
4992
4993 This warning option also activates a special test for comparisons using
4994 the operators ``>='' and`` <=''.
4995 If the compiler can tell that only the equality condition is possible,
4996 then it will warn that the ``>'' or ``<'' part of the test
4997 is useless and that the operator could be replaced by ``=''.
4998 An example would be comparing a @code{Natural} variable <= 0.
4999
5000 This warning option also generates warnings if
5001 one or both tests is optimized away in a membership test for integer
5002 values if the result can be determined at compile time. Range tests on
5003 enumeration types are not included, since it is common for such tests
5004 to include an end point.
5005
5006 This warning can also be turned on using @option{-gnatwa}.
5007
5008 @item -gnatwC
5009 @emph{Suppress warnings on conditionals.}
5010 @cindex @option{-gnatwC} (@command{gcc})
5011 This switch suppresses warnings for conditional expressions used in
5012 tests that are known to be True or False at compile time.
5013
5014 @item -gnatw.c
5015 @emph{Activate warnings on missing component clauses.}
5016 @cindex @option{-gnatw.c} (@command{gcc})
5017 @cindex Component clause, missing
5018 This switch activates warnings for record components where a record
5019 representation clause is present and has component clauses for the
5020 majority, but not all, of the components. A warning is given for each
5021 component for which no component clause is present.
5022
5023 This warning can also be turned on using @option{-gnatwa}.
5024
5025 @item -gnatw.C
5026 @emph{Suppress warnings on missing component clauses.}
5027 @cindex @option{-gnatwC} (@command{gcc})
5028 This switch suppresses warnings for record components that are
5029 missing a component clause in the situation described above.
5030
5031 @item -gnatwd
5032 @emph{Activate warnings on implicit dereferencing.}
5033 @cindex @option{-gnatwd} (@command{gcc})
5034 If this switch is set, then the use of a prefix of an access type
5035 in an indexed component, slice, or selected component without an
5036 explicit @code{.all} will generate a warning. With this warning
5037 enabled, access checks occur only at points where an explicit
5038 @code{.all} appears in the source code (assuming no warnings are
5039 generated as a result of this switch). The default is that such
5040 warnings are not generated.
5041 Note that @option{-gnatwa} does not affect the setting of
5042 this warning option.
5043
5044 @item -gnatwD
5045 @emph{Suppress warnings on implicit dereferencing.}
5046 @cindex @option{-gnatwD} (@command{gcc})
5047 @cindex Implicit dereferencing
5048 @cindex Dereferencing, implicit
5049 This switch suppresses warnings for implicit dereferences in
5050 indexed components, slices, and selected components.
5051
5052 @item -gnatw.d
5053 @emph{Activate tagging of warning messages.}
5054 @cindex @option{-gnatw.d} (@command{gcc})
5055 If this switch is set, then warning messages are tagged, either with
5056 the string ``@option{-gnatw?}'' showing which switch controls the warning,
5057 or with ``[enabled by default]'' if the warning is not under control of a
5058 specific @option{-gnatw?} switch. This mode is off by default, and is not
5059 affected by the use of @code{-gnatwa}.
5060
5061 @item -gnatw.D
5062 @emph{Deactivate tagging of warning messages.}
5063 @cindex @option{-gnatw.d} (@command{gcc})
5064 If this switch is set, then warning messages return to the default
5065 mode in which warnings are not tagged as described above for
5066 @code{-gnatw.d}.
5067
5068 @item -gnatwe
5069 @emph{Treat warnings and style checks as errors.}
5070 @cindex @option{-gnatwe} (@command{gcc})
5071 @cindex Warnings, treat as error
5072 This switch causes warning messages and style check messages to be
5073 treated as errors.
5074 The warning string still appears, but the warning messages are counted
5075 as errors, and prevent the generation of an object file. Note that this
5076 is the only -gnatw switch that affects the handling of style check messages.
5077
5078 @item -gnatw.e
5079 @emph{Activate every optional warning}
5080 @cindex @option{-gnatw.e} (@command{gcc})
5081 @cindex Warnings, activate every optional warning
5082 This switch activates all optional warnings, including those which
5083 are not activated by @code{-gnatwa}. The use of this switch is not
5084 recommended for normal use. If you turn this switch on, it is almost
5085 certain that you will get large numbers of useless warnings. The
5086 warnings that are excluded from @code{-gnatwa} are typically highly
5087 specialized warnings that are suitable for use only in code that has
5088 been specifically designed according to specialized coding rules.
5089
5090 @item -gnatwf
5091 @emph{Activate warnings on unreferenced formals.}
5092 @cindex @option{-gnatwf} (@command{gcc})
5093 @cindex Formals, unreferenced
5094 This switch causes a warning to be generated if a formal parameter
5095 is not referenced in the body of the subprogram. This warning can
5096 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5097 default is that these warnings are not generated.
5098
5099 @item -gnatwF
5100 @emph{Suppress warnings on unreferenced formals.}
5101 @cindex @option{-gnatwF} (@command{gcc})
5102 This switch suppresses warnings for unreferenced formal
5103 parameters. Note that the
5104 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5105 effect of warning on unreferenced entities other than subprogram
5106 formals.
5107
5108 @item -gnatwg
5109 @emph{Activate warnings on unrecognized pragmas.}
5110 @cindex @option{-gnatwg} (@command{gcc})
5111 @cindex Pragmas, unrecognized
5112 This switch causes a warning to be generated if an unrecognized
5113 pragma is encountered. Apart from issuing this warning, the
5114 pragma is ignored and has no effect. This warning can
5115 also be turned on using @option{-gnatwa}. The default
5116 is that such warnings are issued (satisfying the Ada Reference
5117 Manual requirement that such warnings appear).
5118
5119 @item -gnatwG
5120 @emph{Suppress warnings on unrecognized pragmas.}
5121 @cindex @option{-gnatwG} (@command{gcc})
5122 This switch suppresses warnings for unrecognized pragmas.
5123
5124 @item -gnatwh
5125 @emph{Activate warnings on hiding.}
5126 @cindex @option{-gnatwh} (@command{gcc})
5127 @cindex Hiding of Declarations
5128 This switch activates warnings on hiding declarations.
5129 A declaration is considered hiding
5130 if it is for a non-overloadable entity, and it declares an entity with the
5131 same name as some other entity that is directly or use-visible. The default
5132 is that such warnings are not generated.
5133 Note that @option{-gnatwa} does not affect the setting of this warning option.
5134
5135 @item -gnatwH
5136 @emph{Suppress warnings on hiding.}
5137 @cindex @option{-gnatwH} (@command{gcc})
5138 This switch suppresses warnings on hiding declarations.
5139
5140 @item -gnatw.h
5141 @emph{Activate warnings on holes/gaps in records.}
5142 @cindex @option{-gnatw.h} (@command{gcc})
5143 @cindex Record Representation (gaps)
5144 This switch activates warnings on component clauses in record
5145 representation clauses that leave holes (gaps) in the record layout.
5146 If this warning option is active, then record representation clauses
5147 should specify a contiguous layout, adding unused fill fields if needed.
5148 Note that @option{-gnatwa} does not affect the setting of this warning option.
5149
5150 @item -gnatw.H
5151 @emph{Suppress warnings on holes/gaps in records.}
5152 @cindex @option{-gnatw.H} (@command{gcc})
5153 This switch suppresses warnings on component clauses in record
5154 representation clauses that leave holes (haps) in the record layout.
5155
5156 @item -gnatwi
5157 @emph{Activate warnings on implementation units.}
5158 @cindex @option{-gnatwi} (@command{gcc})
5159 This switch activates warnings for a @code{with} of an internal GNAT
5160 implementation unit, defined as any unit from the @code{Ada},
5161 @code{Interfaces}, @code{GNAT},
5162 ^^@code{DEC},^ or @code{System}
5163 hierarchies that is not
5164 documented in either the Ada Reference Manual or the GNAT
5165 Programmer's Reference Manual. Such units are intended only
5166 for internal implementation purposes and should not be @code{with}'ed
5167 by user programs. The default is that such warnings are generated
5168 This warning can also be turned on using @option{-gnatwa}.
5169
5170 @item -gnatwI
5171 @emph{Disable warnings on implementation units.}
5172 @cindex @option{-gnatwI} (@command{gcc})
5173 This switch disables warnings for a @code{with} of an internal GNAT
5174 implementation unit.
5175
5176 @item -gnatw.i
5177 @emph{Activate warnings on overlapping actuals.}
5178 @cindex @option{-gnatw.i} (@command{gcc})
5179 This switch enables a warning on statically detectable overlapping actuals in
5180 a subprogram call, when one of the actuals is an in-out parameter, and the
5181 types of the actuals are not by-copy types. The warning is off by default,
5182 and is not included under -gnatwa.
5183
5184 @item -gnatw.I
5185 @emph{Disable warnings on overlapping actuals.}
5186 @cindex @option{-gnatw.I} (@command{gcc})
5187 This switch disables warnings on overlapping actuals in a call..
5188
5189 @item -gnatwj
5190 @emph{Activate warnings on obsolescent features (Annex J).}
5191 @cindex @option{-gnatwj} (@command{gcc})
5192 @cindex Features, obsolescent
5193 @cindex Obsolescent features
5194 If this warning option is activated, then warnings are generated for
5195 calls to subprograms marked with @code{pragma Obsolescent} and
5196 for use of features in Annex J of the Ada Reference Manual. In the
5197 case of Annex J, not all features are flagged. In particular use
5198 of the renamed packages (like @code{Text_IO}) and use of package
5199 @code{ASCII} are not flagged, since these are very common and
5200 would generate many annoying positive warnings. The default is that
5201 such warnings are not generated. This warning is also turned on by
5202 the use of @option{-gnatwa}.
5203
5204 In addition to the above cases, warnings are also generated for
5205 GNAT features that have been provided in past versions but which
5206 have been superseded (typically by features in the new Ada standard).
5207 For example, @code{pragma Ravenscar} will be flagged since its
5208 function is replaced by @code{pragma Profile(Ravenscar)}, and
5209 @code{pragma Interface_Name} will be flagged since its function
5210 is replaced by @code{pragma Import}.
5211
5212 Note that this warning option functions differently from the
5213 restriction @code{No_Obsolescent_Features} in two respects.
5214 First, the restriction applies only to annex J features.
5215 Second, the restriction does flag uses of package @code{ASCII}.
5216
5217 @item -gnatwJ
5218 @emph{Suppress warnings on obsolescent features (Annex J).}
5219 @cindex @option{-gnatwJ} (@command{gcc})
5220 This switch disables warnings on use of obsolescent features.
5221
5222 @item -gnatwk
5223 @emph{Activate warnings on variables that could be constants.}
5224 @cindex @option{-gnatwk} (@command{gcc})
5225 This switch activates warnings for variables that are initialized but
5226 never modified, and then could be declared constants. The default is that
5227 such warnings are not given.
5228 This warning can also be turned on using @option{-gnatwa}.
5229
5230 @item -gnatwK
5231 @emph{Suppress warnings on variables that could be constants.}
5232 @cindex @option{-gnatwK} (@command{gcc})
5233 This switch disables warnings on variables that could be declared constants.
5234
5235 @item -gnatw.k
5236 @emph{Activate warnings on redefinition of names in standard.}
5237 @cindex @option{-gnatw.k} (@command{gcc})
5238 This switch activates warnings for declarations that declare a name that
5239 is defined in package Standard. Such declarations can be confusing,
5240 especially since the names in package Standard continue to be directly
5241 visible, meaning that use visibiliy on such redeclared names does not
5242 work as expected. Names of discriminants and components in records are
5243 not included in this check.
5244 This warning is not part of the warnings activated by @option{-gnatwa}.
5245 It must be explicitly activated.
5246
5247 @item -gnatw.K
5248 @emph{Suppress warnings on variables that could be constants.}
5249 @cindex @option{-gnatwK} (@command{gcc})
5250 This switch activates warnings for declarations that declare a name that
5251 is defined in package Standard.
5252
5253 @item -gnatwl
5254 @emph{Activate warnings for elaboration pragmas.}
5255 @cindex @option{-gnatwl} (@command{gcc})
5256 @cindex Elaboration, warnings
5257 This switch activates warnings on missing
5258 @code{Elaborate_All} and @code{Elaborate} pragmas.
5259 See the section in this guide on elaboration checking for details on
5260 when such pragmas should be used. In dynamic elaboration mode, this switch
5261 generations warnings about the need to add elaboration pragmas. Note however,
5262 that if you blindly follow these warnings, and add @code{Elaborate_All}
5263 warnings wherever they are recommended, you basically end up with the
5264 equivalent of the static elaboration model, which may not be what you want for
5265 legacy code for which the static model does not work.
5266
5267 For the static model, the messages generated are labeled "info:" (for
5268 information messages). They are not warnings to add elaboration pragmas,
5269 merely informational messages showing what implicit elaboration pragmas
5270 have been added, for use in analyzing elaboration circularity problems.
5271
5272 Warnings are also generated if you
5273 are using the static mode of elaboration, and a @code{pragma Elaborate}
5274 is encountered. The default is that such warnings
5275 are not generated.
5276 This warning is not automatically turned on by the use of @option{-gnatwa}.
5277
5278 @item -gnatwL
5279 @emph{Suppress warnings for elaboration pragmas.}
5280 @cindex @option{-gnatwL} (@command{gcc})
5281 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5282 See the section in this guide on elaboration checking for details on
5283 when such pragmas should be used.
5284
5285 @item -gnatw.l
5286 @emph{List inherited aspects.}
5287 @cindex @option{-gnatw.l} (@command{gcc})
5288 This switch causes the compiler to list inherited invariants,
5289 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
5290 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
5291 These messages are not automatically turned on by the use of @option{-gnatwa}.
5292
5293 @item -gnatw.L
5294 @emph{Suppress listing of inherited aspects.}
5295 @cindex @option{-gnatw.L} (@command{gcc})
5296 This switch suppresses listing of inherited aspects.
5297
5298 @item -gnatwm
5299 @emph{Activate warnings on modified but unreferenced variables.}
5300 @cindex @option{-gnatwm} (@command{gcc})
5301 This switch activates warnings for variables that are assigned (using
5302 an initialization value or with one or more assignment statements) but
5303 whose value is never read. The warning is suppressed for volatile
5304 variables and also for variables that are renamings of other variables
5305 or for which an address clause is given.
5306 This warning can also be turned on using @option{-gnatwa}.
5307 The default is that these warnings are not given.
5308
5309 @item -gnatwM
5310 @emph{Disable warnings on modified but unreferenced variables.}
5311 @cindex @option{-gnatwM} (@command{gcc})
5312 This switch disables warnings for variables that are assigned or
5313 initialized, but never read.
5314
5315 @item -gnatw.m
5316 @emph{Activate warnings on suspicious modulus values.}
5317 @cindex @option{-gnatw.m} (@command{gcc})
5318 This switch activates warnings for modulus values that seem suspicious.
5319 The cases caught are where the size is the same as the modulus (e.g.
5320 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5321 with no size clause. The guess in both cases is that 2**x was intended
5322 rather than x. In addition expressions of the form 2*x for small x
5323 generate a warning (the almost certainly accurate guess being that
5324 2**x was intended). The default is that these warnings are given.
5325
5326 @item -gnatw.M
5327 @emph{Disable warnings on suspicious modulus values.}
5328 @cindex @option{-gnatw.M} (@command{gcc})
5329 This switch disables warnings for suspicious modulus values.
5330
5331 @item -gnatwn
5332 @emph{Set normal warnings mode.}
5333 @cindex @option{-gnatwn} (@command{gcc})
5334 This switch sets normal warning mode, in which enabled warnings are
5335 issued and treated as warnings rather than errors. This is the default
5336 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5337 an explicit @option{-gnatws} or
5338 @option{-gnatwe}. It also cancels the effect of the
5339 implicit @option{-gnatwe} that is activated by the
5340 use of @option{-gnatg}.
5341
5342 @item -gnatw.n
5343 @emph{Activate warnings on atomic synchronization.}
5344 @cindex @option{-gnatw.n} (@command{gcc})
5345 @cindex Atomic Synchronization, warnings
5346 This switch actives warnings when an access to an atomic variable
5347 requires the generation of atomic synchronization code. These
5348 warnings are off by default and this warning is not included
5349 in @code{-gnatwa}.
5350
5351 @item -gnatw.N
5352 @emph{Suppress warnings on atomic synchronization.}
5353 @cindex @option{-gnatw.n} (@command{gcc})
5354 @cindex Atomic Synchronization, warnings
5355 This switch suppresses warnings when an access to an atomic variable
5356 requires the generation of atomic synchronization code.
5357
5358 @item -gnatwo
5359 @emph{Activate warnings on address clause overlays.}
5360 @cindex @option{-gnatwo} (@command{gcc})
5361 @cindex Address Clauses, warnings
5362 This switch activates warnings for possibly unintended initialization
5363 effects of defining address clauses that cause one variable to overlap
5364 another. The default is that such warnings are generated.
5365 This warning can also be turned on using @option{-gnatwa}.
5366
5367 @item -gnatwO
5368 @emph{Suppress warnings on address clause overlays.}
5369 @cindex @option{-gnatwO} (@command{gcc})
5370 This switch suppresses warnings on possibly unintended initialization
5371 effects of defining address clauses that cause one variable to overlap
5372 another.
5373
5374 @item -gnatw.o
5375 @emph{Activate warnings on modified but unreferenced out parameters.}
5376 @cindex @option{-gnatw.o} (@command{gcc})
5377 This switch activates warnings for variables that are modified by using
5378 them as actuals for a call to a procedure with an out mode formal, where
5379 the resulting assigned value is never read. It is applicable in the case
5380 where there is more than one out mode formal. If there is only one out
5381 mode formal, the warning is issued by default (controlled by -gnatwu).
5382 The warning is suppressed for volatile
5383 variables and also for variables that are renamings of other variables
5384 or for which an address clause is given.
5385 The default is that these warnings are not given. Note that this warning
5386 is not included in -gnatwa, it must be activated explicitly.
5387
5388 @item -gnatw.O
5389 @emph{Disable warnings on modified but unreferenced out parameters.}
5390 @cindex @option{-gnatw.O} (@command{gcc})
5391 This switch suppresses warnings for variables that are modified by using
5392 them as actuals for a call to a procedure with an out mode formal, where
5393 the resulting assigned value is never read.
5394
5395 @item -gnatwp
5396 @emph{Activate warnings on ineffective pragma Inlines.}
5397 @cindex @option{-gnatwp} (@command{gcc})
5398 @cindex Inlining, warnings
5399 This switch activates warnings for failure of front end inlining
5400 (activated by @option{-gnatN}) to inline a particular call. There are
5401 many reasons for not being able to inline a call, including most
5402 commonly that the call is too complex to inline. The default is
5403 that such warnings are not given.
5404 This warning can also be turned on using @option{-gnatwa}.
5405 Warnings on ineffective inlining by the gcc back-end can be activated
5406 separately, using the gcc switch -Winline.
5407
5408 @item -gnatwP
5409 @emph{Suppress warnings on ineffective pragma Inlines.}
5410 @cindex @option{-gnatwP} (@command{gcc})
5411 This switch suppresses warnings on ineffective pragma Inlines. If the
5412 inlining mechanism cannot inline a call, it will simply ignore the
5413 request silently.
5414
5415 @item -gnatw.p
5416 @emph{Activate warnings on parameter ordering.}
5417 @cindex @option{-gnatw.p} (@command{gcc})
5418 @cindex Parameter order, warnings
5419 This switch activates warnings for cases of suspicious parameter
5420 ordering when the list of arguments are all simple identifiers that
5421 match the names of the formals, but are in a different order. The
5422 warning is suppressed if any use of named parameter notation is used,
5423 so this is the appropriate way to suppress a false positive (and
5424 serves to emphasize that the "misordering" is deliberate). The
5425 default is
5426 that such warnings are not given.
5427 This warning can also be turned on using @option{-gnatwa}.
5428
5429 @item -gnatw.P
5430 @emph{Suppress warnings on parameter ordering.}
5431 @cindex @option{-gnatw.P} (@command{gcc})
5432 This switch suppresses warnings on cases of suspicious parameter
5433 ordering.
5434
5435 @item -gnatwq
5436 @emph{Activate warnings on questionable missing parentheses.}
5437 @cindex @option{-gnatwq} (@command{gcc})
5438 @cindex Parentheses, warnings
5439 This switch activates warnings for cases where parentheses are not used and
5440 the result is potential ambiguity from a readers point of view. For example
5441 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5442 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5443 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5444 follow the rule of always parenthesizing to make the association clear, and
5445 this warning switch warns if such parentheses are not present. The default
5446 is that these warnings are given.
5447 This warning can also be turned on using @option{-gnatwa}.
5448
5449 @item -gnatwQ
5450 @emph{Suppress warnings on questionable missing parentheses.}
5451 @cindex @option{-gnatwQ} (@command{gcc})
5452 This switch suppresses warnings for cases where the association is not
5453 clear and the use of parentheses is preferred.
5454
5455 @item -gnatwr
5456 @emph{Activate warnings on redundant constructs.}
5457 @cindex @option{-gnatwr} (@command{gcc})
5458 This switch activates warnings for redundant constructs. The following
5459 is the current list of constructs regarded as redundant:
5460
5461 @itemize @bullet
5462 @item
5463 Assignment of an item to itself.
5464 @item
5465 Type conversion that converts an expression to its own type.
5466 @item
5467 Use of the attribute @code{Base} where @code{typ'Base} is the same
5468 as @code{typ}.
5469 @item
5470 Use of pragma @code{Pack} when all components are placed by a record
5471 representation clause.
5472 @item
5473 Exception handler containing only a reraise statement (raise with no
5474 operand) which has no effect.
5475 @item
5476 Use of the operator abs on an operand that is known at compile time
5477 to be non-negative
5478 @item
5479 Comparison of boolean expressions to an explicit True value.
5480 @end itemize
5481
5482 This warning can also be turned on using @option{-gnatwa}.
5483 The default is that warnings for redundant constructs are not given.
5484
5485 @item -gnatwR
5486 @emph{Suppress warnings on redundant constructs.}
5487 @cindex @option{-gnatwR} (@command{gcc})
5488 This switch suppresses warnings for redundant constructs.
5489
5490 @item -gnatw.r
5491 @emph{Activate warnings for object renaming function.}
5492 @cindex @option{-gnatw.r} (@command{gcc})
5493 This switch activates warnings for an object renaming that renames a
5494 function call, which is equivalent to a constant declaration (as
5495 opposed to renaming the function itself). The default is that these
5496 warnings are given. This warning can also be turned on using
5497 @option{-gnatwa}.
5498
5499 @item -gnatw.R
5500 @emph{Suppress warnings for object renaming function.}
5501 @cindex @option{-gnatwT} (@command{gcc})
5502 This switch suppresses warnings for object renaming function.
5503
5504 @item -gnatws
5505 @emph{Suppress all warnings.}
5506 @cindex @option{-gnatws} (@command{gcc})
5507 This switch completely suppresses the
5508 output of all warning messages from the GNAT front end, including
5509 both warnings that can be controlled by switches described in this
5510 section, and those that are normally given unconditionally. The
5511 effect of this suppress action can only be cancelled by a subsequent
5512 use of the switch @option{-gnatwn}.
5513
5514 Note that switch @option{-gnatws} does not suppress
5515 warnings from the @command{gcc} back end.
5516 To suppress these back end warnings as well, use the switch @option{-w}
5517 in addition to @option{-gnatws}. Also this switch has no effect on the
5518 handling of style check messages.
5519
5520 @item -gnatw.s
5521 @emph{Activate warnings on overridden size clauses.}
5522 @cindex @option{-gnatw.s} (@command{gcc})
5523 @cindex Record Representation (component sizes)
5524 This switch activates warnings on component clauses in record
5525 representation clauses where the length given overrides that
5526 specified by an explicit size clause for the component type. A
5527 warning is similarly given in the array case if a specified
5528 component size overrides an explicit size clause for the array
5529 component type.
5530 Note that @option{-gnatwa} does not affect the setting of this warning option.
5531
5532 @item -gnatw.S
5533 @emph{Suppress warnings on overridden size clauses.}
5534 @cindex @option{-gnatw.S} (@command{gcc})
5535 This switch suppresses warnings on component clauses in record
5536 representation clauses that override size clauses, and similar
5537 warnings when an array component size overrides a size clause.
5538
5539 @item -gnatwt
5540 @emph{Activate warnings for tracking of deleted conditional code.}
5541 @cindex @option{-gnatwt} (@command{gcc})
5542 @cindex Deactivated code, warnings
5543 @cindex Deleted code, warnings
5544 This switch activates warnings for tracking of code in conditionals (IF and
5545 CASE statements) that is detected to be dead code which cannot be executed, and
5546 which is removed by the front end. This warning is off by default, and is not
5547 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5548 useful for detecting deactivated code in certified applications.
5549
5550 @item -gnatwT
5551 @emph{Suppress warnings for tracking of deleted conditional code.}
5552 @cindex @option{-gnatwT} (@command{gcc})
5553 This switch suppresses warnings for tracking of deleted conditional code.
5554
5555 @item -gnatw.t
5556 @emph{Activate warnings on suspicious contracts.}
5557 @cindex @option{-gnatw.t} (@command{gcc})
5558 This switch activates warnings on suspicious postconditions (whether a
5559 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012)
5560 and suspicious contract cases (pragma @code{Contract_Cases}). A
5561 function postcondition or contract case is suspicious when no postcondition
5562 or contract case for this function mentions the result of the function.
5563 A procedure postcondition or contract case is suspicious when it only
5564 refers to the pre-state of the procedure, because in that case it should
5565 rather be expressed as a precondition. The default is that such warnings
5566 are not generated. This warning can also be turned on using @option{-gnatwa}.
5567
5568 @item -gnatw.T
5569 @emph{Suppress warnings on suspicious contracts.}
5570 @cindex @option{-gnatw.T} (@command{gcc})
5571 This switch suppresses warnings on suspicious postconditions.
5572
5573 @item -gnatwu
5574 @emph{Activate warnings on unused entities.}
5575 @cindex @option{-gnatwu} (@command{gcc})
5576 This switch activates warnings to be generated for entities that
5577 are declared but not referenced, and for units that are @code{with}'ed
5578 and not
5579 referenced. In the case of packages, a warning is also generated if
5580 no entities in the package are referenced. This means that if a with'ed
5581 package is referenced but the only references are in @code{use}
5582 clauses or @code{renames}
5583 declarations, a warning is still generated. A warning is also generated
5584 for a generic package that is @code{with}'ed but never instantiated.
5585 In the case where a package or subprogram body is compiled, and there
5586 is a @code{with} on the corresponding spec
5587 that is only referenced in the body,
5588 a warning is also generated, noting that the
5589 @code{with} can be moved to the body. The default is that
5590 such warnings are not generated.
5591 This switch also activates warnings on unreferenced formals
5592 (it includes the effect of @option{-gnatwf}).
5593 This warning can also be turned on using @option{-gnatwa}.
5594
5595 @item -gnatwU
5596 @emph{Suppress warnings on unused entities.}
5597 @cindex @option{-gnatwU} (@command{gcc})
5598 This switch suppresses warnings for unused entities and packages.
5599 It also turns off warnings on unreferenced formals (and thus includes
5600 the effect of @option{-gnatwF}).
5601
5602 @item -gnatw.u
5603 @emph{Activate warnings on unordered enumeration types.}
5604 @cindex @option{-gnatw.u} (@command{gcc})
5605 This switch causes enumeration types to be considered as conceptually
5606 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5607 The effect is to generate warnings in clients that use explicit comparisons
5608 or subranges, since these constructs both treat objects of the type as
5609 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5610 which the type is declared, or its body or subunits.) Please refer to
5611 the description of pragma @code{Ordered} in the
5612 @cite{@value{EDITION} Reference Manual} for further details.
5613 The default is that such warnings are not generated.
5614 This warning is not automatically turned on by the use of @option{-gnatwa}.
5615
5616 @item -gnatw.U
5617 @emph{Deactivate warnings on unordered enumeration types.}
5618 @cindex @option{-gnatw.U} (@command{gcc})
5619 This switch causes all enumeration types to be considered as ordered, so
5620 that no warnings are given for comparisons or subranges for any type.
5621
5622 @item -gnatwv
5623 @emph{Activate warnings on unassigned variables.}
5624 @cindex @option{-gnatwv} (@command{gcc})
5625 @cindex Unassigned variable warnings
5626 This switch activates warnings for access to variables which
5627 may not be properly initialized. The default is that
5628 such warnings are generated.
5629 This warning can also be turned on using @option{-gnatwa}.
5630
5631 @item -gnatwV
5632 @emph{Suppress warnings on unassigned variables.}
5633 @cindex @option{-gnatwV} (@command{gcc})
5634 This switch suppresses warnings for access to variables which
5635 may not be properly initialized.
5636 For variables of a composite type, the warning can also be suppressed in
5637 Ada 2005 by using a default initialization with a box. For example, if
5638 Table is an array of records whose components are only partially uninitialized,
5639 then the following code:
5640
5641 @smallexample @c ada
5642 Tab : Table := (others => <>);
5643 @end smallexample
5644
5645 will suppress warnings on subsequent statements that access components
5646 of variable Tab.
5647
5648 @item -gnatw.v
5649 @emph{Activate info messages for non-default bit order.}
5650 @cindex @option{-gnatw.v} (@command{gcc})
5651 @cindex bit order warnings
5652 This switch activates messages (labeled "info", they are not warnings,
5653 just informational messages) about the effects of non-default bit-order
5654 on records to which a component clause is applied. The effect of specifying
5655 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
5656 these messages, which are given by default, are useful in understanding the
5657 exact consequences of using this feature. These messages
5658 can also be turned on using @option{-gnatwa}
5659
5660 @item -gnatw.V
5661 @emph{Suppress info messages for non-default bit order.}
5662 @cindex @option{-gnatw.V} (@command{gcc})
5663 This switch suppresses information messages for the effects of specifying
5664 non-default bit order on record components with component clauses.
5665
5666 @item -gnatww
5667 @emph{Activate warnings on wrong low bound assumption.}
5668 @cindex @option{-gnatww} (@command{gcc})
5669 @cindex String indexing warnings
5670 This switch activates warnings for indexing an unconstrained string parameter
5671 with a literal or S'Length. This is a case where the code is assuming that the
5672 low bound is one, which is in general not true (for example when a slice is
5673 passed). The default is that such warnings are generated.
5674 This warning can also be turned on using @option{-gnatwa}.
5675
5676 @item -gnatwW
5677 @emph{Suppress warnings on wrong low bound assumption.}
5678 @cindex @option{-gnatwW} (@command{gcc})
5679 This switch suppresses warnings for indexing an unconstrained string parameter
5680 with a literal or S'Length. Note that this warning can also be suppressed
5681 in a particular case by adding an
5682 assertion that the lower bound is 1,
5683 as shown in the following example.
5684
5685 @smallexample @c ada
5686 procedure K (S : String) is
5687 pragma Assert (S'First = 1);
5688 @dots{}
5689 @end smallexample
5690
5691 @item -gnatw.w
5692 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5693 @cindex @option{-gnatw.w} (@command{gcc})
5694 @cindex Warnings Off control
5695 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5696 where either the pragma is entirely useless (because it suppresses no
5697 warnings), or it could be replaced by @code{pragma Unreferenced} or
5698 @code{pragma Unmodified}. The default is that these warnings are not given.
5699 Note that this warning is not included in -gnatwa, it must be
5700 activated explicitly.
5701
5702 @item -gnatw.W
5703 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5704 @cindex @option{-gnatw.W} (@command{gcc})
5705 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity)}.
5706
5707 @item -gnatwx
5708 @emph{Activate warnings on Export/Import pragmas.}
5709 @cindex @option{-gnatwx} (@command{gcc})
5710 @cindex Export/Import pragma warnings
5711 This switch activates warnings on Export/Import pragmas when
5712 the compiler detects a possible conflict between the Ada and
5713 foreign language calling sequences. For example, the use of
5714 default parameters in a convention C procedure is dubious
5715 because the C compiler cannot supply the proper default, so
5716 a warning is issued. The default is that such warnings are
5717 generated.
5718 This warning can also be turned on using @option{-gnatwa}.
5719
5720 @item -gnatwX
5721 @emph{Suppress warnings on Export/Import pragmas.}
5722 @cindex @option{-gnatwX} (@command{gcc})
5723 This switch suppresses warnings on Export/Import pragmas.
5724 The sense of this is that you are telling the compiler that
5725 you know what you are doing in writing the pragma, and it
5726 should not complain at you.
5727
5728 @item -gnatw.x
5729 @emph{Activate warnings for No_Exception_Propagation mode.}
5730 @cindex @option{-gnatwm} (@command{gcc})
5731 This switch activates warnings for exception usage when pragma Restrictions
5732 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5733 explicit exception raises which are not covered by a local handler, and for
5734 exception handlers which do not cover a local raise. The default is that these
5735 warnings are not given.
5736
5737 @item -gnatw.X
5738 @emph{Disable warnings for No_Exception_Propagation mode.}
5739 This switch disables warnings for exception usage when pragma Restrictions
5740 (No_Exception_Propagation) is in effect.
5741
5742 @item -gnatwy
5743 @emph{Activate warnings for Ada compatibility issues.}
5744 @cindex @option{-gnatwy} (@command{gcc})
5745 @cindex Ada compatibility issues warnings
5746 For the most part, newer versions of Ada are upwards compatible
5747 with older versions. For example, Ada 2005 programs will almost
5748 always work when compiled as Ada 2012.
5749 However there are some exceptions (for example the fact that
5750 @code{some} is now a reserved word in Ada 2012). This
5751 switch activates several warnings to help in identifying
5752 and correcting such incompatibilities. The default is that
5753 these warnings are generated. Note that at one point Ada 2005
5754 was called Ada 0Y, hence the choice of character.
5755 This warning can also be turned on using @option{-gnatwa}.
5756
5757 @item -gnatwY
5758 @emph{Disable warnings for Ada compatibility issues.}
5759 @cindex @option{-gnatwY} (@command{gcc})
5760 @cindex Ada compatibility issues warnings
5761 This switch suppresses the warnings intended to help in identifying
5762 incompatibilities between Ada language versions.
5763
5764 @item -gnatw.y
5765 @emph{Activate information messages for why package spec needs body}
5766 @cindex @option{-gnatw.y} (@command{gcc})
5767 @cindex Package spec needing body
5768 There are a number of cases in which a package spec needs a body.
5769 For example, the use of pragma Elaborate_Body, or the declaration
5770 of a procedure specification requiring a completion. This switch
5771 causes information messages to be output showing why a package
5772 specification requires a body. This can be useful in the case of
5773 a large package specification which is unexpectedly requiring a
5774 body. The default is that such information messages are not output.
5775
5776 @item -gnatw.Y
5777 @emph{Disable information messages for why package spec needs body}
5778 @cindex @option{-gnatw.Y} (@command{gcc})
5779 @cindex No information messages for why package spec needs body
5780 This switch suppresses the output of information messages showing why
5781 a package specification needs a body.
5782
5783 @item -gnatwz
5784 @emph{Activate warnings on unchecked conversions.}
5785 @cindex @option{-gnatwz} (@command{gcc})
5786 @cindex Unchecked_Conversion warnings
5787 This switch activates warnings for unchecked conversions
5788 where the types are known at compile time to have different
5789 sizes. The default
5790 is that such warnings are generated. Warnings are also
5791 generated for subprogram pointers with different conventions,
5792 and, on VMS only, for data pointers with different conventions.
5793 This warning can also be turned on using @option{-gnatwa}.
5794
5795 @item -gnatwZ
5796 @emph{Suppress warnings on unchecked conversions.}
5797 @cindex @option{-gnatwZ} (@command{gcc})
5798 This switch suppresses warnings for unchecked conversions
5799 where the types are known at compile time to have different
5800 sizes or conventions.
5801
5802 @item ^-Wunused^WARNINGS=UNUSED^
5803 @cindex @option{-Wunused}
5804 The warnings controlled by the @option{-gnatw} switch are generated by
5805 the front end of the compiler. The @option{GCC} back end can provide
5806 additional warnings and they are controlled by the @option{-W} switch.
5807 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5808 warnings for entities that are declared but not referenced.
5809
5810 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5811 @cindex @option{-Wuninitialized}
5812 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5813 the back end warning for uninitialized variables. This switch must be
5814 used in conjunction with an optimization level greater than zero.
5815
5816 @item -Wstack-usage=@var{len}
5817 @cindex @option{-Wstack-usage}
5818 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5819 See @ref{Static Stack Usage Analysis} for details.
5820
5821 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5822 @cindex @option{-Wall}
5823 This switch enables most warnings from the @option{GCC} back end.
5824 The code generator detects a number of warning situations that are missed
5825 by the @option{GNAT} front end, and this switch can be used to activate them.
5826 The use of this switch also sets the default front end warning mode to
5827 @option{-gnatwa}, that is, most front end warnings activated as well.
5828
5829 @item ^-w^/NO_BACK_END_WARNINGS^
5830 @cindex @option{-w}
5831 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5832 The use of this switch also sets the default front end warning mode to
5833 @option{-gnatws}, that is, front end warnings suppressed as well.
5834
5835 @end table
5836
5837 @noindent
5838 @ifclear vms
5839 A string of warning parameters can be used in the same parameter. For example:
5840
5841 @smallexample
5842 -gnatwaGe
5843 @end smallexample
5844
5845 @noindent
5846 will turn on all optional warnings except for unrecognized pragma warnings,
5847 and also specify that warnings should be treated as errors.
5848 @end ifclear
5849
5850 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5851
5852 @table @option
5853 @c !sort!
5854 @item -gnatw.a
5855 @item -gnatwB
5856 @item -gnatw.b
5857 @item -gnatwC
5858 @item -gnatw.C
5859 @item -gnatwD
5860 @item -gnatwF
5861 @item -gnatwg
5862 @item -gnatwH
5863 @item -gnatwi
5864 @item -gnatw.I
5865 @item -gnatwJ
5866 @item -gnatwK
5867 @item -gnatwL
5868 @item -gnatw.L
5869 @item -gnatwM
5870 @item -gnatw.m
5871 @item -gnatwn
5872 @item -gnatwo
5873 @item -gnatw.O
5874 @item -gnatwP
5875 @item -gnatw.P
5876 @item -gnatwq
5877 @item -gnatwR
5878 @item -gnatw.R
5879 @item -gnatw.S
5880 @item -gnatwT
5881 @item -gnatw.T
5882 @item -gnatwU
5883 @item -gnatwv
5884 @item -gnatww
5885 @item -gnatw.W
5886 @item -gnatwx
5887 @item -gnatw.X
5888 @item -gnatwy
5889 @item -gnatwz
5890
5891 @end table
5892
5893 @node Debugging and Assertion Control
5894 @subsection Debugging and Assertion Control
5895
5896 @table @option
5897 @item -gnata
5898 @cindex @option{-gnata} (@command{gcc})
5899 @findex Assert
5900 @findex Debug
5901 @cindex Assertions
5902
5903 @noindent
5904 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5905 are ignored. This switch, where @samp{a} stands for assert, causes
5906 @code{Assert} and @code{Debug} pragmas to be activated.
5907
5908 The pragmas have the form:
5909
5910 @smallexample
5911 @cartouche
5912 @b{pragma} Assert (@var{Boolean-expression} @r{[},
5913 @var{static-string-expression}@r{]})
5914 @b{pragma} Debug (@var{procedure call})
5915 @end cartouche
5916 @end smallexample
5917
5918 @noindent
5919 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5920 If the result is @code{True}, the pragma has no effect (other than
5921 possible side effects from evaluating the expression). If the result is
5922 @code{False}, the exception @code{Assert_Failure} declared in the package
5923 @code{System.Assertions} is
5924 raised (passing @var{static-string-expression}, if present, as the
5925 message associated with the exception). If no string expression is
5926 given the default is a string giving the file name and line number
5927 of the pragma.
5928
5929 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5930 @code{pragma Debug} may appear within a declaration sequence, allowing
5931 debugging procedures to be called between declarations.
5932
5933 @ifset vms
5934 @item /DEBUG@r{[}=debug-level@r{]}
5935 @itemx /NODEBUG
5936 Specifies how much debugging information is to be included in
5937 the resulting object file where 'debug-level' is one of the following:
5938 @table @code
5939 @item TRACEBACK
5940 Include both debugger symbol records and traceback
5941 the object file.
5942 This is the default setting.
5943 @item ALL
5944 Include both debugger symbol records and traceback in
5945 object file.
5946 @item NONE
5947 Excludes both debugger symbol records and traceback
5948 the object file. Same as /NODEBUG.
5949 @item SYMBOLS
5950 Includes only debugger symbol records in the object
5951 file. Note that this doesn't include traceback information.
5952 @end table
5953 @end ifset
5954 @end table
5955
5956 @node Validity Checking
5957 @subsection Validity Checking
5958 @findex Validity Checking
5959
5960 @noindent
5961 The Ada Reference Manual defines the concept of invalid values (see
5962 RM 13.9.1). The primary source of invalid values is uninitialized
5963 variables. A scalar variable that is left uninitialized may contain
5964 an invalid value; the concept of invalid does not apply to access or
5965 composite types.
5966
5967 It is an error to read an invalid value, but the RM does not require
5968 run-time checks to detect such errors, except for some minimal
5969 checking to prevent erroneous execution (i.e. unpredictable
5970 behavior). This corresponds to the @option{-gnatVd} switch below,
5971 which is the default. For example, by default, if the expression of a
5972 case statement is invalid, it will raise Constraint_Error rather than
5973 causing a wild jump, and if an array index on the left-hand side of an
5974 assignment is invalid, it will raise Constraint_Error rather than
5975 overwriting an arbitrary memory location.
5976
5977 The @option{-gnatVa} may be used to enable additional validity checks,
5978 which are not required by the RM. These checks are often very
5979 expensive (which is why the RM does not require them). These checks
5980 are useful in tracking down uninitialized variables, but they are
5981 not usually recommended for production builds.
5982
5983 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5984 control; you can enable whichever validity checks you desire. However,
5985 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5986 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5987 sufficient for non-debugging use.
5988
5989 The @option{-gnatB} switch tells the compiler to assume that all
5990 values are valid (that is, within their declared subtype range)
5991 except in the context of a use of the Valid attribute. This means
5992 the compiler can generate more efficient code, since the range
5993 of values is better known at compile time. However, an uninitialized
5994 variable can cause wild jumps and memory corruption in this mode.
5995
5996 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5997 checking mode as described below.
5998 @ifclear vms
5999 The @code{x} argument is a string of letters that
6000 indicate validity checks that are performed or not performed in addition
6001 to the default checks required by Ada as described above.
6002 @end ifclear
6003 @ifset vms
6004 The options allowed for this qualifier
6005 indicate validity checks that are performed or not performed in addition
6006 to the default checks required by Ada as described above.
6007 @end ifset
6008
6009 @table @option
6010 @c !sort!
6011 @item -gnatVa
6012 @emph{All validity checks.}
6013 @cindex @option{-gnatVa} (@command{gcc})
6014 All validity checks are turned on.
6015 @ifclear vms
6016 That is, @option{-gnatVa} is
6017 equivalent to @option{gnatVcdfimorst}.
6018 @end ifclear
6019
6020 @item -gnatVc
6021 @emph{Validity checks for copies.}
6022 @cindex @option{-gnatVc} (@command{gcc})
6023 The right hand side of assignments, and the initializing values of
6024 object declarations are validity checked.
6025
6026 @item -gnatVd
6027 @emph{Default (RM) validity checks.}
6028 @cindex @option{-gnatVd} (@command{gcc})
6029 Some validity checks are done by default following normal Ada semantics
6030 (RM 13.9.1 (9-11)).
6031 A check is done in case statements that the expression is within the range
6032 of the subtype. If it is not, Constraint_Error is raised.
6033 For assignments to array components, a check is done that the expression used
6034 as index is within the range. If it is not, Constraint_Error is raised.
6035 Both these validity checks may be turned off using switch @option{-gnatVD}.
6036 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6037 switch @option{-gnatVd} will leave the checks turned on.
6038 Switch @option{-gnatVD} should be used only if you are sure that all such
6039 expressions have valid values. If you use this switch and invalid values
6040 are present, then the program is erroneous, and wild jumps or memory
6041 overwriting may occur.
6042
6043 @item -gnatVe
6044 @emph{Validity checks for elementary components.}
6045 @cindex @option{-gnatVe} (@command{gcc})
6046 In the absence of this switch, assignments to record or array components are
6047 not validity checked, even if validity checks for assignments generally
6048 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6049 require valid data, but assignment of individual components does. So for
6050 example, there is a difference between copying the elements of an array with a
6051 slice assignment, compared to assigning element by element in a loop. This
6052 switch allows you to turn off validity checking for components, even when they
6053 are assigned component by component.
6054
6055 @item -gnatVf
6056 @emph{Validity checks for floating-point values.}
6057 @cindex @option{-gnatVf} (@command{gcc})
6058 In the absence of this switch, validity checking occurs only for discrete
6059 values. If @option{-gnatVf} is specified, then validity checking also applies
6060 for floating-point values, and NaNs and infinities are considered invalid,
6061 as well as out of range values for constrained types. Note that this means
6062 that standard IEEE infinity mode is not allowed. The exact contexts
6063 in which floating-point values are checked depends on the setting of other
6064 options. For example,
6065 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6066 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6067 (the order does not matter) specifies that floating-point parameters of mode
6068 @code{in} should be validity checked.
6069
6070 @item -gnatVi
6071 @emph{Validity checks for @code{in} mode parameters}
6072 @cindex @option{-gnatVi} (@command{gcc})
6073 Arguments for parameters of mode @code{in} are validity checked in function
6074 and procedure calls at the point of call.
6075
6076 @item -gnatVm
6077 @emph{Validity checks for @code{in out} mode parameters.}
6078 @cindex @option{-gnatVm} (@command{gcc})
6079 Arguments for parameters of mode @code{in out} are validity checked in
6080 procedure calls at the point of call. The @code{'m'} here stands for
6081 modify, since this concerns parameters that can be modified by the call.
6082 Note that there is no specific option to test @code{out} parameters,
6083 but any reference within the subprogram will be tested in the usual
6084 manner, and if an invalid value is copied back, any reference to it
6085 will be subject to validity checking.
6086
6087 @item -gnatVn
6088 @emph{No validity checks.}
6089 @cindex @option{-gnatVn} (@command{gcc})
6090 This switch turns off all validity checking, including the default checking
6091 for case statements and left hand side subscripts. Note that the use of
6092 the switch @option{-gnatp} suppresses all run-time checks, including
6093 validity checks, and thus implies @option{-gnatVn}. When this switch
6094 is used, it cancels any other @option{-gnatV} previously issued.
6095
6096 @item -gnatVo
6097 @emph{Validity checks for operator and attribute operands.}
6098 @cindex @option{-gnatVo} (@command{gcc})
6099 Arguments for predefined operators and attributes are validity checked.
6100 This includes all operators in package @code{Standard},
6101 the shift operators defined as intrinsic in package @code{Interfaces}
6102 and operands for attributes such as @code{Pos}. Checks are also made
6103 on individual component values for composite comparisons, and on the
6104 expressions in type conversions and qualified expressions. Checks are
6105 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6106
6107 @item -gnatVp
6108 @emph{Validity checks for parameters.}
6109 @cindex @option{-gnatVp} (@command{gcc})
6110 This controls the treatment of parameters within a subprogram (as opposed
6111 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6112 of parameters on a call. If either of these call options is used, then
6113 normally an assumption is made within a subprogram that the input arguments
6114 have been validity checking at the point of call, and do not need checking
6115 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6116 is not made, and parameters are not assumed to be valid, so their validity
6117 will be checked (or rechecked) within the subprogram.
6118
6119 @item -gnatVr
6120 @emph{Validity checks for function returns.}
6121 @cindex @option{-gnatVr} (@command{gcc})
6122 The expression in @code{return} statements in functions is validity
6123 checked.
6124
6125 @item -gnatVs
6126 @emph{Validity checks for subscripts.}
6127 @cindex @option{-gnatVs} (@command{gcc})
6128 All subscripts expressions are checked for validity, whether they appear
6129 on the right side or left side (in default mode only left side subscripts
6130 are validity checked).
6131
6132 @item -gnatVt
6133 @emph{Validity checks for tests.}
6134 @cindex @option{-gnatVt} (@command{gcc})
6135 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6136 statements are checked, as well as guard expressions in entry calls.
6137
6138 @end table
6139
6140 @noindent
6141 The @option{-gnatV} switch may be followed by
6142 ^a string of letters^a list of options^
6143 to turn on a series of validity checking options.
6144 For example,
6145 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6146 specifies that in addition to the default validity checking, copies and
6147 function return expressions are to be validity checked.
6148 In order to make it easier
6149 to specify the desired combination of effects,
6150 @ifclear vms
6151 the upper case letters @code{CDFIMORST} may
6152 be used to turn off the corresponding lower case option.
6153 @end ifclear
6154 @ifset vms
6155 the prefix @code{NO} on an option turns off the corresponding validity
6156 checking:
6157 @itemize @bullet
6158 @item @code{NOCOPIES}
6159 @item @code{NODEFAULT}
6160 @item @code{NOFLOATS}
6161 @item @code{NOIN_PARAMS}
6162 @item @code{NOMOD_PARAMS}
6163 @item @code{NOOPERANDS}
6164 @item @code{NORETURNS}
6165 @item @code{NOSUBSCRIPTS}
6166 @item @code{NOTESTS}
6167 @end itemize
6168 @end ifset
6169 Thus
6170 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6171 turns on all validity checking options except for
6172 checking of @code{@b{in out}} procedure arguments.
6173
6174 The specification of additional validity checking generates extra code (and
6175 in the case of @option{-gnatVa} the code expansion can be substantial).
6176 However, these additional checks can be very useful in detecting
6177 uninitialized variables, incorrect use of unchecked conversion, and other
6178 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6179 is useful in conjunction with the extra validity checking, since this
6180 ensures that wherever possible uninitialized variables have invalid values.
6181
6182 See also the pragma @code{Validity_Checks} which allows modification of
6183 the validity checking mode at the program source level, and also allows for
6184 temporary disabling of validity checks.
6185
6186 @node Style Checking
6187 @subsection Style Checking
6188 @findex Style checking
6189
6190 @noindent
6191 The @option{-gnaty^x^(option,option,@dots{})^} switch
6192 @cindex @option{-gnaty} (@command{gcc})
6193 causes the compiler to
6194 enforce specified style rules. A limited set of style rules has been used
6195 in writing the GNAT sources themselves. This switch allows user programs
6196 to activate all or some of these checks. If the source program fails a
6197 specified style check, an appropriate message is given, preceded by
6198 the character sequence ``(style)''. This message does not prevent
6199 successful compilation (unless the @option{-gnatwe} switch is used).
6200
6201 Note that this is by no means intended to be a general facility for
6202 checking arbitrary coding standards. It is simply an embedding of the
6203 style rules we have chosen for the GNAT sources. If you are starting
6204 a project which does not have established style standards, you may
6205 find it useful to adopt the entire set of GNAT coding standards, or
6206 some subset of them. If you already have an established set of coding
6207 standards, then it may be that selected style checking options do
6208 indeed correspond to choices you have made, but for general checking
6209 of an existing set of coding rules, you should look to the gnatcheck
6210 tool, which is designed for that purpose.
6211
6212 @ifset vms
6213 @code{(option,option,@dots{})} is a sequence of keywords
6214 @end ifset
6215 @ifclear vms
6216 The string @var{x} is a sequence of letters or digits
6217 @end ifclear
6218 indicating the particular style
6219 checks to be performed. The following checks are defined:
6220
6221 @table @option
6222 @c !sort!
6223 @item 0-9
6224 @emph{Specify indentation level.}
6225 If a digit from 1-9 appears
6226 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6227 then proper indentation is checked, with the digit indicating the
6228 indentation level required. A value of zero turns off this style check.
6229 The general style of required indentation is as specified by
6230 the examples in the Ada Reference Manual. Full line comments must be
6231 aligned with the @code{--} starting on a column that is a multiple of
6232 the alignment level, or they may be aligned the same way as the following
6233 non-blank line (this is useful when full line comments appear in the middle
6234 of a statement, or they may be aligned with the source line on the previous
6235 non-blank line.
6236
6237 @item ^a^ATTRIBUTE^
6238 @emph{Check attribute casing.}
6239 Attribute names, including the case of keywords such as @code{digits}
6240 used as attributes names, must be written in mixed case, that is, the
6241 initial letter and any letter following an underscore must be uppercase.
6242 All other letters must be lowercase.
6243
6244 @item ^A^ARRAY_INDEXES^
6245 @emph{Use of array index numbers in array attributes.}
6246 When using the array attributes First, Last, Range,
6247 or Length, the index number must be omitted for one-dimensional arrays
6248 and is required for multi-dimensional arrays.
6249
6250 @item ^b^BLANKS^
6251 @emph{Blanks not allowed at statement end.}
6252 Trailing blanks are not allowed at the end of statements. The purpose of this
6253 rule, together with h (no horizontal tabs), is to enforce a canonical format
6254 for the use of blanks to separate source tokens.
6255
6256 @item ^B^BOOLEAN_OPERATORS^
6257 @emph{Check Boolean operators.}
6258 The use of AND/OR operators is not permitted except in the cases of modular
6259 operands, array operands, and simple stand-alone boolean variables or
6260 boolean constants. In all other cases @code{and then}/@code{or else} are
6261 required.
6262
6263 @item ^c^COMMENTS^
6264 @emph{Check comments, double space.}
6265 Comments must meet the following set of rules:
6266
6267 @itemize @bullet
6268
6269 @item
6270 The ``@code{--}'' that starts the column must either start in column one,
6271 or else at least one blank must precede this sequence.
6272
6273 @item
6274 Comments that follow other tokens on a line must have at least one blank
6275 following the ``@code{--}'' at the start of the comment.
6276
6277 @item
6278 Full line comments must have at least two blanks following the
6279 ``@code{--}'' that starts the comment, with the following exceptions.
6280
6281 @item
6282 A line consisting only of the ``@code{--}'' characters, possibly preceded
6283 by blanks is permitted.
6284
6285 @item
6286 A comment starting with ``@code{--x}'' where @code{x} is a special character
6287 is permitted.
6288 This allows proper processing of the output generated by specialized tools
6289 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6290 annotation
6291 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6292 special character is defined as being in one of the ASCII ranges
6293 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6294 Note that this usage is not permitted
6295 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6296
6297 @item
6298 A line consisting entirely of minus signs, possibly preceded by blanks, is
6299 permitted. This allows the construction of box comments where lines of minus
6300 signs are used to form the top and bottom of the box.
6301
6302 @item
6303 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6304 least one blank follows the initial ``@code{--}''. Together with the preceding
6305 rule, this allows the construction of box comments, as shown in the following
6306 example:
6307 @smallexample
6308 ---------------------------
6309 -- This is a box comment --
6310 -- with two text lines. --
6311 ---------------------------
6312 @end smallexample
6313 @end itemize
6314
6315 @item ^C^COMMENTS1^
6316 @emph{Check comments, single space.}
6317 This is identical to @code{^c^COMMENTS^} except that only one space
6318 is required following the @code{--} of a comment instead of two.
6319
6320 @item ^d^DOS_LINE_ENDINGS^
6321 @emph{Check no DOS line terminators present.}
6322 All lines must be terminated by a single ASCII.LF
6323 character (in particular the DOS line terminator sequence CR/LF is not
6324 allowed).
6325
6326 @item ^e^END^
6327 @emph{Check end/exit labels.}
6328 Optional labels on @code{end} statements ending subprograms and on
6329 @code{exit} statements exiting named loops, are required to be present.
6330
6331 @item ^f^VTABS^
6332 @emph{No form feeds or vertical tabs.}
6333 Neither form feeds nor vertical tab characters are permitted
6334 in the source text.
6335
6336 @item ^g^GNAT^
6337 @emph{GNAT style mode.}
6338 The set of style check switches is set to match that used by the GNAT sources.
6339 This may be useful when developing code that is eventually intended to be
6340 incorporated into GNAT. For further details, see GNAT sources.
6341
6342 @item ^h^HTABS^
6343 @emph{No horizontal tabs.}
6344 Horizontal tab characters are not permitted in the source text.
6345 Together with the b (no blanks at end of line) check, this
6346 enforces a canonical form for the use of blanks to separate
6347 source tokens.
6348
6349 @item ^i^IF_THEN^
6350 @emph{Check if-then layout.}
6351 The keyword @code{then} must appear either on the same
6352 line as corresponding @code{if}, or on a line on its own, lined
6353 up under the @code{if} with at least one non-blank line in between
6354 containing all or part of the condition to be tested.
6355
6356 @item ^I^IN_MODE^
6357 @emph{check mode IN keywords.}
6358 Mode @code{in} (the default mode) is not
6359 allowed to be given explicitly. @code{in out} is fine,
6360 but not @code{in} on its own.
6361
6362 @item ^k^KEYWORD^
6363 @emph{Check keyword casing.}
6364 All keywords must be in lower case (with the exception of keywords
6365 such as @code{digits} used as attribute names to which this check
6366 does not apply).
6367
6368 @item ^l^LAYOUT^
6369 @emph{Check layout.}
6370 Layout of statement and declaration constructs must follow the
6371 recommendations in the Ada Reference Manual, as indicated by the
6372 form of the syntax rules. For example an @code{else} keyword must
6373 be lined up with the corresponding @code{if} keyword.
6374
6375 There are two respects in which the style rule enforced by this check
6376 option are more liberal than those in the Ada Reference Manual. First
6377 in the case of record declarations, it is permissible to put the
6378 @code{record} keyword on the same line as the @code{type} keyword, and
6379 then the @code{end} in @code{end record} must line up under @code{type}.
6380 This is also permitted when the type declaration is split on two lines.
6381 For example, any of the following three layouts is acceptable:
6382
6383 @smallexample @c ada
6384 @cartouche
6385 type q is record
6386 a : integer;
6387 b : integer;
6388 end record;
6389
6390 type q is
6391 record
6392 a : integer;
6393 b : integer;
6394 end record;
6395
6396 type q is
6397 record
6398 a : integer;
6399 b : integer;
6400 end record;
6401
6402 @end cartouche
6403 @end smallexample
6404
6405 @noindent
6406 Second, in the case of a block statement, a permitted alternative
6407 is to put the block label on the same line as the @code{declare} or
6408 @code{begin} keyword, and then line the @code{end} keyword up under
6409 the block label. For example both the following are permitted:
6410
6411 @smallexample @c ada
6412 @cartouche
6413 Block : declare
6414 A : Integer := 3;
6415 begin
6416 Proc (A, A);
6417 end Block;
6418
6419 Block :
6420 declare
6421 A : Integer := 3;
6422 begin
6423 Proc (A, A);
6424 end Block;
6425 @end cartouche
6426 @end smallexample
6427
6428 @noindent
6429 The same alternative format is allowed for loops. For example, both of
6430 the following are permitted:
6431
6432 @smallexample @c ada
6433 @cartouche
6434 Clear : while J < 10 loop
6435 A (J) := 0;
6436 end loop Clear;
6437
6438 Clear :
6439 while J < 10 loop
6440 A (J) := 0;
6441 end loop Clear;
6442 @end cartouche
6443 @end smallexample
6444
6445 @item ^Lnnn^MAX_NESTING=nnn^
6446 @emph{Set maximum nesting level.}
6447 The maximum level of nesting of constructs (including subprograms, loops,
6448 blocks, packages, and conditionals) may not exceed the given value
6449 @option{nnn}. A value of zero disconnects this style check.
6450
6451 @item ^m^LINE_LENGTH^
6452 @emph{Check maximum line length.}
6453 The length of source lines must not exceed 79 characters, including
6454 any trailing blanks. The value of 79 allows convenient display on an
6455 80 character wide device or window, allowing for possible special
6456 treatment of 80 character lines. Note that this count is of
6457 characters in the source text. This means that a tab character counts
6458 as one character in this count and a wide character sequence counts as
6459 a single character (however many bytes are needed in the encoding).
6460
6461 @item ^Mnnn^MAX_LENGTH=nnn^
6462 @emph{Set maximum line length.}
6463 The length of lines must not exceed the
6464 given value @option{nnn}. The maximum value that can be specified is 32767.
6465 If neither style option for setting the line length is used, then the
6466 default is 255. This also controls the maximum length of lexical elements,
6467 where the only restriction is that they must fit on a single line.
6468
6469 @item ^n^STANDARD_CASING^
6470 @emph{Check casing of entities in Standard.}
6471 Any identifier from Standard must be cased
6472 to match the presentation in the Ada Reference Manual (for example,
6473 @code{Integer} and @code{ASCII.NUL}).
6474
6475 @item ^N^NONE^
6476 @emph{Turn off all style checks.}
6477 All style check options are turned off.
6478
6479 @item ^o^ORDERED_SUBPROGRAMS^
6480 @emph{Check order of subprogram bodies.}
6481 All subprogram bodies in a given scope
6482 (e.g.@: a package body) must be in alphabetical order. The ordering
6483 rule uses normal Ada rules for comparing strings, ignoring casing
6484 of letters, except that if there is a trailing numeric suffix, then
6485 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6486 before Junk10).
6487
6488 @item ^O^OVERRIDING_INDICATORS^
6489 @emph{Check that overriding subprograms are explicitly marked as such.}
6490 The declaration of a primitive operation of a type extension that overrides
6491 an inherited operation must carry an overriding indicator.
6492
6493 @item ^p^PRAGMA^
6494 @emph{Check pragma casing.}
6495 Pragma names must be written in mixed case, that is, the
6496 initial letter and any letter following an underscore must be uppercase.
6497 All other letters must be lowercase.
6498
6499 @item ^r^REFERENCES^
6500 @emph{Check references.}
6501 All identifier references must be cased in the same way as the
6502 corresponding declaration. No specific casing style is imposed on
6503 identifiers. The only requirement is for consistency of references
6504 with declarations.
6505
6506 @item ^s^SPECS^
6507 @emph{Check separate specs.}
6508 Separate declarations (``specs'') are required for subprograms (a
6509 body is not allowed to serve as its own declaration). The only
6510 exception is that parameterless library level procedures are
6511 not required to have a separate declaration. This exception covers
6512 the most frequent form of main program procedures.
6513
6514 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6515 @emph{Check no statements after @code{then}/@code{else}.}
6516 No statements are allowed
6517 on the same line as a @code{then} or @code{else} keyword following the
6518 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6519 affected, and a special exception allows a pragma to appear after @code{else}.
6520
6521 @item ^t^TOKEN^
6522 @emph{Check token spacing.}
6523 The following token spacing rules are enforced:
6524
6525 @itemize @bullet
6526
6527 @item
6528 The keywords @code{abs} and @code{not} must be followed by a space.
6529
6530 @item
6531 The token @code{=>} must be surrounded by spaces.
6532
6533 @item
6534 The token @code{<>} must be preceded by a space or a left parenthesis.
6535
6536 @item
6537 Binary operators other than @code{**} must be surrounded by spaces.
6538 There is no restriction on the layout of the @code{**} binary operator.
6539
6540 @item
6541 Colon must be surrounded by spaces.
6542
6543 @item
6544 Colon-equal (assignment, initialization) must be surrounded by spaces.
6545
6546 @item
6547 Comma must be the first non-blank character on the line, or be
6548 immediately preceded by a non-blank character, and must be followed
6549 by a space.
6550
6551 @item
6552 If the token preceding a left parenthesis ends with a letter or digit, then
6553 a space must separate the two tokens.
6554
6555 @item
6556 if the token following a right parenthesis starts with a letter or digit, then
6557 a space must separate the two tokens.
6558
6559 @item
6560 A right parenthesis must either be the first non-blank character on
6561 a line, or it must be preceded by a non-blank character.
6562
6563 @item
6564 A semicolon must not be preceded by a space, and must not be followed by
6565 a non-blank character.
6566
6567 @item
6568 A unary plus or minus may not be followed by a space.
6569
6570 @item
6571 A vertical bar must be surrounded by spaces.
6572 @end itemize
6573
6574 @item
6575 Exactly one blank (and no other white space) must appear between
6576 a @code{not} token and a following @code{in} token.
6577
6578 @item ^u^UNNECESSARY_BLANK_LINES^
6579 @emph{Check unnecessary blank lines.}
6580 Unnecessary blank lines are not allowed. A blank line is considered
6581 unnecessary if it appears at the end of the file, or if more than
6582 one blank line occurs in sequence.
6583
6584 @item ^x^XTRA_PARENS^
6585 @emph{Check extra parentheses.}
6586 Unnecessary extra level of parentheses (C-style) are not allowed
6587 around conditions in @code{if} statements, @code{while} statements and
6588 @code{exit} statements.
6589
6590 @item ^y^ALL_BUILTIN^
6591 @emph{Set all standard style check options}
6592 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6593 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6594 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6595 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6596
6597 @ifclear vms
6598 @item -
6599 @emph{Remove style check options}
6600 This causes any subsequent options in the string to act as canceling the
6601 corresponding style check option. To cancel maximum nesting level control,
6602 use @option{L} parameter witout any integer value after that, because any
6603 digit following @option{-} in the parameter string of the @option{-gnaty}
6604 option will be threated as canceling indentation check. The same is true
6605 for @option{M} parameter. @option{y} and @option{N} parameters are not
6606 allowed after @option{-}.
6607
6608 @item +
6609 This causes any subsequent options in the string to enable the corresponding
6610 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6611 if any.
6612 @end ifclear
6613
6614 @ifset vms
6615 @item NOxxx
6616 @emph{Removing style check options}
6617 If the name of a style check is preceded by @option{NO} then the corresponding
6618 style check is turned off. For example @option{NOCOMMENTS} turns off style
6619 checking for comments.
6620 @end ifset
6621 @end table
6622
6623 @noindent
6624 In the above rules, appearing in column one is always permitted, that is,
6625 counts as meeting either a requirement for a required preceding space,
6626 or as meeting a requirement for no preceding space.
6627
6628 Appearing at the end of a line is also always permitted, that is, counts
6629 as meeting either a requirement for a following space, or as meeting
6630 a requirement for no following space.
6631
6632 @noindent
6633 If any of these style rules is violated, a message is generated giving
6634 details on the violation. The initial characters of such messages are
6635 always ``@code{(style)}''. Note that these messages are treated as warning
6636 messages, so they normally do not prevent the generation of an object
6637 file. The @option{-gnatwe} switch can be used to treat warning messages,
6638 including style messages, as fatal errors.
6639
6640 The switch
6641 @ifclear vms
6642 @option{-gnaty} on its own (that is not
6643 followed by any letters or digits) is equivalent
6644 to the use of @option{-gnatyy} as described above, that is all
6645 built-in standard style check options are enabled.
6646
6647 @end ifclear
6648 @ifset vms
6649 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6650 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6651 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6652 @end ifset
6653
6654 The switch
6655 @ifclear vms
6656 @option{-gnatyN}
6657 @end ifclear
6658 @ifset vms
6659 /STYLE_CHECKS=NONE
6660 @end ifset
6661 clears any previously set style checks.
6662
6663 @node Run-Time Checks
6664 @subsection Run-Time Checks
6665 @cindex Division by zero
6666 @cindex Access before elaboration
6667 @cindex Checks, division by zero
6668 @cindex Checks, access before elaboration
6669 @cindex Checks, stack overflow checking
6670
6671 @noindent
6672 By default, the following checks are suppressed: integer overflow
6673 checks, stack overflow checks, and checks for access before
6674 elaboration on subprogram calls. All other checks, including range
6675 checks and array bounds checks, are turned on by default. The
6676 following @command{gcc} switches refine this default behavior.
6677
6678 @table @option
6679 @c !sort!
6680 @item -gnatp
6681 @cindex @option{-gnatp} (@command{gcc})
6682 @cindex Suppressing checks
6683 @cindex Checks, suppressing
6684 @findex Suppress
6685 This switch causes the unit to be compiled
6686 as though @code{pragma Suppress (All_checks)}
6687 had been present in the source. Validity checks are also eliminated (in
6688 other words @option{-gnatp} also implies @option{-gnatVn}.
6689 Use this switch to improve the performance
6690 of the code at the expense of safety in the presence of invalid data or
6691 program bugs.
6692
6693 Note that when checks are suppressed, the compiler is allowed, but not
6694 required, to omit the checking code. If the run-time cost of the
6695 checking code is zero or near-zero, the compiler will generate it even
6696 if checks are suppressed. In particular, if the compiler can prove
6697 that a certain check will necessarily fail, it will generate code to
6698 do an unconditional ``raise'', even if checks are suppressed. The
6699 compiler warns in this case. Another case in which checks may not be
6700 eliminated is when they are embedded in certain run time routines such
6701 as math library routines.
6702
6703 Of course, run-time checks are omitted whenever the compiler can prove
6704 that they will not fail, whether or not checks are suppressed.
6705
6706 Note that if you suppress a check that would have failed, program
6707 execution is erroneous, which means the behavior is totally
6708 unpredictable. The program might crash, or print wrong answers, or
6709 do anything else. It might even do exactly what you wanted it to do
6710 (and then it might start failing mysteriously next week or next
6711 year). The compiler will generate code based on the assumption that
6712 the condition being checked is true, which can result in disaster if
6713 that assumption is wrong.
6714
6715 The checks subject to suppression include all the checks defined by
6716 the Ada standard, the additional implementation defined checks
6717 @code{Alignment_Check}, @code{Atomic_Synchronization}, and
6718 @code{Validity_Check}, as well as any checks introduced using
6719 @code{pragma Check_Name}.
6720
6721 The @option{-gnatp} switch has no effect if a subsequent
6722 @option{-gnat-p} switch appears.
6723
6724 @item -gnat-p
6725 @cindex @option{-gnat-p} (@command{gcc})
6726 @cindex Suppressing checks
6727 @cindex Checks, suppressing
6728 @findex Suppress
6729 This switch cancels the effect of a previous @option{gnatp} switch.
6730
6731 @item -gnato??
6732 @cindex @option{-gnato??} (@command{gcc})
6733 @cindex Overflow checks
6734 @cindex Overflow mode
6735 @cindex Check, overflow
6736 This switch controls the mode used for computing intermediate
6737 arithmetic integer operations, and also enables overflow checking.
6738 For a full description of overflow mode and checking control, see
6739 the ``Overflow Check Handling in GNAT'' appendix in this
6740 User's Guide.
6741
6742 Overflow checks are always enabled by this switch. The argument
6743 controls the mode, using the codes
6744
6745 @itemize
6746 @item 1 = STRICT
6747 In STRICT mode, intermediate operations are always done using the
6748 base type, and overflow checking ensures that the result is within
6749 the base type range.
6750
6751 @item 2 = MINIMIZED
6752 In MINIMIZED mode, overflows in intermediate operations are avoided
6753 where possible by using a larger integer type for the computation
6754 (typically @code{Long_Long_Integer}). Overflow checking ensures that
6755 the result fits in this larger integer type.
6756
6757 @item 3 = ELIMINATED
6758 In ELIMINATED mode, overflows in intermediate operations are avoided
6759 by using multi-precision arithmetic. In this case, overflow checking
6760 has no effect on intermediate operations (since overflow is impossible).
6761 @end itemize
6762
6763 If two digits are present after @option{-gnato} then the first digit
6764 sets the mode for expressions outside assertions, and the second digit
6765 sets the mode for expressions within assertions. Here assertions is used
6766 in the technical sense (which includes for example precondition and
6767 postcondition expressions).
6768
6769 If one digit is present, the corresponding mode is applicable to both
6770 expressions within and outside assertion expressions.
6771
6772 If no digits are present, the default is to enable overflow checks
6773 and set STRICT mode for both kinds of expressions. This is compatible
6774 with the use of @option{-gnato} in previous versions of GNAT.
6775
6776 @findex Machine_Overflows
6777 Note that the @option{-gnato??} switch does not affect the code generated
6778 for any floating-point operations; it applies only to integer semantics.
6779 For floating-point, @value{EDITION} has the @code{Machine_Overflows}
6780 attribute set to @code{False} and the normal mode of operation is to
6781 generate IEEE NaN and infinite values on overflow or invalid operations
6782 (such as dividing 0.0 by 0.0).
6783
6784 The reason that we distinguish overflow checking from other kinds of
6785 range constraint checking is that a failure of an overflow check, unlike
6786 for example the failure of a range check, can result in an incorrect
6787 value, but cannot cause random memory destruction (like an out of range
6788 subscript), or a wild jump (from an out of range case value). Overflow
6789 checking is also quite expensive in time and space, since in general it
6790 requires the use of double length arithmetic.
6791
6792 Note again that the default is @option{^-gnato00^/OVERFLOW_CHECKS=00^},
6793 so overflow checking is not performed in default mode. This means that out of
6794 the box, with the default settings, @value{EDITION} does not do all the checks
6795 expected from the language description in the Ada Reference Manual.
6796 If you want all constraint checks to be performed, as described in this Manual,
6797 then you must explicitly use the @option{-gnato??}
6798 switch either on the @command{gnatmake} or @command{gcc} command.
6799
6800 @item -gnatE
6801 @cindex @option{-gnatE} (@command{gcc})
6802 @cindex Elaboration checks
6803 @cindex Check, elaboration
6804 Enables dynamic checks for access-before-elaboration
6805 on subprogram calls and generic instantiations.
6806 Note that @option{-gnatE} is not necessary for safety, because in the
6807 default mode, GNAT ensures statically that the checks would not fail.
6808 For full details of the effect and use of this switch,
6809 @xref{Compiling with gcc}.
6810
6811 @item -fstack-check
6812 @cindex @option{-fstack-check} (@command{gcc})
6813 @cindex Stack Overflow Checking
6814 @cindex Checks, stack overflow checking
6815 Activates stack overflow checking. For full details of the effect and use of
6816 this switch see @ref{Stack Overflow Checking}.
6817 @end table
6818
6819 @findex Unsuppress
6820 @noindent
6821 The setting of these switches only controls the default setting of the
6822 checks. You may modify them using either @code{Suppress} (to remove
6823 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6824 the program source.
6825
6826 @node Using gcc for Syntax Checking
6827 @subsection Using @command{gcc} for Syntax Checking
6828 @table @option
6829 @item -gnats
6830 @cindex @option{-gnats} (@command{gcc})
6831 @ifclear vms
6832
6833 @noindent
6834 The @code{s} stands for ``syntax''.
6835 @end ifclear
6836
6837 Run GNAT in syntax checking only mode. For
6838 example, the command
6839
6840 @smallexample
6841 $ gcc -c -gnats x.adb
6842 @end smallexample
6843
6844 @noindent
6845 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6846 series of files in a single command
6847 @ifclear vms
6848 , and can use wild cards to specify such a group of files.
6849 Note that you must specify the @option{-c} (compile
6850 only) flag in addition to the @option{-gnats} flag.
6851 @end ifclear
6852 .
6853 You may use other switches in conjunction with @option{-gnats}. In
6854 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6855 format of any generated error messages.
6856
6857 When the source file is empty or contains only empty lines and/or comments,
6858 the output is a warning:
6859
6860 @smallexample
6861 $ gcc -c -gnats -x ada toto.txt
6862 toto.txt:1:01: warning: empty file, contains no compilation units
6863 $
6864 @end smallexample
6865
6866 Otherwise, the output is simply the error messages, if any. No object file or
6867 ALI file is generated by a syntax-only compilation. Also, no units other
6868 than the one specified are accessed. For example, if a unit @code{X}
6869 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6870 check only mode does not access the source file containing unit
6871 @code{Y}.
6872
6873 @cindex Multiple units, syntax checking
6874 Normally, GNAT allows only a single unit in a source file. However, this
6875 restriction does not apply in syntax-check-only mode, and it is possible
6876 to check a file containing multiple compilation units concatenated
6877 together. This is primarily used by the @code{gnatchop} utility
6878 (@pxref{Renaming Files with gnatchop}).
6879 @end table
6880
6881 @node Using gcc for Semantic Checking
6882 @subsection Using @command{gcc} for Semantic Checking
6883 @table @option
6884 @item -gnatc
6885 @cindex @option{-gnatc} (@command{gcc})
6886
6887 @ifclear vms
6888 @noindent
6889 The @code{c} stands for ``check''.
6890 @end ifclear
6891 Causes the compiler to operate in semantic check mode,
6892 with full checking for all illegalities specified in the
6893 Ada Reference Manual, but without generation of any object code
6894 (no object file is generated).
6895
6896 Because dependent files must be accessed, you must follow the GNAT
6897 semantic restrictions on file structuring to operate in this mode:
6898
6899 @itemize @bullet
6900 @item
6901 The needed source files must be accessible
6902 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6903
6904 @item
6905 Each file must contain only one compilation unit.
6906
6907 @item
6908 The file name and unit name must match (@pxref{File Naming Rules}).
6909 @end itemize
6910
6911 The output consists of error messages as appropriate. No object file is
6912 generated. An @file{ALI} file is generated for use in the context of
6913 cross-reference tools, but this file is marked as not being suitable
6914 for binding (since no object file is generated).
6915 The checking corresponds exactly to the notion of
6916 legality in the Ada Reference Manual.
6917
6918 Any unit can be compiled in semantics-checking-only mode, including
6919 units that would not normally be compiled (subunits,
6920 and specifications where a separate body is present).
6921 @end table
6922
6923 @node Compiling Different Versions of Ada
6924 @subsection Compiling Different Versions of Ada
6925
6926 @noindent
6927 The switches described in this section allow you to explicitly specify
6928 the version of the Ada language that your programs are written in.
6929 The default mode is Ada 2012,
6930 but you can also specify Ada 95, Ada 2005 mode, or
6931 indicate Ada 83 compatibility mode.
6932
6933 @table @option
6934 @cindex Compatibility with Ada 83
6935
6936 @item -gnat83 (Ada 83 Compatibility Mode)
6937 @cindex @option{-gnat83} (@command{gcc})
6938 @cindex ACVC, Ada 83 tests
6939 @cindex Ada 83 mode
6940
6941 @noindent
6942 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6943 specifies that the program is to be compiled in Ada 83 mode. With
6944 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6945 semantics where this can be done easily.
6946 It is not possible to guarantee this switch does a perfect
6947 job; some subtle tests, such as are
6948 found in earlier ACVC tests (and that have been removed from the ACATS suite
6949 for Ada 95), might not compile correctly.
6950 Nevertheless, this switch may be useful in some circumstances, for example
6951 where, due to contractual reasons, existing code needs to be maintained
6952 using only Ada 83 features.
6953
6954 With few exceptions (most notably the need to use @code{<>} on
6955 @cindex Generic formal parameters
6956 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6957 reserved words, and the use of packages
6958 with optional bodies), it is not necessary to specify the
6959 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6960 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6961 a correct Ada 83 program is usually also a correct program
6962 in these later versions of the language standard.
6963 For further information, please refer to @ref{Compatibility and Porting Guide}.
6964
6965 @item -gnat95 (Ada 95 mode)
6966 @cindex @option{-gnat95} (@command{gcc})
6967 @cindex Ada 95 mode
6968
6969 @noindent
6970 This switch directs the compiler to implement the Ada 95 version of the
6971 language.
6972 Since Ada 95 is almost completely upwards
6973 compatible with Ada 83, Ada 83 programs may generally be compiled using
6974 this switch (see the description of the @option{-gnat83} switch for further
6975 information about Ada 83 mode).
6976 If an Ada 2005 program is compiled in Ada 95 mode,
6977 uses of the new Ada 2005 features will cause error
6978 messages or warnings.
6979
6980 This switch also can be used to cancel the effect of a previous
6981 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
6982 switch earlier in the command line.
6983
6984 @item -gnat05 or -gnat2005 (Ada 2005 mode)
6985 @cindex @option{-gnat05} (@command{gcc})
6986 @cindex @option{-gnat2005} (@command{gcc})
6987 @cindex Ada 2005 mode
6988
6989 @noindent
6990 This switch directs the compiler to implement the Ada 2005 version of the
6991 language, as documented in the official Ada standards document.
6992 Since Ada 2005 is almost completely upwards
6993 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6994 may generally be compiled using this switch (see the description of the
6995 @option{-gnat83} and @option{-gnat95} switches for further
6996 information).
6997
6998 @item -gnat12 or -gnat2012 (Ada 2012 mode)
6999 @cindex @option{-gnat12} (@command{gcc})
7000 @cindex @option{-gnat2012} (@command{gcc})
7001 @cindex Ada 2012 mode
7002
7003 @noindent
7004 This switch directs the compiler to implement the Ada 2012 version of the
7005 language (also the default).
7006 Since Ada 2012 is almost completely upwards
7007 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
7008 Ada 83 and Ada 95 programs
7009 may generally be compiled using this switch (see the description of the
7010 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
7011 for further information).
7012
7013 @item -gnatX (Enable GNAT Extensions)
7014 @cindex @option{-gnatX} (@command{gcc})
7015 @cindex Ada language extensions
7016 @cindex GNAT extensions
7017
7018 @noindent
7019 This switch directs the compiler to implement the latest version of the
7020 language (currently Ada 2012) and also to enable certain GNAT implementation
7021 extensions that are not part of any Ada standard. For a full list of these
7022 extensions, see the GNAT reference manual.
7023
7024 @end table
7025
7026 @node Character Set Control
7027 @subsection Character Set Control
7028 @table @option
7029 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7030 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7031
7032 @noindent
7033 Normally GNAT recognizes the Latin-1 character set in source program
7034 identifiers, as described in the Ada Reference Manual.
7035 This switch causes
7036 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7037 single character ^^or word^ indicating the character set, as follows:
7038
7039 @table @code
7040 @item 1
7041 ISO 8859-1 (Latin-1) identifiers
7042
7043 @item 2
7044 ISO 8859-2 (Latin-2) letters allowed in identifiers
7045
7046 @item 3
7047 ISO 8859-3 (Latin-3) letters allowed in identifiers
7048
7049 @item 4
7050 ISO 8859-4 (Latin-4) letters allowed in identifiers
7051
7052 @item 5
7053 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7054
7055 @item 9
7056 ISO 8859-15 (Latin-9) letters allowed in identifiers
7057
7058 @item ^p^PC^
7059 IBM PC letters (code page 437) allowed in identifiers
7060
7061 @item ^8^PC850^
7062 IBM PC letters (code page 850) allowed in identifiers
7063
7064 @item ^f^FULL_UPPER^
7065 Full upper-half codes allowed in identifiers
7066
7067 @item ^n^NO_UPPER^
7068 No upper-half codes allowed in identifiers
7069
7070 @item ^w^WIDE^
7071 Wide-character codes (that is, codes greater than 255)
7072 allowed in identifiers
7073 @end table
7074
7075 @xref{Foreign Language Representation}, for full details on the
7076 implementation of these character sets.
7077
7078 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7079 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7080 Specify the method of encoding for wide characters.
7081 @var{e} is one of the following:
7082
7083 @table @code
7084
7085 @item ^h^HEX^
7086 Hex encoding (brackets coding also recognized)
7087
7088 @item ^u^UPPER^
7089 Upper half encoding (brackets encoding also recognized)
7090
7091 @item ^s^SHIFT_JIS^
7092 Shift/JIS encoding (brackets encoding also recognized)
7093
7094 @item ^e^EUC^
7095 EUC encoding (brackets encoding also recognized)
7096
7097 @item ^8^UTF8^
7098 UTF-8 encoding (brackets encoding also recognized)
7099
7100 @item ^b^BRACKETS^
7101 Brackets encoding only (default value)
7102 @end table
7103 For full details on these encoding
7104 methods see @ref{Wide Character Encodings}.
7105 Note that brackets coding is always accepted, even if one of the other
7106 options is specified, so for example @option{-gnatW8} specifies that both
7107 brackets and UTF-8 encodings will be recognized. The units that are
7108 with'ed directly or indirectly will be scanned using the specified
7109 representation scheme, and so if one of the non-brackets scheme is
7110 used, it must be used consistently throughout the program. However,
7111 since brackets encoding is always recognized, it may be conveniently
7112 used in standard libraries, allowing these libraries to be used with
7113 any of the available coding schemes.
7114
7115 Note that brackets encoding only applies to program text. Within comments,
7116 brackets are considered to be normal graphic characters, and bracket sequences
7117 are never recognized as wide characters.
7118
7119 If no @option{-gnatW?} parameter is present, then the default
7120 representation is normally Brackets encoding only. However, if the
7121 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7122 byte order mark or BOM for UTF-8), then these three characters are
7123 skipped and the default representation for the file is set to UTF-8.
7124
7125 Note that the wide character representation that is specified (explicitly
7126 or by default) for the main program also acts as the default encoding used
7127 for Wide_Text_IO files if not specifically overridden by a WCEM form
7128 parameter.
7129
7130 @end table
7131
7132 When no @option{-gnatW?} is specified, then characters (other than wide
7133 characters represented using brackets notation) are treated as 8-bit
7134 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
7135 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
7136 characters in the range 16#00#..16#1F# are not accepted in program text
7137 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
7138 in program text, but allowed and ignored in comments. Note in particular
7139 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
7140 as an end of line in this default mode. If your source program contains
7141 instances of the NEL character used as a line terminator,
7142 you must use UTF-8 encoding for the whole
7143 source program. In default mode, all lines must be ended by a standard
7144 end of line sequence (CR, CR/LF, or LF).
7145
7146 Note that the convention of simply accepting all upper half characters in
7147 comments means that programs that use standard ASCII for program text, but
7148 UTF-8 encoding for comments are accepted in default mode, providing that the
7149 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
7150 This is a common mode for many programs with foreign language comments.
7151
7152 @node File Naming Control
7153 @subsection File Naming Control
7154
7155 @table @option
7156 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7157 @cindex @option{-gnatk} (@command{gcc})
7158 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7159 1-999, indicates the maximum allowable length of a file name (not
7160 including the @file{.ads} or @file{.adb} extension). The default is not
7161 to enable file name krunching.
7162
7163 For the source file naming rules, @xref{File Naming Rules}.
7164 @end table
7165
7166 @node Subprogram Inlining Control
7167 @subsection Subprogram Inlining Control
7168
7169 @table @option
7170 @c !sort!
7171 @item -gnatn[12]
7172 @cindex @option{-gnatn} (@command{gcc})
7173 @ifclear vms
7174 The @code{n} here is intended to suggest the first syllable of the
7175 word ``inline''.
7176 @end ifclear
7177 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7178 inlining to actually occur, optimization must be enabled and, in order
7179 to enable inlining of subprograms specified by pragma @code{Inline},
7180 you must also specify this switch.
7181 In the absence of this switch, GNAT does not attempt
7182 inlining and does not need to access the bodies of
7183 subprograms for which @code{pragma Inline} is specified if they are not
7184 in the current unit.
7185
7186 You can optionally specify the inlining level: 1 for moderate inlining across
7187 modules, which is a good compromise between compilation times and performances
7188 at run time, or 2 for full inlining across modules, which may bring about
7189 longer compilation times. If no inlining level is specified, the compiler will
7190 pick it based on the optimization level: 1 for @option{-O1}, @option{-O2} or
7191 @option{-Os} and 2 for @option{-O3}.
7192
7193 If you specify this switch the compiler will access these bodies,
7194 creating an extra source dependency for the resulting object file, and
7195 where possible, the call will be inlined.
7196 For further details on when inlining is possible
7197 see @ref{Inlining of Subprograms}.
7198
7199 @item -gnatN
7200 @cindex @option{-gnatN} (@command{gcc})
7201 This switch activates front-end inlining which also
7202 generates additional dependencies.
7203
7204 When using a gcc-based back end (in practice this means using any version
7205 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7206 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7207 Historically front end inlining was more extensive than the gcc back end
7208 inlining, but that is no longer the case.
7209 @end table
7210
7211 @node Auxiliary Output Control
7212 @subsection Auxiliary Output Control
7213
7214 @table @option
7215 @item -gnatt
7216 @cindex @option{-gnatt} (@command{gcc})
7217 @cindex Writing internal trees
7218 @cindex Internal trees, writing to file
7219 Causes GNAT to write the internal tree for a unit to a file (with the
7220 extension @file{.adt}.
7221 This not normally required, but is used by separate analysis tools.
7222 Typically
7223 these tools do the necessary compilations automatically, so you should
7224 not have to specify this switch in normal operation.
7225 Note that the combination of switches @option{-gnatct}
7226 generates a tree in the form required by ASIS applications.
7227
7228 @item -gnatu
7229 @cindex @option{-gnatu} (@command{gcc})
7230 Print a list of units required by this compilation on @file{stdout}.
7231 The listing includes all units on which the unit being compiled depends
7232 either directly or indirectly.
7233
7234 @ifclear vms
7235 @item -pass-exit-codes
7236 @cindex @option{-pass-exit-codes} (@command{gcc})
7237 If this switch is not used, the exit code returned by @command{gcc} when
7238 compiling multiple files indicates whether all source files have
7239 been successfully used to generate object files or not.
7240
7241 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7242 exit status and allows an integrated development environment to better
7243 react to a compilation failure. Those exit status are:
7244
7245 @table @asis
7246 @item 5
7247 There was an error in at least one source file.
7248 @item 3
7249 At least one source file did not generate an object file.
7250 @item 2
7251 The compiler died unexpectedly (internal error for example).
7252 @item 0
7253 An object file has been generated for every source file.
7254 @end table
7255 @end ifclear
7256 @end table
7257
7258 @node Debugging Control
7259 @subsection Debugging Control
7260
7261 @table @option
7262 @c !sort!
7263 @cindex Debugging options
7264 @ifclear vms
7265 @item -gnatd@var{x}
7266 @cindex @option{-gnatd} (@command{gcc})
7267 Activate internal debugging switches. @var{x} is a letter or digit, or
7268 string of letters or digits, which specifies the type of debugging
7269 outputs desired. Normally these are used only for internal development
7270 or system debugging purposes. You can find full documentation for these
7271 switches in the body of the @code{Debug} unit in the compiler source
7272 file @file{debug.adb}.
7273 @end ifclear
7274
7275 @item -gnatG[=nn]
7276 @cindex @option{-gnatG} (@command{gcc})
7277 This switch causes the compiler to generate auxiliary output containing
7278 a pseudo-source listing of the generated expanded code. Like most Ada
7279 compilers, GNAT works by first transforming the high level Ada code into
7280 lower level constructs. For example, tasking operations are transformed
7281 into calls to the tasking run-time routines. A unique capability of GNAT
7282 is to list this expanded code in a form very close to normal Ada source.
7283 This is very useful in understanding the implications of various Ada
7284 usage on the efficiency of the generated code. There are many cases in
7285 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7286 generate a lot of run-time code. By using @option{-gnatG} you can identify
7287 these cases, and consider whether it may be desirable to modify the coding
7288 approach to improve efficiency.
7289
7290 The optional parameter @code{nn} if present after -gnatG specifies an
7291 alternative maximum line length that overrides the normal default of 72.
7292 This value is in the range 40-999999, values less than 40 being silently
7293 reset to 40. The equal sign is optional.
7294
7295 The format of the output is very similar to standard Ada source, and is
7296 easily understood by an Ada programmer. The following special syntactic
7297 additions correspond to low level features used in the generated code that
7298 do not have any exact analogies in pure Ada source form. The following
7299 is a partial list of these special constructions. See the spec
7300 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7301
7302 If the switch @option{-gnatL} is used in conjunction with
7303 @cindex @option{-gnatL} (@command{gcc})
7304 @option{-gnatG}, then the original source lines are interspersed
7305 in the expanded source (as comment lines with the original line number).
7306
7307 @table @code
7308 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7309 Shows the storage pool being used for an allocator.
7310
7311 @item at end @var{procedure-name};
7312 Shows the finalization (cleanup) procedure for a scope.
7313
7314 @item (if @var{expr} then @var{expr} else @var{expr})
7315 Conditional expression equivalent to the @code{x?y:z} construction in C.
7316
7317 @item @var{target}^^^(@var{source})
7318 A conversion with floating-point truncation instead of rounding.
7319
7320 @item @var{target}?(@var{source})
7321 A conversion that bypasses normal Ada semantic checking. In particular
7322 enumeration types and fixed-point types are treated simply as integers.
7323
7324 @item @var{target}?^^^(@var{source})
7325 Combines the above two cases.
7326
7327 @item @var{x} #/ @var{y}
7328 @itemx @var{x} #mod @var{y}
7329 @itemx @var{x} #* @var{y}
7330 @itemx @var{x} #rem @var{y}
7331 A division or multiplication of fixed-point values which are treated as
7332 integers without any kind of scaling.
7333
7334 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7335 Shows the storage pool associated with a @code{free} statement.
7336
7337 @item [subtype or type declaration]
7338 Used to list an equivalent declaration for an internally generated
7339 type that is referenced elsewhere in the listing.
7340
7341 @c @item freeze @var{type-name} @ovar{actions}
7342 @c Expanding @ovar macro inline (explanation in macro def comments)
7343 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7344 Shows the point at which @var{type-name} is frozen, with possible
7345 associated actions to be performed at the freeze point.
7346
7347 @item reference @var{itype}
7348 Reference (and hence definition) to internal type @var{itype}.
7349
7350 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7351 Intrinsic function call.
7352
7353 @item @var{label-name} : label
7354 Declaration of label @var{labelname}.
7355
7356 @item #$ @var{subprogram-name}
7357 An implicit call to a run-time support routine
7358 (to meet the requirement of H.3.1(9) in a
7359 convenient manner).
7360
7361 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7362 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7363 @var{expr}, but handled more efficiently).
7364
7365 @item [constraint_error]
7366 Raise the @code{Constraint_Error} exception.
7367
7368 @item @var{expression}'reference
7369 A pointer to the result of evaluating @var{expression}.
7370
7371 @item @var{target-type}!(@var{source-expression})
7372 An unchecked conversion of @var{source-expression} to @var{target-type}.
7373
7374 @item [@var{numerator}/@var{denominator}]
7375 Used to represent internal real literals (that) have no exact
7376 representation in base 2-16 (for example, the result of compile time
7377 evaluation of the expression 1.0/27.0).
7378 @end table
7379
7380 @item -gnatD[=nn]
7381 @cindex @option{-gnatD} (@command{gcc})
7382 When used in conjunction with @option{-gnatG}, this switch causes
7383 the expanded source, as described above for
7384 @option{-gnatG} to be written to files with names
7385 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7386 instead of to the standard output file. For
7387 example, if the source file name is @file{hello.adb}, then a file
7388 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
7389 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7390 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7391 you to do source level debugging using the generated code which is
7392 sometimes useful for complex code, for example to find out exactly
7393 which part of a complex construction raised an exception. This switch
7394 also suppress generation of cross-reference information (see
7395 @option{-gnatx}) since otherwise the cross-reference information
7396 would refer to the @file{^.dg^.DG^} file, which would cause
7397 confusion since this is not the original source file.
7398
7399 Note that @option{-gnatD} actually implies @option{-gnatG}
7400 automatically, so it is not necessary to give both options.
7401 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7402
7403 If the switch @option{-gnatL} is used in conjunction with
7404 @cindex @option{-gnatL} (@command{gcc})
7405 @option{-gnatDG}, then the original source lines are interspersed
7406 in the expanded source (as comment lines with the original line number).
7407
7408 The optional parameter @code{nn} if present after -gnatD specifies an
7409 alternative maximum line length that overrides the normal default of 72.
7410 This value is in the range 40-999999, values less than 40 being silently
7411 reset to 40. The equal sign is optional.
7412
7413 @item -gnatr
7414 @cindex @option{-gnatr} (@command{gcc})
7415 @cindex pragma Restrictions
7416 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7417 so that violation of restrictions causes warnings rather than illegalities.
7418 This is useful during the development process when new restrictions are added
7419 or investigated. The switch also causes pragma Profile to be treated as
7420 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7421 restriction warnings rather than restrictions.
7422
7423 @ifclear vms
7424 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7425 @cindex @option{-gnatR} (@command{gcc})
7426 This switch controls output from the compiler of a listing showing
7427 representation information for declared types and objects. For
7428 @option{-gnatR0}, no information is output (equivalent to omitting
7429 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7430 so @option{-gnatR} with no parameter has the same effect), size and alignment
7431 information is listed for declared array and record types. For
7432 @option{-gnatR2}, size and alignment information is listed for all
7433 declared types and objects. The @code{Linker_Section} is also listed for any
7434 entity for which the @code{Linker_Section} is set explicitly or implicitly (the
7435 latter case occurs for objects of a type for which a @code{Linker_Section}
7436 is set).
7437
7438 Finally @option{-gnatR3} includes symbolic
7439 expressions for values that are computed at run time for
7440 variant records. These symbolic expressions have a mostly obvious
7441 format with #n being used to represent the value of the n'th
7442 discriminant. See source files @file{repinfo.ads/adb} in the
7443 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7444 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7445 the output is to a file with the name @file{^file.rep^file_REP^} where
7446 file is the name of the corresponding source file.
7447
7448 @item -gnatRm[s]
7449 This form of the switch controls output of subprogram conventions
7450 and parameter passing mechanisms for all subprograms. A following
7451 @code{s} means output to a file as described above.
7452 @end ifclear
7453 @ifset vms
7454 @item /REPRESENTATION_INFO
7455 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7456 This qualifier controls output from the compiler of a listing showing
7457 representation information for declared types and objects. For
7458 @option{/REPRESENTATION_INFO=NONE}, no information is output
7459 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7460 @option{/REPRESENTATION_INFO} without option is equivalent to
7461 @option{/REPRESENTATION_INFO=ARRAYS}.
7462 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7463 information is listed for declared array and record types. For
7464 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7465 is listed for all expression information for values that are computed
7466 at run time for variant records. These symbolic expressions have a mostly
7467 obvious format with #n being used to represent the value of the n'th
7468 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7469 @code{GNAT} sources for full details on the format of
7470 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7471 If _FILE is added at the end of an option
7472 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7473 then the output is to a file with the name @file{file_REP} where
7474 file is the name of the corresponding source file.
7475
7476 @item /REPRESENTATION_INFO=MECHANISMS
7477 This qualifier form controls output of subprogram conventions
7478 and parameter passing mechanisms for all subprograms. It is
7479 possible to append _FILE as described above to cause information
7480 to be written to a file.
7481 @end ifset
7482
7483 Note that it is possible for record components to have zero size. In
7484 this case, the component clause uses an obvious extension of permitted
7485 Ada syntax, for example @code{at 0 range 0 .. -1}.
7486
7487 Representation information requires that code be generated (since it is the
7488 code generator that lays out complex data structures). If an attempt is made
7489 to output representation information when no code is generated, for example
7490 when a subunit is compiled on its own, then no information can be generated
7491 and the compiler outputs a message to this effect.
7492
7493 @item -gnatS
7494 @cindex @option{-gnatS} (@command{gcc})
7495 The use of the switch @option{-gnatS} for an
7496 Ada compilation will cause the compiler to output a
7497 representation of package Standard in a form very
7498 close to standard Ada. It is not quite possible to
7499 do this entirely in standard Ada (since new
7500 numeric base types cannot be created in standard
7501 Ada), but the output is easily
7502 readable to any Ada programmer, and is useful to
7503 determine the characteristics of target dependent
7504 types in package Standard.
7505
7506 @item -gnatx
7507 @cindex @option{-gnatx} (@command{gcc})
7508 Normally the compiler generates full cross-referencing information in
7509 the @file{ALI} file. This information is used by a number of tools,
7510 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7511 suppresses this information. This saves some space and may slightly
7512 speed up compilation, but means that these tools cannot be used.
7513 @end table
7514
7515 @node Exception Handling Control
7516 @subsection Exception Handling Control
7517
7518 @noindent
7519 GNAT uses two methods for handling exceptions at run-time. The
7520 @code{setjmp/longjmp} method saves the context when entering
7521 a frame with an exception handler. Then when an exception is
7522 raised, the context can be restored immediately, without the
7523 need for tracing stack frames. This method provides very fast
7524 exception propagation, but introduces significant overhead for
7525 the use of exception handlers, even if no exception is raised.
7526
7527 The other approach is called ``zero cost'' exception handling.
7528 With this method, the compiler builds static tables to describe
7529 the exception ranges. No dynamic code is required when entering
7530 a frame containing an exception handler. When an exception is
7531 raised, the tables are used to control a back trace of the
7532 subprogram invocation stack to locate the required exception
7533 handler. This method has considerably poorer performance for
7534 the propagation of exceptions, but there is no overhead for
7535 exception handlers if no exception is raised. Note that in this
7536 mode and in the context of mixed Ada and C/C++ programming,
7537 to propagate an exception through a C/C++ code, the C/C++ code
7538 must be compiled with the @option{-funwind-tables} GCC's
7539 option.
7540
7541 The following switches may be used to control which of the
7542 two exception handling methods is used.
7543
7544 @table @option
7545 @c !sort!
7546
7547 @item --RTS=sjlj
7548 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7549 This switch causes the setjmp/longjmp run-time (when available) to be used
7550 for exception handling. If the default
7551 mechanism for the target is zero cost exceptions, then
7552 this switch can be used to modify this default, and must be
7553 used for all units in the partition.
7554 This option is rarely used. One case in which it may be
7555 advantageous is if you have an application where exception
7556 raising is common and the overall performance of the
7557 application is improved by favoring exception propagation.
7558
7559 @item --RTS=zcx
7560 @cindex @option{--RTS=zcx} (@command{gnatmake})
7561 @cindex Zero Cost Exceptions
7562 This switch causes the zero cost approach to be used
7563 for exception handling. If this is the default mechanism for the
7564 target (see below), then this switch is unneeded. If the default
7565 mechanism for the target is setjmp/longjmp exceptions, then
7566 this switch can be used to modify this default, and must be
7567 used for all units in the partition.
7568 This option can only be used if the zero cost approach
7569 is available for the target in use, otherwise it will generate an error.
7570 @end table
7571
7572 @noindent
7573 The same option @option{--RTS} must be used both for @command{gcc}
7574 and @command{gnatbind}. Passing this option to @command{gnatmake}
7575 (@pxref{Switches for gnatmake}) will ensure the required consistency
7576 through the compilation and binding steps.
7577
7578 @node Units to Sources Mapping Files
7579 @subsection Units to Sources Mapping Files
7580
7581 @table @option
7582
7583 @item -gnatem=@var{path}
7584 @cindex @option{-gnatem} (@command{gcc})
7585 A mapping file is a way to communicate to the compiler two mappings:
7586 from unit names to file names (without any directory information) and from
7587 file names to path names (with full directory information). These mappings
7588 are used by the compiler to short-circuit the path search.
7589
7590 The use of mapping files is not required for correct operation of the
7591 compiler, but mapping files can improve efficiency, particularly when
7592 sources are read over a slow network connection. In normal operation,
7593 you need not be concerned with the format or use of mapping files,
7594 and the @option{-gnatem} switch is not a switch that you would use
7595 explicitly. It is intended primarily for use by automatic tools such as
7596 @command{gnatmake} running under the project file facility. The
7597 description here of the format of mapping files is provided
7598 for completeness and for possible use by other tools.
7599
7600 A mapping file is a sequence of sets of three lines. In each set, the
7601 first line is the unit name, in lower case, with @code{%s} appended
7602 for specs and @code{%b} appended for bodies; the second line is the
7603 file name; and the third line is the path name.
7604
7605 Example:
7606 @smallexample
7607 main%b
7608 main.2.ada
7609 /gnat/project1/sources/main.2.ada
7610 @end smallexample
7611
7612 When the switch @option{-gnatem} is specified, the compiler will
7613 create in memory the two mappings from the specified file. If there is
7614 any problem (nonexistent file, truncated file or duplicate entries),
7615 no mapping will be created.
7616
7617 Several @option{-gnatem} switches may be specified; however, only the
7618 last one on the command line will be taken into account.
7619
7620 When using a project file, @command{gnatmake} creates a temporary
7621 mapping file and communicates it to the compiler using this switch.
7622
7623 @end table
7624
7625 @node Integrated Preprocessing
7626 @subsection Integrated Preprocessing
7627
7628 @noindent
7629 GNAT sources may be preprocessed immediately before compilation.
7630 In this case, the actual
7631 text of the source is not the text of the source file, but is derived from it
7632 through a process called preprocessing. Integrated preprocessing is specified
7633 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7634 indicates, through a text file, the preprocessing data to be used.
7635 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7636
7637 @noindent
7638 Note that when integrated preprocessing is used, the output from the
7639 preprocessor is not written to any external file. Instead it is passed
7640 internally to the compiler. If you need to preserve the result of
7641 preprocessing in a file, then you should use @command{gnatprep}
7642 to perform the desired preprocessing in stand-alone mode.
7643
7644 @noindent
7645 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7646 used when Integrated Preprocessing is used. The reason is that preprocessing
7647 with another Preprocessing Data file without changing the sources will
7648 not trigger recompilation without this switch.
7649
7650 @noindent
7651 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7652 always trigger recompilation for sources that are preprocessed,
7653 because @command{gnatmake} cannot compute the checksum of the source after
7654 preprocessing.
7655
7656 @noindent
7657 The actual preprocessing function is described in details in section
7658 @ref{Preprocessing with gnatprep}. This section only describes how integrated
7659 preprocessing is triggered and parameterized.
7660
7661 @table @code
7662
7663 @item -gnatep=@var{file}
7664 @cindex @option{-gnatep} (@command{gcc})
7665 This switch indicates to the compiler the file name (without directory
7666 information) of the preprocessor data file to use. The preprocessor data file
7667 should be found in the source directories. Note that when the compiler is
7668 called by a builder such as (@command{gnatmake} with a project
7669 file, if the object directory is not also a source directory, the builder needs
7670 to be called with @option{-x}.
7671
7672 @noindent
7673 A preprocessing data file is a text file with significant lines indicating
7674 how should be preprocessed either a specific source or all sources not
7675 mentioned in other lines. A significant line is a nonempty, non-comment line.
7676 Comments are similar to Ada comments.
7677
7678 @noindent
7679 Each significant line starts with either a literal string or the character '*'.
7680 A literal string is the file name (without directory information) of the source
7681 to preprocess. A character '*' indicates the preprocessing for all the sources
7682 that are not specified explicitly on other lines (order of the lines is not
7683 significant). It is an error to have two lines with the same file name or two
7684 lines starting with the character '*'.
7685
7686 @noindent
7687 After the file name or the character '*', another optional literal string
7688 indicating the file name of the definition file to be used for preprocessing
7689 (@pxref{Form of Definitions File}). The definition files are found by the
7690 compiler in one of the source directories. In some cases, when compiling
7691 a source in a directory other than the current directory, if the definition
7692 file is in the current directory, it may be necessary to add the current
7693 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7694 the compiler would not find the definition file.
7695
7696 @noindent
7697 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7698 be found. Those ^switches^switches^ are:
7699
7700 @table @code
7701
7702 @item -b
7703 Causes both preprocessor lines and the lines deleted by
7704 preprocessing to be replaced by blank lines, preserving the line number.
7705 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7706 it cancels the effect of @option{-c}.
7707
7708 @item -c
7709 Causes both preprocessor lines and the lines deleted
7710 by preprocessing to be retained as comments marked
7711 with the special string ``@code{--! }''.
7712
7713 @item -Dsymbol=value
7714 Define or redefine a symbol, associated with value. A symbol is an Ada
7715 identifier, or an Ada reserved word, with the exception of @code{if},
7716 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7717 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7718 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7719 same name defined in a definition file.
7720
7721 @item -s
7722 Causes a sorted list of symbol names and values to be
7723 listed on the standard output file.
7724
7725 @item -u
7726 Causes undefined symbols to be treated as having the value @code{FALSE}
7727 in the context
7728 of a preprocessor test. In the absence of this option, an undefined symbol in
7729 a @code{#if} or @code{#elsif} test will be treated as an error.
7730
7731 @end table
7732
7733 @noindent
7734 Examples of valid lines in a preprocessor data file:
7735
7736 @smallexample
7737 "toto.adb" "prep.def" -u
7738 -- preprocess "toto.adb", using definition file "prep.def",
7739 -- undefined symbol are False.
7740
7741 * -c -DVERSION=V101
7742 -- preprocess all other sources without a definition file;
7743 -- suppressed lined are commented; symbol VERSION has the value V101.
7744
7745 "titi.adb" "prep2.def" -s
7746 -- preprocess "titi.adb", using definition file "prep2.def";
7747 -- list all symbols with their values.
7748 @end smallexample
7749
7750 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7751 @cindex @option{-gnateD} (@command{gcc})
7752 Define or redefine a preprocessing symbol, associated with value. If no value
7753 is given on the command line, then the value of the symbol is @code{True}.
7754 A symbol is an identifier, following normal Ada (case-insensitive)
7755 rules for its syntax, and value is either an arbitrary string between double
7756 quotes or any sequence (including an empty sequence) of characters from the
7757 set (letters, digits, period, underline).
7758 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7759 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7760
7761 @ifclear vms
7762 @noindent
7763 Examples:
7764
7765 @smallexample
7766 -gnateDToto=Titi
7767 -gnateDFoo
7768 -gnateDFoo=\"Foo-Bar\"
7769 @end smallexample
7770 @end ifclear
7771
7772 @noindent
7773 A symbol declared with this ^switch^switch^ on the command line replaces a
7774 symbol with the same name either in a definition file or specified with a
7775 ^switch^switch^ -D in the preprocessor data file.
7776
7777 @noindent
7778 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7779
7780 @item -gnateG
7781 When integrated preprocessing is performed and the preprocessor modifies
7782 the source text, write the result of this preprocessing into a file
7783 <source>^.prep^_prep^.
7784
7785 @end table
7786
7787 @node Code Generation Control
7788 @subsection Code Generation Control
7789
7790 @noindent
7791
7792 The GCC technology provides a wide range of target dependent
7793 @option{-m} switches for controlling
7794 details of code generation with respect to different versions of
7795 architectures. This includes variations in instruction sets (e.g.@:
7796 different members of the power pc family), and different requirements
7797 for optimal arrangement of instructions (e.g.@: different members of
7798 the x86 family). The list of available @option{-m} switches may be
7799 found in the GCC documentation.
7800
7801 Use of these @option{-m} switches may in some cases result in improved
7802 code performance.
7803
7804 The @value{EDITION} technology is tested and qualified without any
7805 @option{-m} switches,
7806 so generally the most reliable approach is to avoid the use of these
7807 switches. However, we generally expect most of these switches to work
7808 successfully with @value{EDITION}, and many customers have reported successful
7809 use of these options.
7810
7811 Our general advice is to avoid the use of @option{-m} switches unless
7812 special needs lead to requirements in this area. In particular,
7813 there is no point in using @option{-m} switches to improve performance
7814 unless you actually see a performance improvement.
7815
7816 @ifset vms
7817 @node Return Codes
7818 @subsection Return Codes
7819 @cindex Return Codes
7820 @cindex @option{/RETURN_CODES=VMS}
7821
7822 @noindent
7823 On VMS, GNAT compiled programs return POSIX-style codes by default,
7824 e.g.@: @option{/RETURN_CODES=POSIX}.
7825
7826 To enable VMS style return codes, use GNAT BIND and LINK with the option
7827 @option{/RETURN_CODES=VMS}. For example:
7828
7829 @smallexample
7830 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7831 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7832 @end smallexample
7833
7834 @noindent
7835 Programs built with /RETURN_CODES=VMS are suitable to be called in
7836 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7837 are suitable for spawning with appropriate GNAT RTL routines.
7838
7839 @end ifset
7840
7841 @node Search Paths and the Run-Time Library (RTL)
7842 @section Search Paths and the Run-Time Library (RTL)
7843
7844 @noindent
7845 With the GNAT source-based library system, the compiler must be able to
7846 find source files for units that are needed by the unit being compiled.
7847 Search paths are used to guide this process.
7848
7849 The compiler compiles one source file whose name must be given
7850 explicitly on the command line. In other words, no searching is done
7851 for this file. To find all other source files that are needed (the most
7852 common being the specs of units), the compiler examines the following
7853 directories, in the following order:
7854
7855 @enumerate
7856 @item
7857 The directory containing the source file of the main unit being compiled
7858 (the file name on the command line).
7859
7860 @item
7861 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7862 @command{gcc} command line, in the order given.
7863
7864 @item
7865 @findex ADA_PRJ_INCLUDE_FILE
7866 Each of the directories listed in the text file whose name is given
7867 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7868
7869 @noindent
7870 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7871 driver when project files are used. It should not normally be set
7872 by other means.
7873
7874 @item
7875 @findex ADA_INCLUDE_PATH
7876 Each of the directories listed in the value of the
7877 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7878 @ifclear vms
7879 Construct this value
7880 exactly as the @env{PATH} environment variable: a list of directory
7881 names separated by colons (semicolons when working with the NT version).
7882 @end ifclear
7883 @ifset vms
7884 Normally, define this value as a logical name containing a comma separated
7885 list of directory names.
7886
7887 This variable can also be defined by means of an environment string
7888 (an argument to the HP C exec* set of functions).
7889
7890 Logical Name:
7891 @smallexample
7892 DEFINE ANOTHER_PATH FOO:[BAG]
7893 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7894 @end smallexample
7895
7896 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7897 first, followed by the standard Ada
7898 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7899 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7900 (Text_IO, Sequential_IO, etc)
7901 instead of the standard Ada packages. Thus, in order to get the standard Ada
7902 packages by default, ADA_INCLUDE_PATH must be redefined.
7903 @end ifset
7904
7905 @item
7906 The content of the @file{ada_source_path} file which is part of the GNAT
7907 installation tree and is used to store standard libraries such as the
7908 GNAT Run Time Library (RTL) source files.
7909 @ifclear vms
7910 @ref{Installing a library}
7911 @end ifclear
7912 @end enumerate
7913
7914 @noindent
7915 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7916 inhibits the use of the directory
7917 containing the source file named in the command line. You can still
7918 have this directory on your search path, but in this case it must be
7919 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7920
7921 Specifying the switch @option{-nostdinc}
7922 inhibits the search of the default location for the GNAT Run Time
7923 Library (RTL) source files.
7924
7925 The compiler outputs its object files and ALI files in the current
7926 working directory.
7927 @ifclear vms
7928 Caution: The object file can be redirected with the @option{-o} switch;
7929 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7930 so the @file{ALI} file will not go to the right place. Therefore, you should
7931 avoid using the @option{-o} switch.
7932 @end ifclear
7933
7934 @findex System.IO
7935 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7936 children make up the GNAT RTL, together with the simple @code{System.IO}
7937 package used in the @code{"Hello World"} example. The sources for these units
7938 are needed by the compiler and are kept together in one directory. Not
7939 all of the bodies are needed, but all of the sources are kept together
7940 anyway. In a normal installation, you need not specify these directory
7941 names when compiling or binding. Either the environment variables or
7942 the built-in defaults cause these files to be found.
7943
7944 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7945 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7946 consisting of child units of @code{GNAT}. This is a collection of generally
7947 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7948 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7949
7950 Besides simplifying access to the RTL, a major use of search paths is
7951 in compiling sources from multiple directories. This can make
7952 development environments much more flexible.
7953
7954 @node Order of Compilation Issues
7955 @section Order of Compilation Issues
7956
7957 @noindent
7958 If, in our earlier example, there was a spec for the @code{hello}
7959 procedure, it would be contained in the file @file{hello.ads}; yet this
7960 file would not have to be explicitly compiled. This is the result of the
7961 model we chose to implement library management. Some of the consequences
7962 of this model are as follows:
7963
7964 @itemize @bullet
7965 @item
7966 There is no point in compiling specs (except for package
7967 specs with no bodies) because these are compiled as needed by clients. If
7968 you attempt a useless compilation, you will receive an error message.
7969 It is also useless to compile subunits because they are compiled as needed
7970 by the parent.
7971
7972 @item
7973 There are no order of compilation requirements: performing a
7974 compilation never obsoletes anything. The only way you can obsolete
7975 something and require recompilations is to modify one of the
7976 source files on which it depends.
7977
7978 @item
7979 There is no library as such, apart from the ALI files
7980 (@pxref{The Ada Library Information Files}, for information on the format
7981 of these files). For now we find it convenient to create separate ALI files,
7982 but eventually the information therein may be incorporated into the object
7983 file directly.
7984
7985 @item
7986 When you compile a unit, the source files for the specs of all units
7987 that it @code{with}'s, all its subunits, and the bodies of any generics it
7988 instantiates must be available (reachable by the search-paths mechanism
7989 described above), or you will receive a fatal error message.
7990 @end itemize
7991
7992 @node Examples
7993 @section Examples
7994
7995 @noindent
7996 The following are some typical Ada compilation command line examples:
7997
7998 @table @code
7999 @item $ gcc -c xyz.adb
8000 Compile body in file @file{xyz.adb} with all default options.
8001
8002 @ifclear vms
8003 @item $ gcc -c -O2 -gnata xyz-def.adb
8004 @end ifclear
8005 @ifset vms
8006 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
8007 @end ifset
8008
8009 Compile the child unit package in file @file{xyz-def.adb} with extensive
8010 optimizations, and pragma @code{Assert}/@code{Debug} statements
8011 enabled.
8012
8013 @item $ gcc -c -gnatc abc-def.adb
8014 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
8015 mode.
8016 @end table
8017
8018 @node Binding with gnatbind
8019 @chapter Binding with @code{gnatbind}
8020 @findex gnatbind
8021
8022 @menu
8023 * Running gnatbind::
8024 * Switches for gnatbind::
8025 * Command-Line Access::
8026 * Search Paths for gnatbind::
8027 * Examples of gnatbind Usage::
8028 @end menu
8029
8030 @noindent
8031 This chapter describes the GNAT binder, @code{gnatbind}, which is used
8032 to bind compiled GNAT objects.
8033
8034 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
8035 driver (see @ref{The GNAT Driver and Project Files}).
8036
8037 The @code{gnatbind} program performs four separate functions:
8038
8039 @enumerate
8040 @item
8041 Checks that a program is consistent, in accordance with the rules in
8042 Chapter 10 of the Ada Reference Manual. In particular, error
8043 messages are generated if a program uses inconsistent versions of a
8044 given unit.
8045
8046 @item
8047 Checks that an acceptable order of elaboration exists for the program
8048 and issues an error message if it cannot find an order of elaboration
8049 that satisfies the rules in Chapter 10 of the Ada Language Manual.
8050
8051 @item
8052 Generates a main program incorporating the given elaboration order.
8053 This program is a small Ada package (body and spec) that
8054 must be subsequently compiled
8055 using the GNAT compiler. The necessary compilation step is usually
8056 performed automatically by @command{gnatlink}. The two most important
8057 functions of this program
8058 are to call the elaboration routines of units in an appropriate order
8059 and to call the main program.
8060
8061 @item
8062 Determines the set of object files required by the given main program.
8063 This information is output in the forms of comments in the generated program,
8064 to be read by the @command{gnatlink} utility used to link the Ada application.
8065 @end enumerate
8066
8067 @node Running gnatbind
8068 @section Running @code{gnatbind}
8069
8070 @noindent
8071 The form of the @code{gnatbind} command is
8072
8073 @smallexample
8074 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8075 @c Expanding @ovar macro inline (explanation in macro def comments)
8076 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8077 @end smallexample
8078
8079 @noindent
8080 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8081 unit body. @code{gnatbind} constructs an Ada
8082 package in two files whose names are
8083 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8084 For example, if given the
8085 parameter @file{hello.ali}, for a main program contained in file
8086 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8087 and @file{b~hello.adb}.
8088
8089 When doing consistency checking, the binder takes into consideration
8090 any source files it can locate. For example, if the binder determines
8091 that the given main program requires the package @code{Pack}, whose
8092 @file{.ALI}
8093 file is @file{pack.ali} and whose corresponding source spec file is
8094 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8095 (using the same search path conventions as previously described for the
8096 @command{gcc} command). If it can locate this source file, it checks that
8097 the time stamps
8098 or source checksums of the source and its references to in @file{ALI} files
8099 match. In other words, any @file{ALI} files that mentions this spec must have
8100 resulted from compiling this version of the source file (or in the case
8101 where the source checksums match, a version close enough that the
8102 difference does not matter).
8103
8104 @cindex Source files, use by binder
8105 The effect of this consistency checking, which includes source files, is
8106 that the binder ensures that the program is consistent with the latest
8107 version of the source files that can be located at bind time. Editing a
8108 source file without compiling files that depend on the source file cause
8109 error messages to be generated by the binder.
8110
8111 For example, suppose you have a main program @file{hello.adb} and a
8112 package @code{P}, from file @file{p.ads} and you perform the following
8113 steps:
8114
8115 @enumerate
8116 @item
8117 Enter @code{gcc -c hello.adb} to compile the main program.
8118
8119 @item
8120 Enter @code{gcc -c p.ads} to compile package @code{P}.
8121
8122 @item
8123 Edit file @file{p.ads}.
8124
8125 @item
8126 Enter @code{gnatbind hello}.
8127 @end enumerate
8128
8129 @noindent
8130 At this point, the file @file{p.ali} contains an out-of-date time stamp
8131 because the file @file{p.ads} has been edited. The attempt at binding
8132 fails, and the binder generates the following error messages:
8133
8134 @smallexample
8135 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8136 error: "p.ads" has been modified and must be recompiled
8137 @end smallexample
8138
8139 @noindent
8140 Now both files must be recompiled as indicated, and then the bind can
8141 succeed, generating a main program. You need not normally be concerned
8142 with the contents of this file, but for reference purposes a sample
8143 binder output file is given in @ref{Example of Binder Output File}.
8144
8145 In most normal usage, the default mode of @command{gnatbind} which is to
8146 generate the main package in Ada, as described in the previous section.
8147 In particular, this means that any Ada programmer can read and understand
8148 the generated main program. It can also be debugged just like any other
8149 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8150 @command{gnatbind} and @command{gnatlink}.
8151
8152 @node Switches for gnatbind
8153 @section Switches for @command{gnatbind}
8154
8155 @noindent
8156 The following switches are available with @code{gnatbind}; details will
8157 be presented in subsequent sections.
8158
8159 @menu
8160 * Consistency-Checking Modes::
8161 * Binder Error Message Control::
8162 * Elaboration Control::
8163 * Output Control::
8164 * Dynamic Allocation Control::
8165 * Binding with Non-Ada Main Programs::
8166 * Binding Programs with No Main Subprogram::
8167 @end menu
8168
8169 @table @option
8170 @c !sort!
8171
8172 @item --version
8173 @cindex @option{--version} @command{gnatbind}
8174 Display Copyright and version, then exit disregarding all other options.
8175
8176 @item --help
8177 @cindex @option{--help} @command{gnatbind}
8178 If @option{--version} was not used, display usage, then exit disregarding
8179 all other options.
8180
8181 @item -a
8182 @cindex @option{-a} @command{gnatbind}
8183 Indicates that, if supported by the platform, the adainit procedure should
8184 be treated as an initialisation routine by the linker (a constructor). This
8185 is intended to be used by the Project Manager to automatically initialize
8186 shared Stand-Alone Libraries.
8187
8188 @item ^-aO^/OBJECT_SEARCH^
8189 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8190 Specify directory to be searched for ALI files.
8191
8192 @item ^-aI^/SOURCE_SEARCH^
8193 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8194 Specify directory to be searched for source file.
8195
8196 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8197 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8198 Output ALI list (to standard output or to the named file).
8199
8200 @item ^-b^/REPORT_ERRORS=BRIEF^
8201 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8202 Generate brief messages to @file{stderr} even if verbose mode set.
8203
8204 @item ^-c^/NOOUTPUT^
8205 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8206 Check only, no generation of binder output file.
8207
8208 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8209 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8210 This switch can be used to change the default task stack size value
8211 to a specified size @var{nn}, which is expressed in bytes by default, or
8212 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8213 with @var{m}.
8214 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8215 in effect, to completing all task specs with
8216 @smallexample @c ada
8217 pragma Storage_Size (nn);
8218 @end smallexample
8219 When they do not already have such a pragma.
8220
8221 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8222 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8223 This switch can be used to change the default secondary stack size value
8224 to a specified size @var{nn}, which is expressed in bytes by default, or
8225 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8226 with @var{m}.
8227
8228 The secondary stack is used to deal with functions that return a variable
8229 sized result, for example a function returning an unconstrained
8230 String. There are two ways in which this secondary stack is allocated.
8231
8232 For most targets, the secondary stack is growing on demand and is allocated
8233 as a chain of blocks in the heap. The -D option is not very
8234 relevant. It only give some control over the size of the allocated
8235 blocks (whose size is the minimum of the default secondary stack size value,
8236 and the actual size needed for the current allocation request).
8237
8238 For certain targets, notably VxWorks 653,
8239 the secondary stack is allocated by carving off a fixed ratio chunk of the
8240 primary task stack. The -D option is used to define the
8241 size of the environment task's secondary stack.
8242
8243 @item ^-e^/ELABORATION_DEPENDENCIES^
8244 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8245 Output complete list of elaboration-order dependencies.
8246
8247 @item ^-E^/STORE_TRACEBACKS^
8248 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8249 Store tracebacks in exception occurrences when the target supports it.
8250 @ignore
8251 @c The following may get moved to an appendix
8252 This option is currently supported on the following targets:
8253 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8254 @end ignore
8255 See also the packages @code{GNAT.Traceback} and
8256 @code{GNAT.Traceback.Symbolic} for more information.
8257 @ifclear vms
8258 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8259 @command{gcc} option.
8260 @end ifclear
8261
8262 @item ^-F^/FORCE_ELABS_FLAGS^
8263 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8264 Force the checks of elaboration flags. @command{gnatbind} does not normally
8265 generate checks of elaboration flags for the main executable, except when
8266 a Stand-Alone Library is used. However, there are cases when this cannot be
8267 detected by gnatbind. An example is importing an interface of a Stand-Alone
8268 Library through a pragma Import and only specifying through a linker switch
8269 this Stand-Alone Library. This switch is used to guarantee that elaboration
8270 flag checks are generated.
8271
8272 @item ^-h^/HELP^
8273 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8274 Output usage (help) information
8275
8276 @item ^-H32^/32_MALLOC^
8277 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8278 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8279 For further details see @ref{Dynamic Allocation Control}.
8280
8281 @item ^-H64^/64_MALLOC^
8282 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8283 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8284 @cindex @code{__gnat_malloc}
8285 For further details see @ref{Dynamic Allocation Control}.
8286
8287 @item ^-I^/SEARCH^
8288 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8289 Specify directory to be searched for source and ALI files.
8290
8291 @item ^-I-^/NOCURRENT_DIRECTORY^
8292 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8293 Do not look for sources in the current directory where @code{gnatbind} was
8294 invoked, and do not look for ALI files in the directory containing the
8295 ALI file named in the @code{gnatbind} command line.
8296
8297 @item ^-l^/ORDER_OF_ELABORATION^
8298 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8299 Output chosen elaboration order.
8300
8301 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8302 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8303 Bind the units for library building. In this case the adainit and
8304 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8305 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8306 ^@var{xxx}final^@var{XXX}FINAL^.
8307 Implies ^-n^/NOCOMPILE^.
8308 @ifclear vms
8309 (@xref{GNAT and Libraries}, for more details.)
8310 @end ifclear
8311 @ifset vms
8312 On OpenVMS, these init and final procedures are exported in uppercase
8313 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8314 the init procedure will be "TOTOINIT" and the exported name of the final
8315 procedure will be "TOTOFINAL".
8316 @end ifset
8317
8318 @item ^-Mxyz^/RENAME_MAIN=xyz^
8319 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8320 Rename generated main program from main to xyz. This option is
8321 supported on cross environments only.
8322
8323 @item ^-m^/ERROR_LIMIT=^@var{n}
8324 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8325 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8326 in the range 1..999999. The default value if no switch is
8327 given is 9999. If the number of warnings reaches this limit, then a
8328 message is output and further warnings are suppressed, the bind
8329 continues in this case. If the number of errors reaches this
8330 limit, then a message is output and the bind is abandoned.
8331 A value of zero means that no limit is enforced. The equal
8332 sign is optional.
8333
8334 @ifset unw
8335 Furthermore, under Windows, the sources pointed to by the libraries path
8336 set in the registry are not searched for.
8337 @end ifset
8338
8339 @item ^-n^/NOMAIN^
8340 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8341 No main program.
8342
8343 @item -nostdinc
8344 @cindex @option{-nostdinc} (@command{gnatbind})
8345 Do not look for sources in the system default directory.
8346
8347 @item -nostdlib
8348 @cindex @option{-nostdlib} (@command{gnatbind})
8349 Do not look for library files in the system default directory.
8350
8351 @item --RTS=@var{rts-path}
8352 @cindex @option{--RTS} (@code{gnatbind})
8353 Specifies the default location of the runtime library. Same meaning as the
8354 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8355
8356 @item ^-o ^/OUTPUT=^@var{file}
8357 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8358 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8359 Note that if this option is used, then linking must be done manually,
8360 gnatlink cannot be used.
8361
8362 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8363 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8364 Output object list (to standard output or to the named file).
8365
8366 @item ^-p^/PESSIMISTIC_ELABORATION^
8367 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8368 Pessimistic (worst-case) elaboration order
8369
8370 @item ^-P^-P^
8371 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8372 Generate binder file suitable for CodePeer.
8373
8374 @item ^-R^-R^
8375 @cindex @option{^-R^-R^} (@command{gnatbind})
8376 Output closure source list.
8377
8378 @item ^-s^/READ_SOURCES=ALL^
8379 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8380 Require all source files to be present.
8381
8382 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8383 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8384 Specifies the value to be used when detecting uninitialized scalar
8385 objects with pragma Initialize_Scalars.
8386 The @var{xxx} ^string specified with the switch^option^ may be either
8387 @itemize @bullet
8388 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8389 @item ``@option{^lo^LOW^}'' for the lowest possible value
8390 @item ``@option{^hi^HIGH^}'' for the highest possible value
8391 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8392 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8393 @end itemize
8394
8395 In addition, you can specify @option{-Sev} to indicate that the value is
8396 to be set at run time. In this case, the program will look for an environment
8397 @cindex GNAT_INIT_SCALARS
8398 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8399 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8400 If no environment variable is found, or if it does not have a valid value,
8401 then the default is @option{in} (invalid values).
8402
8403 @ifclear vms
8404 @item -static
8405 @cindex @option{-static} (@code{gnatbind})
8406 Link against a static GNAT run time.
8407
8408 @item -shared
8409 @cindex @option{-shared} (@code{gnatbind})
8410 Link against a shared GNAT run time when available.
8411 @end ifclear
8412
8413 @item ^-t^/NOTIME_STAMP_CHECK^
8414 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8415 Tolerate time stamp and other consistency errors
8416
8417 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8418 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8419 Set the time slice value to @var{n} milliseconds. If the system supports
8420 the specification of a specific time slice value, then the indicated value
8421 is used. If the system does not support specific time slice values, but
8422 does support some general notion of round-robin scheduling, then any
8423 nonzero value will activate round-robin scheduling.
8424
8425 A value of zero is treated specially. It turns off time
8426 slicing, and in addition, indicates to the tasking run time that the
8427 semantics should match as closely as possible the Annex D
8428 requirements of the Ada RM, and in particular sets the default
8429 scheduling policy to @code{FIFO_Within_Priorities}.
8430
8431 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8432 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8433 Enable dynamic stack usage, with @var{n} results stored and displayed
8434 at program termination. A result is generated when a task
8435 terminates. Results that can't be stored are displayed on the fly, at
8436 task termination. This option is currently not supported on Itanium
8437 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8438
8439 @item ^-v^/REPORT_ERRORS=VERBOSE^
8440 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8441 Verbose mode. Write error messages, header, summary output to
8442 @file{stdout}.
8443
8444 @ifclear vms
8445 @item -w@var{x}
8446 @cindex @option{-w} (@code{gnatbind})
8447 Warning mode (@var{x}=s/e for suppress/treat as error)
8448 @end ifclear
8449
8450 @ifset vms
8451 @item /WARNINGS=NORMAL
8452 @cindex @option{/WARNINGS} (@code{gnatbind})
8453 Normal warnings mode. Warnings are issued but ignored
8454
8455 @item /WARNINGS=SUPPRESS
8456 @cindex @option{/WARNINGS} (@code{gnatbind})
8457 All warning messages are suppressed
8458
8459 @item /WARNINGS=ERROR
8460 @cindex @option{/WARNINGS} (@code{gnatbind})
8461 Warning messages are treated as fatal errors
8462 @end ifset
8463
8464 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8465 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8466 Override default wide character encoding for standard Text_IO files.
8467
8468 @item ^-x^/READ_SOURCES=NONE^
8469 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8470 Exclude source files (check object consistency only).
8471
8472 @ifset vms
8473 @item /READ_SOURCES=AVAILABLE
8474 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8475 Default mode, in which sources are checked for consistency only if
8476 they are available.
8477 @end ifset
8478
8479 @item ^-y^/ENABLE_LEAP_SECONDS^
8480 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8481 Enable leap seconds support in @code{Ada.Calendar} and its children.
8482
8483 @item ^-z^/ZERO_MAIN^
8484 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8485 No main subprogram.
8486 @end table
8487
8488 @ifclear vms
8489 @noindent
8490 You may obtain this listing of switches by running @code{gnatbind} with
8491 no arguments.
8492 @end ifclear
8493
8494 @node Consistency-Checking Modes
8495 @subsection Consistency-Checking Modes
8496
8497 @noindent
8498 As described earlier, by default @code{gnatbind} checks
8499 that object files are consistent with one another and are consistent
8500 with any source files it can locate. The following switches control binder
8501 access to sources.
8502
8503 @table @option
8504 @c !sort!
8505 @item ^-s^/READ_SOURCES=ALL^
8506 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8507 Require source files to be present. In this mode, the binder must be
8508 able to locate all source files that are referenced, in order to check
8509 their consistency. In normal mode, if a source file cannot be located it
8510 is simply ignored. If you specify this switch, a missing source
8511 file is an error.
8512
8513 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8514 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8515 Override default wide character encoding for standard Text_IO files.
8516 Normally the default wide character encoding method used for standard
8517 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8518 the main source input (see description of switch
8519 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8520 use of this switch for the binder (which has the same set of
8521 possible arguments) overrides this default as specified.
8522
8523 @item ^-x^/READ_SOURCES=NONE^
8524 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8525 Exclude source files. In this mode, the binder only checks that ALI
8526 files are consistent with one another. Source files are not accessed.
8527 The binder runs faster in this mode, and there is still a guarantee that
8528 the resulting program is self-consistent.
8529 If a source file has been edited since it was last compiled, and you
8530 specify this switch, the binder will not detect that the object
8531 file is out of date with respect to the source file. Note that this is the
8532 mode that is automatically used by @command{gnatmake} because in this
8533 case the checking against sources has already been performed by
8534 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8535
8536 @ifset vms
8537 @item /READ_SOURCES=AVAILABLE
8538 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8539 This is the default mode in which source files are checked if they are
8540 available, and ignored if they are not available.
8541 @end ifset
8542 @end table
8543
8544 @node Binder Error Message Control
8545 @subsection Binder Error Message Control
8546
8547 @noindent
8548 The following switches provide control over the generation of error
8549 messages from the binder:
8550
8551 @table @option
8552 @c !sort!
8553 @item ^-v^/REPORT_ERRORS=VERBOSE^
8554 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8555 Verbose mode. In the normal mode, brief error messages are generated to
8556 @file{stderr}. If this switch is present, a header is written
8557 to @file{stdout} and any error messages are directed to @file{stdout}.
8558 All that is written to @file{stderr} is a brief summary message.
8559
8560 @item ^-b^/REPORT_ERRORS=BRIEF^
8561 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8562 Generate brief error messages to @file{stderr} even if verbose mode is
8563 specified. This is relevant only when used with the
8564 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8565
8566 @ifclear vms
8567 @item -m@var{n}
8568 @cindex @option{-m} (@code{gnatbind})
8569 Limits the number of error messages to @var{n}, a decimal integer in the
8570 range 1-999. The binder terminates immediately if this limit is reached.
8571
8572 @item -M@var{xxx}
8573 @cindex @option{-M} (@code{gnatbind})
8574 Renames the generated main program from @code{main} to @code{xxx}.
8575 This is useful in the case of some cross-building environments, where
8576 the actual main program is separate from the one generated
8577 by @code{gnatbind}.
8578 @end ifclear
8579
8580 @item ^-ws^/WARNINGS=SUPPRESS^
8581 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8582 @cindex Warnings
8583 Suppress all warning messages.
8584
8585 @item ^-we^/WARNINGS=ERROR^
8586 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8587 Treat any warning messages as fatal errors.
8588
8589 @ifset vms
8590 @item /WARNINGS=NORMAL
8591 Standard mode with warnings generated, but warnings do not get treated
8592 as errors.
8593 @end ifset
8594
8595 @item ^-t^/NOTIME_STAMP_CHECK^
8596 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8597 @cindex Time stamp checks, in binder
8598 @cindex Binder consistency checks
8599 @cindex Consistency checks, in binder
8600 The binder performs a number of consistency checks including:
8601
8602 @itemize @bullet
8603 @item
8604 Check that time stamps of a given source unit are consistent
8605 @item
8606 Check that checksums of a given source unit are consistent
8607 @item
8608 Check that consistent versions of @code{GNAT} were used for compilation
8609 @item
8610 Check consistency of configuration pragmas as required
8611 @end itemize
8612
8613 @noindent
8614 Normally failure of such checks, in accordance with the consistency
8615 requirements of the Ada Reference Manual, causes error messages to be
8616 generated which abort the binder and prevent the output of a binder
8617 file and subsequent link to obtain an executable.
8618
8619 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8620 into warnings, so that
8621 binding and linking can continue to completion even in the presence of such
8622 errors. The result may be a failed link (due to missing symbols), or a
8623 non-functional executable which has undefined semantics.
8624 @emph{This means that
8625 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8626 with extreme care.}
8627 @end table
8628
8629 @node Elaboration Control
8630 @subsection Elaboration Control
8631
8632 @noindent
8633 The following switches provide additional control over the elaboration
8634 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8635
8636 @table @option
8637 @item ^-p^/PESSIMISTIC_ELABORATION^
8638 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8639 Normally the binder attempts to choose an elaboration order that is
8640 likely to minimize the likelihood of an elaboration order error resulting
8641 in raising a @code{Program_Error} exception. This switch reverses the
8642 action of the binder, and requests that it deliberately choose an order
8643 that is likely to maximize the likelihood of an elaboration error.
8644 This is useful in ensuring portability and avoiding dependence on
8645 accidental fortuitous elaboration ordering.
8646
8647 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8648 switch if dynamic
8649 elaboration checking is used (@option{-gnatE} switch used for compilation).
8650 This is because in the default static elaboration mode, all necessary
8651 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8652 These implicit pragmas are still respected by the binder in
8653 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8654 safe elaboration order is assured.
8655
8656 Note that @option{^-p^/PESSIMISTIC_ELABORATION^} is not intended for
8657 production use; it is more for debugging/experimental use.
8658 @end table
8659
8660 @node Output Control
8661 @subsection Output Control
8662
8663 @noindent
8664 The following switches allow additional control over the output
8665 generated by the binder.
8666
8667 @table @option
8668 @c !sort!
8669
8670 @item ^-c^/NOOUTPUT^
8671 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8672 Check only. Do not generate the binder output file. In this mode the
8673 binder performs all error checks but does not generate an output file.
8674
8675 @item ^-e^/ELABORATION_DEPENDENCIES^
8676 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8677 Output complete list of elaboration-order dependencies, showing the
8678 reason for each dependency. This output can be rather extensive but may
8679 be useful in diagnosing problems with elaboration order. The output is
8680 written to @file{stdout}.
8681
8682 @item ^-h^/HELP^
8683 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8684 Output usage information. The output is written to @file{stdout}.
8685
8686 @item ^-K^/LINKER_OPTION_LIST^
8687 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8688 Output linker options to @file{stdout}. Includes library search paths,
8689 contents of pragmas Ident and Linker_Options, and libraries added
8690 by @code{gnatbind}.
8691
8692 @item ^-l^/ORDER_OF_ELABORATION^
8693 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8694 Output chosen elaboration order. The output is written to @file{stdout}.
8695
8696 @item ^-O^/OBJECT_LIST^
8697 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8698 Output full names of all the object files that must be linked to provide
8699 the Ada component of the program. The output is written to @file{stdout}.
8700 This list includes the files explicitly supplied and referenced by the user
8701 as well as implicitly referenced run-time unit files. The latter are
8702 omitted if the corresponding units reside in shared libraries. The
8703 directory names for the run-time units depend on the system configuration.
8704
8705 @item ^-o ^/OUTPUT=^@var{file}
8706 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8707 Set name of output file to @var{file} instead of the normal
8708 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8709 binder generated body filename.
8710 Note that if this option is used, then linking must be done manually.
8711 It is not possible to use gnatlink in this case, since it cannot locate
8712 the binder file.
8713
8714 @item ^-r^/RESTRICTION_LIST^
8715 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8716 Generate list of @code{pragma Restrictions} that could be applied to
8717 the current unit. This is useful for code audit purposes, and also may
8718 be used to improve code generation in some cases.
8719
8720 @end table
8721
8722 @node Dynamic Allocation Control
8723 @subsection Dynamic Allocation Control
8724
8725 @noindent
8726 The heap control switches -- @option{-H32} and @option{-H64} --
8727 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8728 They only affect compiler-generated allocations via @code{__gnat_malloc};
8729 explicit calls to @code{malloc} and related functions from the C
8730 run-time library are unaffected.
8731
8732 @table @option
8733 @item -H32
8734 Allocate memory on 32-bit heap
8735
8736 @item -H64
8737 Allocate memory on 64-bit heap. This is the default
8738 unless explicitly overridden by a @code{'Size} clause on the access type.
8739 @end table
8740
8741 @ifset vms
8742 @noindent
8743 See also @ref{Access types and 32/64-bit allocation}.
8744 @end ifset
8745 @ifclear vms
8746 @noindent
8747 These switches are only effective on VMS platforms.
8748 @end ifclear
8749
8750
8751 @node Binding with Non-Ada Main Programs
8752 @subsection Binding with Non-Ada Main Programs
8753
8754 @noindent
8755 In our description so far we have assumed that the main
8756 program is in Ada, and that the task of the binder is to generate a
8757 corresponding function @code{main} that invokes this Ada main
8758 program. GNAT also supports the building of executable programs where
8759 the main program is not in Ada, but some of the called routines are
8760 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8761 The following switch is used in this situation:
8762
8763 @table @option
8764 @item ^-n^/NOMAIN^
8765 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8766 No main program. The main program is not in Ada.
8767 @end table
8768
8769 @noindent
8770 In this case, most of the functions of the binder are still required,
8771 but instead of generating a main program, the binder generates a file
8772 containing the following callable routines:
8773
8774 @table @code
8775 @item adainit
8776 @findex adainit
8777 You must call this routine to initialize the Ada part of the program by
8778 calling the necessary elaboration routines. A call to @code{adainit} is
8779 required before the first call to an Ada subprogram.
8780
8781 Note that it is assumed that the basic execution environment must be setup
8782 to be appropriate for Ada execution at the point where the first Ada
8783 subprogram is called. In particular, if the Ada code will do any
8784 floating-point operations, then the FPU must be setup in an appropriate
8785 manner. For the case of the x86, for example, full precision mode is
8786 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8787 that the FPU is in the right state.
8788
8789 @item adafinal
8790 @findex adafinal
8791 You must call this routine to perform any library-level finalization
8792 required by the Ada subprograms. A call to @code{adafinal} is required
8793 after the last call to an Ada subprogram, and before the program
8794 terminates.
8795 @end table
8796
8797 @noindent
8798 If the @option{^-n^/NOMAIN^} switch
8799 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8800 @cindex Binder, multiple input files
8801 is given, more than one ALI file may appear on
8802 the command line for @code{gnatbind}. The normal @dfn{closure}
8803 calculation is performed for each of the specified units. Calculating
8804 the closure means finding out the set of units involved by tracing
8805 @code{with} references. The reason it is necessary to be able to
8806 specify more than one ALI file is that a given program may invoke two or
8807 more quite separate groups of Ada units.
8808
8809 The binder takes the name of its output file from the last specified ALI
8810 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8811 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8812 The output is an Ada unit in source form that can be compiled with GNAT.
8813 This compilation occurs automatically as part of the @command{gnatlink}
8814 processing.
8815
8816 Currently the GNAT run time requires a FPU using 80 bits mode
8817 precision. Under targets where this is not the default it is required to
8818 call GNAT.Float_Control.Reset before using floating point numbers (this
8819 include float computation, float input and output) in the Ada code. A
8820 side effect is that this could be the wrong mode for the foreign code
8821 where floating point computation could be broken after this call.
8822
8823 @node Binding Programs with No Main Subprogram
8824 @subsection Binding Programs with No Main Subprogram
8825
8826 @noindent
8827 It is possible to have an Ada program which does not have a main
8828 subprogram. This program will call the elaboration routines of all the
8829 packages, then the finalization routines.
8830
8831 The following switch is used to bind programs organized in this manner:
8832
8833 @table @option
8834 @item ^-z^/ZERO_MAIN^
8835 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8836 Normally the binder checks that the unit name given on the command line
8837 corresponds to a suitable main subprogram. When this switch is used,
8838 a list of ALI files can be given, and the execution of the program
8839 consists of elaboration of these units in an appropriate order. Note
8840 that the default wide character encoding method for standard Text_IO
8841 files is always set to Brackets if this switch is set (you can use
8842 the binder switch
8843 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8844 @end table
8845
8846 @node Command-Line Access
8847 @section Command-Line Access
8848
8849 @noindent
8850 The package @code{Ada.Command_Line} provides access to the command-line
8851 arguments and program name. In order for this interface to operate
8852 correctly, the two variables
8853
8854 @smallexample
8855 @group
8856 int gnat_argc;
8857 char **gnat_argv;
8858 @end group
8859 @end smallexample
8860
8861 @noindent
8862 @findex gnat_argv
8863 @findex gnat_argc
8864 are declared in one of the GNAT library routines. These variables must
8865 be set from the actual @code{argc} and @code{argv} values passed to the
8866 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8867 generates the C main program to automatically set these variables.
8868 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8869 set these variables. If they are not set, the procedures in
8870 @code{Ada.Command_Line} will not be available, and any attempt to use
8871 them will raise @code{Constraint_Error}. If command line access is
8872 required, your main program must set @code{gnat_argc} and
8873 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8874 it.
8875
8876 @node Search Paths for gnatbind
8877 @section Search Paths for @code{gnatbind}
8878
8879 @noindent
8880 The binder takes the name of an ALI file as its argument and needs to
8881 locate source files as well as other ALI files to verify object consistency.
8882
8883 For source files, it follows exactly the same search rules as @command{gcc}
8884 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8885 directories searched are:
8886
8887 @enumerate
8888 @item
8889 The directory containing the ALI file named in the command line, unless
8890 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8891
8892 @item
8893 All directories specified by @option{^-I^/SEARCH^}
8894 switches on the @code{gnatbind}
8895 command line, in the order given.
8896
8897 @item
8898 @findex ADA_PRJ_OBJECTS_FILE
8899 Each of the directories listed in the text file whose name is given
8900 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8901
8902 @noindent
8903 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8904 driver when project files are used. It should not normally be set
8905 by other means.
8906
8907 @item
8908 @findex ADA_OBJECTS_PATH
8909 Each of the directories listed in the value of the
8910 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8911 @ifset unw
8912 Construct this value
8913 exactly as the @env{PATH} environment variable: a list of directory
8914 names separated by colons (semicolons when working with the NT version
8915 of GNAT).
8916 @end ifset
8917 @ifset vms
8918 Normally, define this value as a logical name containing a comma separated
8919 list of directory names.
8920
8921 This variable can also be defined by means of an environment string
8922 (an argument to the HP C exec* set of functions).
8923
8924 Logical Name:
8925 @smallexample
8926 DEFINE ANOTHER_PATH FOO:[BAG]
8927 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8928 @end smallexample
8929
8930 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8931 first, followed by the standard Ada
8932 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8933 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8934 (Text_IO, Sequential_IO, etc)
8935 instead of the standard Ada packages. Thus, in order to get the standard Ada
8936 packages by default, ADA_OBJECTS_PATH must be redefined.
8937 @end ifset
8938
8939 @item
8940 The content of the @file{ada_object_path} file which is part of the GNAT
8941 installation tree and is used to store standard libraries such as the
8942 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8943 specified.
8944 @ifclear vms
8945 @ref{Installing a library}
8946 @end ifclear
8947 @end enumerate
8948
8949 @noindent
8950 In the binder the switch @option{^-I^/SEARCH^}
8951 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8952 is used to specify both source and
8953 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8954 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8955 instead if you want to specify
8956 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8957 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8958 if you want to specify library paths
8959 only. This means that for the binder
8960 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8961 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8962 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8963 The binder generates the bind file (a C language source file) in the
8964 current working directory.
8965
8966 @findex Ada
8967 @findex System
8968 @findex Interfaces
8969 @findex GNAT
8970 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8971 children make up the GNAT Run-Time Library, together with the package
8972 GNAT and its children, which contain a set of useful additional
8973 library functions provided by GNAT. The sources for these units are
8974 needed by the compiler and are kept together in one directory. The ALI
8975 files and object files generated by compiling the RTL are needed by the
8976 binder and the linker and are kept together in one directory, typically
8977 different from the directory containing the sources. In a normal
8978 installation, you need not specify these directory names when compiling
8979 or binding. Either the environment variables or the built-in defaults
8980 cause these files to be found.
8981
8982 Besides simplifying access to the RTL, a major use of search paths is
8983 in compiling sources from multiple directories. This can make
8984 development environments much more flexible.
8985
8986 @node Examples of gnatbind Usage
8987 @section Examples of @code{gnatbind} Usage
8988
8989 @noindent
8990 This section contains a number of examples of using the GNAT binding
8991 utility @code{gnatbind}.
8992
8993 @table @code
8994 @item gnatbind hello
8995 The main program @code{Hello} (source program in @file{hello.adb}) is
8996 bound using the standard switch settings. The generated main program is
8997 @file{b~hello.adb}. This is the normal, default use of the binder.
8998
8999 @ifclear vms
9000 @item gnatbind hello -o mainprog.adb
9001 @end ifclear
9002 @ifset vms
9003 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
9004 @end ifset
9005 The main program @code{Hello} (source program in @file{hello.adb}) is
9006 bound using the standard switch settings. The generated main program is
9007 @file{mainprog.adb} with the associated spec in
9008 @file{mainprog.ads}. Note that you must specify the body here not the
9009 spec. Note that if this option is used, then linking must be done manually,
9010 since gnatlink will not be able to find the generated file.
9011 @end table
9012
9013 @c ------------------------------------
9014 @node Linking with gnatlink
9015 @chapter Linking with @command{gnatlink}
9016 @c ------------------------------------
9017 @findex gnatlink
9018
9019 @noindent
9020 This chapter discusses @command{gnatlink}, a tool that links
9021 an Ada program and builds an executable file. This utility
9022 invokes the system linker ^(via the @command{gcc} command)^^
9023 with a correct list of object files and library references.
9024 @command{gnatlink} automatically determines the list of files and
9025 references for the Ada part of a program. It uses the binder file
9026 generated by the @command{gnatbind} to determine this list.
9027
9028 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
9029 driver (see @ref{The GNAT Driver and Project Files}).
9030
9031 @menu
9032 * Running gnatlink::
9033 * Switches for gnatlink::
9034 @end menu
9035
9036 @node Running gnatlink
9037 @section Running @command{gnatlink}
9038
9039 @noindent
9040 The form of the @command{gnatlink} command is
9041
9042 @smallexample
9043 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
9044 @c @ovar{non-Ada objects} @ovar{linker options}
9045 @c Expanding @ovar macro inline (explanation in macro def comments)
9046 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
9047 @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
9048
9049 @end smallexample
9050
9051 @noindent
9052 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
9053 non-Ada objects
9054 or linker options) may be in any order, provided that no non-Ada object may
9055 be mistaken for a main @file{ALI} file.
9056 Any file name @file{F} without the @file{.ali}
9057 extension will be taken as the main @file{ALI} file if a file exists
9058 whose name is the concatenation of @file{F} and @file{.ali}.
9059
9060 @noindent
9061 @file{@var{mainprog}.ali} references the ALI file of the main program.
9062 The @file{.ali} extension of this file can be omitted. From this
9063 reference, @command{gnatlink} locates the corresponding binder file
9064 @file{b~@var{mainprog}.adb} and, using the information in this file along
9065 with the list of non-Ada objects and linker options, constructs a
9066 linker command file to create the executable.
9067
9068 The arguments other than the @command{gnatlink} switches and the main
9069 @file{ALI} file are passed to the linker uninterpreted.
9070 They typically include the names of
9071 object files for units written in other languages than Ada and any library
9072 references required to resolve references in any of these foreign language
9073 units, or in @code{Import} pragmas in any Ada units.
9074
9075 @var{linker options} is an optional list of linker specific
9076 switches.
9077 The default linker called by gnatlink is @command{gcc} which in
9078 turn calls the appropriate system linker.
9079
9080 One useful option for the linker is @option{-s}: it reduces the size of the
9081 executable by removing all symbol table and relocation information from the
9082 executable.
9083
9084 Standard options for the linker such as @option{-lmy_lib} or
9085 @option{-Ldir} can be added as is.
9086 For options that are not recognized by
9087 @command{gcc} as linker options, use the @command{gcc} switches
9088 @option{-Xlinker} or @option{-Wl,}.
9089
9090 Refer to the GCC documentation for
9091 details.
9092
9093 Here is an example showing how to generate a linker map:
9094
9095 @smallexample
9096 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9097 @end smallexample
9098
9099 Using @var{linker options} it is possible to set the program stack and
9100 heap size.
9101 @ifset unw
9102 See @ref{Setting Stack Size from gnatlink} and
9103 @ref{Setting Heap Size from gnatlink}.
9104 @end ifset
9105
9106 @command{gnatlink} determines the list of objects required by the Ada
9107 program and prepends them to the list of objects passed to the linker.
9108 @command{gnatlink} also gathers any arguments set by the use of
9109 @code{pragma Linker_Options} and adds them to the list of arguments
9110 presented to the linker.
9111
9112 @ifset vms
9113 @command{gnatlink} accepts the following types of extra files on the command
9114 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9115 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9116 handled according to their extension.
9117 @end ifset
9118
9119 @node Switches for gnatlink
9120 @section Switches for @command{gnatlink}
9121
9122 @noindent
9123 The following switches are available with the @command{gnatlink} utility:
9124
9125 @table @option
9126 @c !sort!
9127
9128 @item --version
9129 @cindex @option{--version} @command{gnatlink}
9130 Display Copyright and version, then exit disregarding all other options.
9131
9132 @item --help
9133 @cindex @option{--help} @command{gnatlink}
9134 If @option{--version} was not used, display usage, then exit disregarding
9135 all other options.
9136
9137 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9138 @cindex Command line length
9139 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9140 On some targets, the command line length is limited, and @command{gnatlink}
9141 will generate a separate file for the linker if the list of object files
9142 is too long.
9143 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9144 to be generated even if
9145 the limit is not exceeded. This is useful in some cases to deal with
9146 special situations where the command line length is exceeded.
9147
9148 @item ^-g^/DEBUG^
9149 @cindex Debugging information, including
9150 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9151 The option to include debugging information causes the Ada bind file (in
9152 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9153 @option{^-g^/DEBUG^}.
9154 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9155 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9156 Without @option{^-g^/DEBUG^}, the binder removes these files by
9157 default. The same procedure apply if a C bind file was generated using
9158 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9159 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9160
9161 @item ^-n^/NOCOMPILE^
9162 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9163 Do not compile the file generated by the binder. This may be used when
9164 a link is rerun with different options, but there is no need to recompile
9165 the binder file.
9166
9167 @item ^-v^/VERBOSE^
9168 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9169 Causes additional information to be output, including a full list of the
9170 included object files. This switch option is most useful when you want
9171 to see what set of object files are being used in the link step.
9172
9173 @item ^-v -v^/VERBOSE/VERBOSE^
9174 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9175 Very verbose mode. Requests that the compiler operate in verbose mode when
9176 it compiles the binder file, and that the system linker run in verbose mode.
9177
9178 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9179 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9180 @var{exec-name} specifies an alternate name for the generated
9181 executable program. If this switch is omitted, the executable has the same
9182 name as the main unit. For example, @code{gnatlink try.ali} creates
9183 an executable called @file{^try^TRY.EXE^}.
9184
9185 @ifclear vms
9186 @item -b @var{target}
9187 @cindex @option{-b} (@command{gnatlink})
9188 Compile your program to run on @var{target}, which is the name of a
9189 system configuration. You must have a GNAT cross-compiler built if
9190 @var{target} is not the same as your host system.
9191
9192 @item -B@var{dir}
9193 @cindex @option{-B} (@command{gnatlink})
9194 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9195 from @var{dir} instead of the default location. Only use this switch
9196 when multiple versions of the GNAT compiler are available.
9197 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9198 for further details. You would normally use the @option{-b} or
9199 @option{-V} switch instead.
9200
9201 @item -M
9202 When linking an executable, create a map file. The name of the map file
9203 has the same name as the executable with extension ".map".
9204
9205 @item -M=mapfile
9206 When linking an executable, create a map file. The name of the map file is
9207 "mapfile".
9208
9209 @item --GCC=@var{compiler_name}
9210 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9211 Program used for compiling the binder file. The default is
9212 @command{gcc}. You need to use quotes around @var{compiler_name} if
9213 @code{compiler_name} contains spaces or other separator characters.
9214 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9215 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9216 inserted after your command name. Thus in the above example the compiler
9217 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9218 A limitation of this syntax is that the name and path name of the executable
9219 itself must not include any embedded spaces. If the compiler executable is
9220 different from the default one (gcc or <prefix>-gcc), then the back-end
9221 switches in the ALI file are not used to compile the binder generated source.
9222 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9223 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9224 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9225 is taken into account. However, all the additional switches are also taken
9226 into account. Thus,
9227 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9228 @option{--GCC="bar -x -y -z -t"}.
9229
9230 @item --LINK=@var{name}
9231 @cindex @option{--LINK=} (@command{gnatlink})
9232 @var{name} is the name of the linker to be invoked. This is especially
9233 useful in mixed language programs since languages such as C++ require
9234 their own linker to be used. When this switch is omitted, the default
9235 name for the linker is @command{gcc}. When this switch is used, the
9236 specified linker is called instead of @command{gcc} with exactly the same
9237 parameters that would have been passed to @command{gcc} so if the desired
9238 linker requires different parameters it is necessary to use a wrapper
9239 script that massages the parameters before invoking the real linker. It
9240 may be useful to control the exact invocation by using the verbose
9241 switch.
9242
9243 @end ifclear
9244
9245 @ifset vms
9246 @item /DEBUG=TRACEBACK
9247 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9248 This qualifier causes sufficient information to be included in the
9249 executable file to allow a traceback, but does not include the full
9250 symbol information needed by the debugger.
9251
9252 @item /IDENTIFICATION="<string>"
9253 @code{"<string>"} specifies the string to be stored in the image file
9254 identification field in the image header.
9255 It overrides any pragma @code{Ident} specified string.
9256
9257 @item /NOINHIBIT-EXEC
9258 Generate the executable file even if there are linker warnings.
9259
9260 @item /NOSTART_FILES
9261 Don't link in the object file containing the ``main'' transfer address.
9262 Used when linking with a foreign language main program compiled with an
9263 HP compiler.
9264
9265 @item /STATIC
9266 Prefer linking with object libraries over sharable images, even without
9267 /DEBUG.
9268 @end ifset
9269
9270 @end table
9271
9272 @node The GNAT Make Program gnatmake
9273 @chapter The GNAT Make Program @command{gnatmake}
9274 @findex gnatmake
9275
9276 @menu
9277 * Running gnatmake::
9278 * Switches for gnatmake::
9279 * Mode Switches for gnatmake::
9280 * Notes on the Command Line::
9281 * How gnatmake Works::
9282 * Examples of gnatmake Usage::
9283 @end menu
9284 @noindent
9285 A typical development cycle when working on an Ada program consists of
9286 the following steps:
9287
9288 @enumerate
9289 @item
9290 Edit some sources to fix bugs.
9291
9292 @item
9293 Add enhancements.
9294
9295 @item
9296 Compile all sources affected.
9297
9298 @item
9299 Rebind and relink.
9300
9301 @item
9302 Test.
9303 @end enumerate
9304
9305 @noindent
9306 The third step can be tricky, because not only do the modified files
9307 @cindex Dependency rules
9308 have to be compiled, but any files depending on these files must also be
9309 recompiled. The dependency rules in Ada can be quite complex, especially
9310 in the presence of overloading, @code{use} clauses, generics and inlined
9311 subprograms.
9312
9313 @command{gnatmake} automatically takes care of the third and fourth steps
9314 of this process. It determines which sources need to be compiled,
9315 compiles them, and binds and links the resulting object files.
9316
9317 Unlike some other Ada make programs, the dependencies are always
9318 accurately recomputed from the new sources. The source based approach of
9319 the GNAT compilation model makes this possible. This means that if
9320 changes to the source program cause corresponding changes in
9321 dependencies, they will always be tracked exactly correctly by
9322 @command{gnatmake}.
9323
9324 @node Running gnatmake
9325 @section Running @command{gnatmake}
9326
9327 @noindent
9328 The usual form of the @command{gnatmake} command is
9329
9330 @smallexample
9331 @c $ gnatmake @ovar{switches} @var{file_name}
9332 @c @ovar{file_names} @ovar{mode_switches}
9333 @c Expanding @ovar macro inline (explanation in macro def comments)
9334 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9335 @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9336 @end smallexample
9337
9338 @noindent
9339 The only required argument is one @var{file_name}, which specifies
9340 a compilation unit that is a main program. Several @var{file_names} can be
9341 specified: this will result in several executables being built.
9342 If @code{switches} are present, they can be placed before the first
9343 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9344 If @var{mode_switches} are present, they must always be placed after
9345 the last @var{file_name} and all @code{switches}.
9346
9347 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9348 extension may be omitted from the @var{file_name} arguments. However, if
9349 you are using non-standard extensions, then it is required that the
9350 extension be given. A relative or absolute directory path can be
9351 specified in a @var{file_name}, in which case, the input source file will
9352 be searched for in the specified directory only. Otherwise, the input
9353 source file will first be searched in the directory where
9354 @command{gnatmake} was invoked and if it is not found, it will be search on
9355 the source path of the compiler as described in
9356 @ref{Search Paths and the Run-Time Library (RTL)}.
9357
9358 All @command{gnatmake} output (except when you specify
9359 @option{^-M^/DEPENDENCIES_LIST^}) is to
9360 @file{stderr}. The output produced by the
9361 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9362 @file{stdout}.
9363
9364 @node Switches for gnatmake
9365 @section Switches for @command{gnatmake}
9366
9367 @noindent
9368 You may specify any of the following switches to @command{gnatmake}:
9369
9370 @table @option
9371 @c !sort!
9372
9373 @item --version
9374 @cindex @option{--version} @command{gnatmake}
9375 Display Copyright and version, then exit disregarding all other options.
9376
9377 @item --help
9378 @cindex @option{--help} @command{gnatmake}
9379 If @option{--version} was not used, display usage, then exit disregarding
9380 all other options.
9381
9382 @ifclear vms
9383 @item --GCC=@var{compiler_name}
9384 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9385 Program used for compiling. The default is `@command{gcc}'. You need to use
9386 quotes around @var{compiler_name} if @code{compiler_name} contains
9387 spaces or other separator characters. As an example @option{--GCC="foo -x
9388 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9389 compiler. A limitation of this syntax is that the name and path name of
9390 the executable itself must not include any embedded spaces. Note that
9391 switch @option{-c} is always inserted after your command name. Thus in the
9392 above example the compiler command that will be used by @command{gnatmake}
9393 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9394 used, only the last @var{compiler_name} is taken into account. However,
9395 all the additional switches are also taken into account. Thus,
9396 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9397 @option{--GCC="bar -x -y -z -t"}.
9398
9399 @item --GNATBIND=@var{binder_name}
9400 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9401 Program used for binding. The default is `@code{gnatbind}'. You need to
9402 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9403 or other separator characters. As an example @option{--GNATBIND="bar -x
9404 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9405 binder. Binder switches that are normally appended by @command{gnatmake}
9406 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9407 A limitation of this syntax is that the name and path name of the executable
9408 itself must not include any embedded spaces.
9409
9410 @item --GNATLINK=@var{linker_name}
9411 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9412 Program used for linking. The default is `@command{gnatlink}'. You need to
9413 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9414 or other separator characters. As an example @option{--GNATLINK="lan -x
9415 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9416 linker. Linker switches that are normally appended by @command{gnatmake} to
9417 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9418 A limitation of this syntax is that the name and path name of the executable
9419 itself must not include any embedded spaces.
9420
9421 @end ifclear
9422
9423 @item ^--subdirs^/SUBDIRS^=subdir
9424 Actual object directory of each project file is the subdirectory subdir of the
9425 object directory specified or defaulted in the project file.
9426
9427 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9428 Disallow simultaneous compilations in the same object directory when
9429 project files are used.
9430
9431 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9432 By default, shared library projects are not allowed to import static library
9433 projects. When this switch is used on the command line, this restriction is
9434 relaxed.
9435
9436 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9437 Specify a source info file. This switch is active only when project files
9438 are used. If the source info file is specified as a relative path, then it is
9439 relative to the object directory of the main project. If the source info file
9440 does not exist, then after the Project Manager has successfully parsed and
9441 processed the project files and found the sources, it creates the source info
9442 file. If the source info file already exists and can be read successfully,
9443 then the Project Manager will get all the needed information about the sources
9444 from the source info file and will not look for them. This reduces the time
9445 to process the project files, especially when looking for sources that take a
9446 long time. If the source info file exists but cannot be parsed successfully,
9447 the Project Manager will attempt to recreate it. If the Project Manager fails
9448 to create the source info file, a message is issued, but gnatmake does not
9449 fail. @command{gnatmake} "trusts" the source info file. This means that
9450 if the source files have changed (addition, deletion, moving to a different
9451 source directory), then the source info file need to be deleted and recreated.
9452
9453 @ifclear vms
9454 @item --create-map-file
9455 When linking an executable, create a map file. The name of the map file
9456 has the same name as the executable with extension ".map".
9457
9458 @item --create-map-file=mapfile
9459 When linking an executable, create a map file. The name of the map file is
9460 "mapfile".
9461
9462 @end ifclear
9463
9464 @item ^-a^/ALL_FILES^
9465 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9466 Consider all files in the make process, even the GNAT internal system
9467 files (for example, the predefined Ada library files), as well as any
9468 locked files. Locked files are files whose ALI file is write-protected.
9469 By default,
9470 @command{gnatmake} does not check these files,
9471 because the assumption is that the GNAT internal files are properly up
9472 to date, and also that any write protected ALI files have been properly
9473 installed. Note that if there is an installation problem, such that one
9474 of these files is not up to date, it will be properly caught by the
9475 binder.
9476 You may have to specify this switch if you are working on GNAT
9477 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9478 in conjunction with @option{^-f^/FORCE_COMPILE^}
9479 if you need to recompile an entire application,
9480 including run-time files, using special configuration pragmas,
9481 such as a @code{Normalize_Scalars} pragma.
9482
9483 By default
9484 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9485 internal files with
9486 @ifclear vms
9487 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9488 @end ifclear
9489 @ifset vms
9490 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9491 @end ifset
9492
9493 @item ^-b^/ACTIONS=BIND^
9494 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9495 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9496 compilation and binding, but no link.
9497 Can be combined with @option{^-l^/ACTIONS=LINK^}
9498 to do binding and linking. When not combined with
9499 @option{^-c^/ACTIONS=COMPILE^}
9500 all the units in the closure of the main program must have been previously
9501 compiled and must be up to date. The root unit specified by @var{file_name}
9502 may be given without extension, with the source extension or, if no GNAT
9503 Project File is specified, with the ALI file extension.
9504
9505 @item ^-c^/ACTIONS=COMPILE^
9506 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9507 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9508 is also specified. Do not perform linking, except if both
9509 @option{^-b^/ACTIONS=BIND^} and
9510 @option{^-l^/ACTIONS=LINK^} are also specified.
9511 If the root unit specified by @var{file_name} is not a main unit, this is the
9512 default. Otherwise @command{gnatmake} will attempt binding and linking
9513 unless all objects are up to date and the executable is more recent than
9514 the objects.
9515
9516 @item ^-C^/MAPPING^
9517 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9518 Use a temporary mapping file. A mapping file is a way to communicate
9519 to the compiler two mappings: from unit names to file names (without
9520 any directory information) and from file names to path names (with
9521 full directory information). A mapping file can make the compiler's
9522 file searches faster, especially if there are many source directories,
9523 or the sources are read over a slow network connection. If
9524 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9525 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9526 is initially populated based on the project file. If
9527 @option{^-C^/MAPPING^} is used without
9528 @option{^-P^/PROJECT_FILE^},
9529 the mapping file is initially empty. Each invocation of the compiler
9530 will add any newly accessed sources to the mapping file.
9531
9532 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9533 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9534 Use a specific mapping file. The file, specified as a path name (absolute or
9535 relative) by this switch, should already exist, otherwise the switch is
9536 ineffective. The specified mapping file will be communicated to the compiler.
9537 This switch is not compatible with a project file
9538 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9539 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9540
9541 @item ^-d^/DISPLAY_PROGRESS^
9542 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9543 Display progress for each source, up to date or not, as a single line
9544
9545 @smallexample
9546 completed x out of y (zz%)
9547 @end smallexample
9548
9549 If the file needs to be compiled this is displayed after the invocation of
9550 the compiler. These lines are displayed even in quiet output mode.
9551
9552 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9553 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9554 Put all object files and ALI file in directory @var{dir}.
9555 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9556 and ALI files go in the current working directory.
9557
9558 This switch cannot be used when using a project file.
9559
9560 @item -eInnn
9561 @cindex @option{-eI} (@command{gnatmake})
9562 Indicates that the main source is a multi-unit source and the rank of the unit
9563 in the source file is nnn. nnn needs to be a positive number and a valid
9564 index in the source. This switch cannot be used when @command{gnatmake} is
9565 invoked for several mains.
9566
9567 @ifclear vms
9568 @item -eL
9569 @cindex @option{-eL} (@command{gnatmake})
9570 @cindex symbolic links
9571 Follow all symbolic links when processing project files.
9572 This should be used if your project uses symbolic links for files or
9573 directories, but is not needed in other cases.
9574
9575 @cindex naming scheme
9576 This also assumes that no directory matches the naming scheme for files (for
9577 instance that you do not have a directory called "sources.ads" when using the
9578 default GNAT naming scheme).
9579
9580 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9581 save a lot of system calls (several per source file and object file), which
9582 can result in a significant speed up to load and manipulate a project file,
9583 especially when using source files from a remote system.
9584
9585 @end ifclear
9586
9587 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9588 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9589 Output the commands for the compiler, the binder and the linker
9590 on ^standard output^SYS$OUTPUT^,
9591 instead of ^standard error^SYS$ERROR^.
9592
9593 @item ^-f^/FORCE_COMPILE^
9594 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9595 Force recompilations. Recompile all sources, even though some object
9596 files may be up to date, but don't recompile predefined or GNAT internal
9597 files or locked files (files with a write-protected ALI file),
9598 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9599
9600 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9601 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9602 When using project files, if some errors or warnings are detected during
9603 parsing and verbose mode is not in effect (no use of switch
9604 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9605 file, rather than its simple file name.
9606
9607 @item ^-g^/DEBUG^
9608 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9609 Enable debugging. This switch is simply passed to the compiler and to the
9610 linker.
9611
9612 @item ^-i^/IN_PLACE^
9613 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9614 In normal mode, @command{gnatmake} compiles all object files and ALI files
9615 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9616 then instead object files and ALI files that already exist are overwritten
9617 in place. This means that once a large project is organized into separate
9618 directories in the desired manner, then @command{gnatmake} will automatically
9619 maintain and update this organization. If no ALI files are found on the
9620 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9621 the new object and ALI files are created in the
9622 directory containing the source being compiled. If another organization
9623 is desired, where objects and sources are kept in different directories,
9624 a useful technique is to create dummy ALI files in the desired directories.
9625 When detecting such a dummy file, @command{gnatmake} will be forced to
9626 recompile the corresponding source file, and it will be put the resulting
9627 object and ALI files in the directory where it found the dummy file.
9628
9629 @item ^-j^/PROCESSES=^@var{n}
9630 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9631 @cindex Parallel make
9632 Use @var{n} processes to carry out the (re)compilations. On a multiprocessor
9633 machine compilations will occur in parallel. If @var{n} is 0, then the
9634 maximum number of parallel compilations is the number of core processors
9635 on the platform. In the event of compilation errors, messages from various
9636 compilations might get interspersed (but @command{gnatmake} will give you the
9637 full ordered list of failing compiles at the end). If this is problematic,
9638 rerun the make process with n set to 1 to get a clean list of messages.
9639
9640 @item ^-k^/CONTINUE_ON_ERROR^
9641 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9642 Keep going. Continue as much as possible after a compilation error. To
9643 ease the programmer's task in case of compilation errors, the list of
9644 sources for which the compile fails is given when @command{gnatmake}
9645 terminates.
9646
9647 If @command{gnatmake} is invoked with several @file{file_names} and with this
9648 switch, if there are compilation errors when building an executable,
9649 @command{gnatmake} will not attempt to build the following executables.
9650
9651 @item ^-l^/ACTIONS=LINK^
9652 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9653 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9654 and linking. Linking will not be performed if combined with
9655 @option{^-c^/ACTIONS=COMPILE^}
9656 but not with @option{^-b^/ACTIONS=BIND^}.
9657 When not combined with @option{^-b^/ACTIONS=BIND^}
9658 all the units in the closure of the main program must have been previously
9659 compiled and must be up to date, and the main program needs to have been bound.
9660 The root unit specified by @var{file_name}
9661 may be given without extension, with the source extension or, if no GNAT
9662 Project File is specified, with the ALI file extension.
9663
9664 @item ^-m^/MINIMAL_RECOMPILATION^
9665 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9666 Specify that the minimum necessary amount of recompilations
9667 be performed. In this mode @command{gnatmake} ignores time
9668 stamp differences when the only
9669 modifications to a source file consist in adding/removing comments,
9670 empty lines, spaces or tabs. This means that if you have changed the
9671 comments in a source file or have simply reformatted it, using this
9672 switch will tell @command{gnatmake} not to recompile files that depend on it
9673 (provided other sources on which these files depend have undergone no
9674 semantic modifications). Note that the debugging information may be
9675 out of date with respect to the sources if the @option{-m} switch causes
9676 a compilation to be switched, so the use of this switch represents a
9677 trade-off between compilation time and accurate debugging information.
9678
9679 @item ^-M^/DEPENDENCIES_LIST^
9680 @cindex Dependencies, producing list
9681 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9682 Check if all objects are up to date. If they are, output the object
9683 dependences to @file{stdout} in a form that can be directly exploited in
9684 a @file{Makefile}. By default, each source file is prefixed with its
9685 (relative or absolute) directory name. This name is whatever you
9686 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9687 and @option{^-I^/SEARCH^} switches. If you use
9688 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9689 @option{^-q^/QUIET^}
9690 (see below), only the source file names,
9691 without relative paths, are output. If you just specify the
9692 @option{^-M^/DEPENDENCIES_LIST^}
9693 switch, dependencies of the GNAT internal system files are omitted. This
9694 is typically what you want. If you also specify
9695 the @option{^-a^/ALL_FILES^} switch,
9696 dependencies of the GNAT internal files are also listed. Note that
9697 dependencies of the objects in external Ada libraries (see switch
9698 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9699 are never reported.
9700
9701 @item ^-n^/DO_OBJECT_CHECK^
9702 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9703 Don't compile, bind, or link. Checks if all objects are up to date.
9704 If they are not, the full name of the first file that needs to be
9705 recompiled is printed.
9706 Repeated use of this option, followed by compiling the indicated source
9707 file, will eventually result in recompiling all required units.
9708
9709 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9710 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9711 Output executable name. The name of the final executable program will be
9712 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9713 name for the executable will be the name of the input file in appropriate form
9714 for an executable file on the host system.
9715
9716 This switch cannot be used when invoking @command{gnatmake} with several
9717 @file{file_names}.
9718
9719 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9720 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9721 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9722 automatically missing object directories, library directories and exec
9723 directories.
9724
9725 @item ^-P^/PROJECT_FILE=^@var{project}
9726 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9727 Use project file @var{project}. Only one such switch can be used.
9728 @xref{gnatmake and Project Files}.
9729
9730 @item ^-q^/QUIET^
9731 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9732 Quiet. When this flag is not set, the commands carried out by
9733 @command{gnatmake} are displayed.
9734
9735 @item ^-s^/SWITCH_CHECK/^
9736 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9737 Recompile if compiler switches have changed since last compilation.
9738 All compiler switches but -I and -o are taken into account in the
9739 following way:
9740 orders between different ``first letter'' switches are ignored, but
9741 orders between same switches are taken into account. For example,
9742 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9743 is equivalent to @option{-O -g}.
9744
9745 This switch is recommended when Integrated Preprocessing is used.
9746
9747 @item ^-u^/UNIQUE^
9748 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9749 Unique. Recompile at most the main files. It implies -c. Combined with
9750 -f, it is equivalent to calling the compiler directly. Note that using
9751 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9752 (@pxref{Project Files and Main Subprograms}).
9753
9754 @item ^-U^/ALL_PROJECTS^
9755 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9756 When used without a project file or with one or several mains on the command
9757 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9758 on the command line, all sources of all project files are checked and compiled
9759 if not up to date, and libraries are rebuilt, if necessary.
9760
9761 @item ^-v^/REASONS^
9762 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9763 Verbose. Display the reason for all recompilations @command{gnatmake}
9764 decides are necessary, with the highest verbosity level.
9765
9766 @item ^-vl^/LOW_VERBOSITY^
9767 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9768 Verbosity level Low. Display fewer lines than in verbosity Medium.
9769
9770 @item ^-vm^/MEDIUM_VERBOSITY^
9771 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9772 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9773
9774 @item ^-vh^/HIGH_VERBOSITY^
9775 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9776 Verbosity level High. Equivalent to ^-v^/REASONS^.
9777
9778 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9779 Indicate the verbosity of the parsing of GNAT project files.
9780 @xref{Switches Related to Project Files}.
9781
9782 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9783 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9784 Indicate that sources that are not part of any Project File may be compiled.
9785 Normally, when using Project Files, only sources that are part of a Project
9786 File may be compile. When this switch is used, a source outside of all Project
9787 Files may be compiled. The ALI file and the object file will be put in the
9788 object directory of the main Project. The compilation switches used will only
9789 be those specified on the command line. Even when
9790 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9791 command line need to be sources of a project file.
9792
9793 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9794 Indicate that external variable @var{name} has the value @var{value}.
9795 The Project Manager will use this value for occurrences of
9796 @code{external(name)} when parsing the project file.
9797 @xref{Switches Related to Project Files}.
9798
9799 @item ^-z^/NOMAIN^
9800 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9801 No main subprogram. Bind and link the program even if the unit name
9802 given on the command line is a package name. The resulting executable
9803 will execute the elaboration routines of the package and its closure,
9804 then the finalization routines.
9805
9806 @end table
9807
9808 @table @asis
9809 @item @command{gcc} @asis{switches}
9810 @ifclear vms
9811 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9812 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9813 @end ifclear
9814 @ifset vms
9815 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9816 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9817 automatically treated as a compiler switch, and passed on to all
9818 compilations that are carried out.
9819 @end ifset
9820 @end table
9821
9822 @noindent
9823 Source and library search path switches:
9824
9825 @table @option
9826 @c !sort!
9827 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9828 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9829 When looking for source files also look in directory @var{dir}.
9830 The order in which source files search is undertaken is
9831 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9832
9833 @item ^-aL^/SKIP_MISSING=^@var{dir}
9834 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9835 Consider @var{dir} as being an externally provided Ada library.
9836 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9837 files have been located in directory @var{dir}. This allows you to have
9838 missing bodies for the units in @var{dir} and to ignore out of date bodies
9839 for the same units. You still need to specify
9840 the location of the specs for these units by using the switches
9841 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9842 or @option{^-I^/SEARCH=^@var{dir}}.
9843 Note: this switch is provided for compatibility with previous versions
9844 of @command{gnatmake}. The easier method of causing standard libraries
9845 to be excluded from consideration is to write-protect the corresponding
9846 ALI files.
9847
9848 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9849 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9850 When searching for library and object files, look in directory
9851 @var{dir}. The order in which library files are searched is described in
9852 @ref{Search Paths for gnatbind}.
9853
9854 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9855 @cindex Search paths, for @command{gnatmake}
9856 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9857 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9858 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9859
9860 @item ^-I^/SEARCH=^@var{dir}
9861 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9862 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9863 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9864
9865 @item ^-I-^/NOCURRENT_DIRECTORY^
9866 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9867 @cindex Source files, suppressing search
9868 Do not look for source files in the directory containing the source
9869 file named in the command line.
9870 Do not look for ALI or object files in the directory
9871 where @command{gnatmake} was invoked.
9872
9873 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9874 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9875 @cindex Linker libraries
9876 Add directory @var{dir} to the list of directories in which the linker
9877 will search for libraries. This is equivalent to
9878 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9879 @ifclear vms
9880 Furthermore, under Windows, the sources pointed to by the libraries path
9881 set in the registry are not searched for.
9882 @end ifclear
9883
9884 @item -nostdinc
9885 @cindex @option{-nostdinc} (@command{gnatmake})
9886 Do not look for source files in the system default directory.
9887
9888 @item -nostdlib
9889 @cindex @option{-nostdlib} (@command{gnatmake})
9890 Do not look for library files in the system default directory.
9891
9892 @item --RTS=@var{rts-path}
9893 @cindex @option{--RTS} (@command{gnatmake})
9894 Specifies the default location of the runtime library. GNAT looks for the
9895 runtime
9896 in the following directories, and stops as soon as a valid runtime is found
9897 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9898 @file{ada_object_path} present):
9899
9900 @itemize @bullet
9901 @item <current directory>/$rts_path
9902
9903 @item <default-search-dir>/$rts_path
9904
9905 @item <default-search-dir>/rts-$rts_path
9906 @end itemize
9907
9908 @noindent
9909 The selected path is handled like a normal RTS path.
9910
9911 @end table
9912
9913 @node Mode Switches for gnatmake
9914 @section Mode Switches for @command{gnatmake}
9915
9916 @noindent
9917 The mode switches (referred to as @code{mode_switches}) allow the
9918 inclusion of switches that are to be passed to the compiler itself, the
9919 binder or the linker. The effect of a mode switch is to cause all
9920 subsequent switches up to the end of the switch list, or up to the next
9921 mode switch, to be interpreted as switches to be passed on to the
9922 designated component of GNAT.
9923
9924 @table @option
9925 @c !sort!
9926 @item -cargs @var{switches}
9927 @cindex @option{-cargs} (@command{gnatmake})
9928 Compiler switches. Here @var{switches} is a list of switches
9929 that are valid switches for @command{gcc}. They will be passed on to
9930 all compile steps performed by @command{gnatmake}.
9931
9932 @item -bargs @var{switches}
9933 @cindex @option{-bargs} (@command{gnatmake})
9934 Binder switches. Here @var{switches} is a list of switches
9935 that are valid switches for @code{gnatbind}. They will be passed on to
9936 all bind steps performed by @command{gnatmake}.
9937
9938 @item -largs @var{switches}
9939 @cindex @option{-largs} (@command{gnatmake})
9940 Linker switches. Here @var{switches} is a list of switches
9941 that are valid switches for @command{gnatlink}. They will be passed on to
9942 all link steps performed by @command{gnatmake}.
9943
9944 @item -margs @var{switches}
9945 @cindex @option{-margs} (@command{gnatmake})
9946 Make switches. The switches are directly interpreted by @command{gnatmake},
9947 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9948 or @option{-largs}.
9949 @end table
9950
9951 @node Notes on the Command Line
9952 @section Notes on the Command Line
9953
9954 @noindent
9955 This section contains some additional useful notes on the operation
9956 of the @command{gnatmake} command.
9957
9958 @itemize @bullet
9959 @item
9960 @cindex Recompilation, by @command{gnatmake}
9961 If @command{gnatmake} finds no ALI files, it recompiles the main program
9962 and all other units required by the main program.
9963 This means that @command{gnatmake}
9964 can be used for the initial compile, as well as during subsequent steps of
9965 the development cycle.
9966
9967 @item
9968 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9969 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9970 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9971 warning.
9972
9973 @item
9974 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9975 is used to specify both source and
9976 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9977 instead if you just want to specify
9978 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9979 if you want to specify library paths
9980 only.
9981
9982 @item
9983 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9984 This may conveniently be used to exclude standard libraries from
9985 consideration and in particular it means that the use of the
9986 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9987 unless @option{^-a^/ALL_FILES^} is also specified.
9988
9989 @item
9990 @command{gnatmake} has been designed to make the use of Ada libraries
9991 particularly convenient. Assume you have an Ada library organized
9992 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9993 of your Ada compilation units,
9994 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9995 specs of these units, but no bodies. Then to compile a unit
9996 stored in @code{main.adb}, which uses this Ada library you would just type
9997
9998 @smallexample
9999 @ifclear vms
10000 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
10001 @end ifclear
10002 @ifset vms
10003 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
10004 /SKIP_MISSING=@i{[OBJ_DIR]} main
10005 @end ifset
10006 @end smallexample
10007
10008 @item
10009 Using @command{gnatmake} along with the
10010 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
10011 switch provides a mechanism for avoiding unnecessary recompilations. Using
10012 this switch,
10013 you can update the comments/format of your
10014 source files without having to recompile everything. Note, however, that
10015 adding or deleting lines in a source files may render its debugging
10016 info obsolete. If the file in question is a spec, the impact is rather
10017 limited, as that debugging info will only be useful during the
10018 elaboration phase of your program. For bodies the impact can be more
10019 significant. In all events, your debugger will warn you if a source file
10020 is more recent than the corresponding object, and alert you to the fact
10021 that the debugging information may be out of date.
10022 @end itemize
10023
10024 @node How gnatmake Works
10025 @section How @command{gnatmake} Works
10026
10027 @noindent
10028 Generally @command{gnatmake} automatically performs all necessary
10029 recompilations and you don't need to worry about how it works. However,
10030 it may be useful to have some basic understanding of the @command{gnatmake}
10031 approach and in particular to understand how it uses the results of
10032 previous compilations without incorrectly depending on them.
10033
10034 First a definition: an object file is considered @dfn{up to date} if the
10035 corresponding ALI file exists and if all the source files listed in the
10036 dependency section of this ALI file have time stamps matching those in
10037 the ALI file. This means that neither the source file itself nor any
10038 files that it depends on have been modified, and hence there is no need
10039 to recompile this file.
10040
10041 @command{gnatmake} works by first checking if the specified main unit is up
10042 to date. If so, no compilations are required for the main unit. If not,
10043 @command{gnatmake} compiles the main program to build a new ALI file that
10044 reflects the latest sources. Then the ALI file of the main unit is
10045 examined to find all the source files on which the main program depends,
10046 and @command{gnatmake} recursively applies the above procedure on all these
10047 files.
10048
10049 This process ensures that @command{gnatmake} only trusts the dependencies
10050 in an existing ALI file if they are known to be correct. Otherwise it
10051 always recompiles to determine a new, guaranteed accurate set of
10052 dependencies. As a result the program is compiled ``upside down'' from what may
10053 be more familiar as the required order of compilation in some other Ada
10054 systems. In particular, clients are compiled before the units on which
10055 they depend. The ability of GNAT to compile in any order is critical in
10056 allowing an order of compilation to be chosen that guarantees that
10057 @command{gnatmake} will recompute a correct set of new dependencies if
10058 necessary.
10059
10060 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
10061 imported by several of the executables, it will be recompiled at most once.
10062
10063 Note: when using non-standard naming conventions
10064 (@pxref{Using Other File Names}), changing through a configuration pragmas
10065 file the version of a source and invoking @command{gnatmake} to recompile may
10066 have no effect, if the previous version of the source is still accessible
10067 by @command{gnatmake}. It may be necessary to use the switch
10068 ^-f^/FORCE_COMPILE^.
10069
10070 @node Examples of gnatmake Usage
10071 @section Examples of @command{gnatmake} Usage
10072
10073 @table @code
10074 @item gnatmake hello.adb
10075 Compile all files necessary to bind and link the main program
10076 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
10077 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
10078
10079 @item gnatmake main1 main2 main3
10080 Compile all files necessary to bind and link the main programs
10081 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
10082 (containing unit @code{Main2}) and @file{main3.adb}
10083 (containing unit @code{Main3}) and bind and link the resulting object files
10084 to generate three executable files @file{^main1^MAIN1.EXE^},
10085 @file{^main2^MAIN2.EXE^}
10086 and @file{^main3^MAIN3.EXE^}.
10087
10088 @ifclear vms
10089 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10090 @end ifclear
10091
10092 @ifset vms
10093 @item gnatmake Main_Unit /QUIET
10094 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10095 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10096 @end ifset
10097 Compile all files necessary to bind and link the main program unit
10098 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10099 be done with optimization level 2 and the order of elaboration will be
10100 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10101 displaying commands it is executing.
10102 @end table
10103
10104 @c *************************
10105 @node Improving Performance
10106 @chapter Improving Performance
10107 @cindex Improving performance
10108
10109 @noindent
10110 This chapter presents several topics related to program performance.
10111 It first describes some of the tradeoffs that need to be considered
10112 and some of the techniques for making your program run faster.
10113 It then documents the @command{gnatelim} tool and unused subprogram/data
10114 elimination feature, which can reduce the size of program executables.
10115
10116 @ifnottex
10117 @menu
10118 * Performance Considerations::
10119 * Text_IO Suggestions::
10120 * Reducing Size of Ada Executables with gnatelim::
10121 * Reducing Size of Executables with unused subprogram/data elimination::
10122 @end menu
10123 @end ifnottex
10124
10125 @c *****************************
10126 @node Performance Considerations
10127 @section Performance Considerations
10128
10129 @noindent
10130 The GNAT system provides a number of options that allow a trade-off
10131 between
10132
10133 @itemize @bullet
10134 @item
10135 performance of the generated code
10136
10137 @item
10138 speed of compilation
10139
10140 @item
10141 minimization of dependences and recompilation
10142
10143 @item
10144 the degree of run-time checking.
10145 @end itemize
10146
10147 @noindent
10148 The defaults (if no options are selected) aim at improving the speed
10149 of compilation and minimizing dependences, at the expense of performance
10150 of the generated code:
10151
10152 @itemize @bullet
10153 @item
10154 no optimization
10155
10156 @item
10157 no inlining of subprogram calls
10158
10159 @item
10160 all run-time checks enabled except overflow and elaboration checks
10161 @end itemize
10162
10163 @noindent
10164 These options are suitable for most program development purposes. This
10165 chapter describes how you can modify these choices, and also provides
10166 some guidelines on debugging optimized code.
10167
10168 @menu
10169 * Controlling Run-Time Checks::
10170 * Use of Restrictions::
10171 * Optimization Levels::
10172 * Debugging Optimized Code::
10173 * Inlining of Subprograms::
10174 * Vectorization of loops::
10175 * Other Optimization Switches::
10176 * Optimization and Strict Aliasing::
10177 * Aliased Variables and Optimization::
10178 * Passive Task Optimization::
10179
10180 @ifset vms
10181 * Coverage Analysis::
10182 @end ifset
10183 @end menu
10184
10185 @node Controlling Run-Time Checks
10186 @subsection Controlling Run-Time Checks
10187
10188 @noindent
10189 By default, GNAT generates all run-time checks, except integer overflow
10190 checks, stack overflow checks, and checks for access before elaboration on
10191 subprogram calls. The latter are not required in default mode, because all
10192 necessary checking is done at compile time.
10193 @cindex @option{-gnatp} (@command{gcc})
10194 @cindex @option{-gnato} (@command{gcc})
10195 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10196 be modified. @xref{Run-Time Checks}.
10197
10198 Our experience is that the default is suitable for most development
10199 purposes.
10200
10201 We treat integer overflow specially because these
10202 are quite expensive and in our experience are not as important as other
10203 run-time checks in the development process. Note that division by zero
10204 is not considered an overflow check, and divide by zero checks are
10205 generated where required by default.
10206
10207 Elaboration checks are off by default, and also not needed by default, since
10208 GNAT uses a static elaboration analysis approach that avoids the need for
10209 run-time checking. This manual contains a full chapter discussing the issue
10210 of elaboration checks, and if the default is not satisfactory for your use,
10211 you should read this chapter.
10212
10213 For validity checks, the minimal checks required by the Ada Reference
10214 Manual (for case statements and assignments to array elements) are on
10215 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10216 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10217 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10218 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10219 are also suppressed entirely if @option{-gnatp} is used.
10220
10221 @cindex Overflow checks
10222 @cindex Checks, overflow
10223 @findex Suppress
10224 @findex Unsuppress
10225 @cindex pragma Suppress
10226 @cindex pragma Unsuppress
10227 Note that the setting of the switches controls the default setting of
10228 the checks. They may be modified using either @code{pragma Suppress} (to
10229 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10230 checks) in the program source.
10231
10232 @node Use of Restrictions
10233 @subsection Use of Restrictions
10234
10235 @noindent
10236 The use of pragma Restrictions allows you to control which features are
10237 permitted in your program. Apart from the obvious point that if you avoid
10238 relatively expensive features like finalization (enforceable by the use
10239 of pragma Restrictions (No_Finalization), the use of this pragma does not
10240 affect the generated code in most cases.
10241
10242 One notable exception to this rule is that the possibility of task abort
10243 results in some distributed overhead, particularly if finalization or
10244 exception handlers are used. The reason is that certain sections of code
10245 have to be marked as non-abortable.
10246
10247 If you use neither the @code{abort} statement, nor asynchronous transfer
10248 of control (@code{select @dots{} then abort}), then this distributed overhead
10249 is removed, which may have a general positive effect in improving
10250 overall performance. Especially code involving frequent use of tasking
10251 constructs and controlled types will show much improved performance.
10252 The relevant restrictions pragmas are
10253
10254 @smallexample @c ada
10255 pragma Restrictions (No_Abort_Statements);
10256 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10257 @end smallexample
10258
10259 @noindent
10260 It is recommended that these restriction pragmas be used if possible. Note
10261 that this also means that you can write code without worrying about the
10262 possibility of an immediate abort at any point.
10263
10264 @node Optimization Levels
10265 @subsection Optimization Levels
10266 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10267
10268 @noindent
10269 Without any optimization ^option,^qualifier,^
10270 the compiler's goal is to reduce the cost of
10271 compilation and to make debugging produce the expected results.
10272 Statements are independent: if you stop the program with a breakpoint between
10273 statements, you can then assign a new value to any variable or change
10274 the program counter to any other statement in the subprogram and get exactly
10275 the results you would expect from the source code.
10276
10277 Turning on optimization makes the compiler attempt to improve the
10278 performance and/or code size at the expense of compilation time and
10279 possibly the ability to debug the program.
10280
10281 If you use multiple
10282 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10283 the last such option is the one that is effective.
10284
10285 @noindent
10286 The default is optimization off. This results in the fastest compile
10287 times, but GNAT makes absolutely no attempt to optimize, and the
10288 generated programs are considerably larger and slower than when
10289 optimization is enabled. You can use the
10290 @ifclear vms
10291 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10292 @option{-O2}, @option{-O3}, and @option{-Os})
10293 @end ifclear
10294 @ifset vms
10295 @code{OPTIMIZE} qualifier
10296 @end ifset
10297 to @command{gcc} to control the optimization level:
10298
10299 @table @option
10300 @item ^-O0^/OPTIMIZE=NONE^
10301 No optimization (the default);
10302 generates unoptimized code but has
10303 the fastest compilation time.
10304
10305 Note that many other compilers do fairly extensive optimization
10306 even if ``no optimization'' is specified. With gcc, it is
10307 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10308 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10309 really does mean no optimization at all. This difference between
10310 gcc and other compilers should be kept in mind when doing
10311 performance comparisons.
10312
10313 @item ^-O1^/OPTIMIZE=SOME^
10314 Moderate optimization;
10315 optimizes reasonably well but does not
10316 degrade compilation time significantly.
10317
10318 @item ^-O2^/OPTIMIZE=ALL^
10319 @ifset vms
10320 @itemx /OPTIMIZE=DEVELOPMENT
10321 @end ifset
10322 Full optimization;
10323 generates highly optimized code and has
10324 the slowest compilation time.
10325
10326 @item ^-O3^/OPTIMIZE=INLINING^
10327 Full optimization as in @option{-O2};
10328 also uses more aggressive automatic inlining of subprograms within a unit
10329 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10330
10331 @item ^-Os^/OPTIMIZE=SPACE^
10332 Optimize space usage (code and data) of resulting program.
10333 @end table
10334
10335 @noindent
10336 Higher optimization levels perform more global transformations on the
10337 program and apply more expensive analysis algorithms in order to generate
10338 faster and more compact code. The price in compilation time, and the
10339 resulting improvement in execution time,
10340 both depend on the particular application and the hardware environment.
10341 You should experiment to find the best level for your application.
10342
10343 Since the precise set of optimizations done at each level will vary from
10344 release to release (and sometime from target to target), it is best to think
10345 of the optimization settings in general terms.
10346 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10347 the GNU Compiler Collection (GCC)}, for details about
10348 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10349 individually enable or disable specific optimizations.
10350
10351 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10352 been tested extensively at all optimization levels. There are some bugs
10353 which appear only with optimization turned on, but there have also been
10354 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10355 level of optimization does not improve the reliability of the code
10356 generator, which in practice is highly reliable at all optimization
10357 levels.
10358
10359 Note regarding the use of @option{-O3}: The use of this optimization level
10360 is generally discouraged with GNAT, since it often results in larger
10361 executables which may run more slowly. See further discussion of this point
10362 in @ref{Inlining of Subprograms}.
10363
10364 @node Debugging Optimized Code
10365 @subsection Debugging Optimized Code
10366 @cindex Debugging optimized code
10367 @cindex Optimization and debugging
10368
10369 @noindent
10370 Although it is possible to do a reasonable amount of debugging at
10371 @ifclear vms
10372 nonzero optimization levels,
10373 the higher the level the more likely that
10374 @end ifclear
10375 @ifset vms
10376 @option{/OPTIMIZE} settings other than @code{NONE},
10377 such settings will make it more likely that
10378 @end ifset
10379 source-level constructs will have been eliminated by optimization.
10380 For example, if a loop is strength-reduced, the loop
10381 control variable may be completely eliminated and thus cannot be
10382 displayed in the debugger.
10383 This can only happen at @option{-O2} or @option{-O3}.
10384 Explicit temporary variables that you code might be eliminated at
10385 ^level^setting^ @option{-O1} or higher.
10386
10387 The use of the @option{^-g^/DEBUG^} switch,
10388 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10389 which is needed for source-level debugging,
10390 affects the size of the program executable on disk,
10391 and indeed the debugging information can be quite large.
10392 However, it has no effect on the generated code (and thus does not
10393 degrade performance)
10394
10395 Since the compiler generates debugging tables for a compilation unit before
10396 it performs optimizations, the optimizing transformations may invalidate some
10397 of the debugging data. You therefore need to anticipate certain
10398 anomalous situations that may arise while debugging optimized code.
10399 These are the most common cases:
10400
10401 @enumerate
10402 @item
10403 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
10404 commands show
10405 the PC bouncing back and forth in the code. This may result from any of
10406 the following optimizations:
10407
10408 @itemize @bullet
10409 @item
10410 @i{Common subexpression elimination:} using a single instance of code for a
10411 quantity that the source computes several times. As a result you
10412 may not be able to stop on what looks like a statement.
10413
10414 @item
10415 @i{Invariant code motion:} moving an expression that does not change within a
10416 loop, to the beginning of the loop.
10417
10418 @item
10419 @i{Instruction scheduling:} moving instructions so as to
10420 overlap loads and stores (typically) with other code, or in
10421 general to move computations of values closer to their uses. Often
10422 this causes you to pass an assignment statement without the assignment
10423 happening and then later bounce back to the statement when the
10424 value is actually needed. Placing a breakpoint on a line of code
10425 and then stepping over it may, therefore, not always cause all the
10426 expected side-effects.
10427 @end itemize
10428
10429 @item
10430 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10431 two identical pieces of code are merged and the program counter suddenly
10432 jumps to a statement that is not supposed to be executed, simply because
10433 it (and the code following) translates to the same thing as the code
10434 that @emph{was} supposed to be executed. This effect is typically seen in
10435 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10436 a @code{break} in a C @code{^switch^switch^} statement.
10437
10438 @item
10439 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10440 There are various reasons for this effect:
10441
10442 @itemize @bullet
10443 @item
10444 In a subprogram prologue, a parameter may not yet have been moved to its
10445 ``home''.
10446
10447 @item
10448 A variable may be dead, and its register re-used. This is
10449 probably the most common cause.
10450
10451 @item
10452 As mentioned above, the assignment of a value to a variable may
10453 have been moved.
10454
10455 @item
10456 A variable may be eliminated entirely by value propagation or
10457 other means. In this case, GCC may incorrectly generate debugging
10458 information for the variable
10459 @end itemize
10460
10461 @noindent
10462 In general, when an unexpected value appears for a local variable or parameter
10463 you should first ascertain if that value was actually computed by
10464 your program, as opposed to being incorrectly reported by the debugger.
10465 Record fields or
10466 array elements in an object designated by an access value
10467 are generally less of a problem, once you have ascertained that the access
10468 value is sensible.
10469 Typically, this means checking variables in the preceding code and in the
10470 calling subprogram to verify that the value observed is explainable from other
10471 values (one must apply the procedure recursively to those
10472 other values); or re-running the code and stopping a little earlier
10473 (perhaps before the call) and stepping to better see how the variable obtained
10474 the value in question; or continuing to step @emph{from} the point of the
10475 strange value to see if code motion had simply moved the variable's
10476 assignments later.
10477 @end enumerate
10478
10479 @noindent
10480 In light of such anomalies, a recommended technique is to use @option{-O0}
10481 early in the software development cycle, when extensive debugging capabilities
10482 are most needed, and then move to @option{-O1} and later @option{-O2} as
10483 the debugger becomes less critical.
10484 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10485 a release management issue.
10486 @ifclear vms
10487 Note that if you use @option{-g} you can then use the @command{strip} program
10488 on the resulting executable,
10489 which removes both debugging information and global symbols.
10490 @end ifclear
10491
10492 @node Inlining of Subprograms
10493 @subsection Inlining of Subprograms
10494
10495 @noindent
10496 A call to a subprogram in the current unit is inlined if all the
10497 following conditions are met:
10498
10499 @itemize @bullet
10500 @item
10501 The optimization level is at least @option{-O1}.
10502
10503 @item
10504 The called subprogram is suitable for inlining: It must be small enough
10505 and not contain something that @command{gcc} cannot support in inlined
10506 subprograms.
10507
10508 @item
10509 @cindex pragma Inline
10510 @findex Inline
10511 Any one of the following applies: @code{pragma Inline} is applied to the
10512 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10513 subprogram is local to the unit and called once from within it; the
10514 subprogram is small and optimization level @option{-O2} is specified;
10515 optimization level @option{-O3} is specified.
10516 @end itemize
10517
10518 @noindent
10519 Calls to subprograms in @code{with}'ed units are normally not inlined.
10520 To achieve actual inlining (that is, replacement of the call by the code
10521 in the body of the subprogram), the following conditions must all be true:
10522
10523 @itemize @bullet
10524 @item
10525 The optimization level is at least @option{-O1}.
10526
10527 @item
10528 The called subprogram is suitable for inlining: It must be small enough
10529 and not contain something that @command{gcc} cannot support in inlined
10530 subprograms.
10531
10532 @item
10533 The call appears in a body (not in a package spec).
10534
10535 @item
10536 There is a @code{pragma Inline} for the subprogram.
10537
10538 @item
10539 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10540 @end itemize
10541
10542 Even if all these conditions are met, it may not be possible for
10543 the compiler to inline the call, due to the length of the body,
10544 or features in the body that make it impossible for the compiler
10545 to do the inlining.
10546
10547 Note that specifying the @option{-gnatn} switch causes additional
10548 compilation dependencies. Consider the following:
10549
10550 @smallexample @c ada
10551 @cartouche
10552 package R is
10553 procedure Q;
10554 pragma Inline (Q);
10555 end R;
10556 package body R is
10557 @dots{}
10558 end R;
10559
10560 with R;
10561 procedure Main is
10562 begin
10563 @dots{}
10564 R.Q;
10565 end Main;
10566 @end cartouche
10567 @end smallexample
10568
10569 @noindent
10570 With the default behavior (no @option{-gnatn} switch specified), the
10571 compilation of the @code{Main} procedure depends only on its own source,
10572 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10573 means that editing the body of @code{R} does not require recompiling
10574 @code{Main}.
10575
10576 On the other hand, the call @code{R.Q} is not inlined under these
10577 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10578 is compiled, the call will be inlined if the body of @code{Q} is small
10579 enough, but now @code{Main} depends on the body of @code{R} in
10580 @file{r.adb} as well as on the spec. This means that if this body is edited,
10581 the main program must be recompiled. Note that this extra dependency
10582 occurs whether or not the call is in fact inlined by @command{gcc}.
10583
10584 The use of front end inlining with @option{-gnatN} generates similar
10585 additional dependencies.
10586
10587 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10588 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10589 can be used to prevent
10590 all inlining. This switch overrides all other conditions and ensures
10591 that no inlining occurs. The extra dependences resulting from
10592 @option{-gnatn} will still be active, even if
10593 this switch is used to suppress the resulting inlining actions.
10594
10595 @cindex @option{-fno-inline-functions} (@command{gcc})
10596 Note: The @option{-fno-inline-functions} switch can be used to prevent
10597 automatic inlining of subprograms if @option{-O3} is used.
10598
10599 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10600 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10601 automatic inlining of small subprograms if @option{-O2} is used.
10602
10603 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10604 Note: The @option{-fno-inline-functions-called-once} switch
10605 can be used to prevent inlining of subprograms local to the unit
10606 and called once from within it if @option{-O1} is used.
10607
10608 Note regarding the use of @option{-O3}: @option{-gnatn} is made up of two
10609 sub-switches @option{-gnatn1} and @option{-gnatn2} that can be directly
10610 specified in lieu of it, @option{-gnatn} being translated into one of them
10611 based on the optimization level. With @option{-O2} or below, @option{-gnatn}
10612 is equivalent to @option{-gnatn1} which activates pragma @code{Inline} with
10613 moderate inlining across modules. With @option{-O3}, @option{-gnatn} is
10614 equivalent to @option{-gnatn2} which activates pragma @code{Inline} with
10615 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
10616 effect of inlining subprograms you did not think should be inlined. We have
10617 found that the use of @option{-O3} may slow down the compilation and increase
10618 the code size by performing excessive inlining, leading to increased
10619 instruction cache pressure from the increased code size and thus minor
10620 performance improvements. So the bottom line here is that you should not
10621 automatically assume that @option{-O3} is better than @option{-O2}, and
10622 indeed you should use @option{-O3} only if tests show that it actually
10623 improves performance for your program.
10624
10625 @node Vectorization of loops
10626 @subsection Vectorization of loops
10627 @cindex Optimization Switches
10628
10629 You can take advantage of the auto-vectorizer present in the @command{gcc}
10630 back end to vectorize loops with GNAT. The corresponding command line switch
10631 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10632 and other aggressive optimizations helpful for vectorization also are enabled
10633 by default at this level, using @option{-O3} directly is recommended.
10634
10635 You also need to make sure that the target architecture features a supported
10636 SIMD instruction set. For example, for the x86 architecture, you should at
10637 least specify @option{-msse2} to get significant vectorization (but you don't
10638 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10639 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10640
10641 The preferred loop form for vectorization is the @code{for} iteration scheme.
10642 Loops with a @code{while} iteration scheme can also be vectorized if they are
10643 very simple, but the vectorizer will quickly give up otherwise. With either
10644 iteration scheme, the flow of control must be straight, in particular no
10645 @code{exit} statement may appear in the loop body. The loop may however
10646 contain a single nested loop, if it can be vectorized when considered alone:
10647
10648 @smallexample @c ada
10649 @cartouche
10650 A : array (1..4, 1..4) of Long_Float;
10651 S : array (1..4) of Long_Float;
10652
10653 procedure Sum is
10654 begin
10655 for I in A'Range(1) loop
10656 for J in A'Range(2) loop
10657 S (I) := S (I) + A (I, J);
10658 end loop;
10659 end loop;
10660 end Sum;
10661 @end cartouche
10662 @end smallexample
10663
10664 The vectorizable operations depend on the targeted SIMD instruction set, but
10665 the adding and some of the multiplying operators are generally supported, as
10666 well as the logical operators for modular types. Note that, in the former
10667 case, enabling overflow checks, for example with @option{-gnato}, totally
10668 disables vectorization. The other checks are not supposed to have the same
10669 definitive effect, although compiling with @option{-gnatp} might well reveal
10670 cases where some checks do thwart vectorization.
10671
10672 Type conversions may also prevent vectorization if they involve semantics that
10673 are not directly supported by the code generator or the SIMD instruction set.
10674 A typical example is direct conversion from floating-point to integer types.
10675 The solution in this case is to use the following idiom:
10676
10677 @smallexample @c ada
10678 Integer (S'Truncation (F))
10679 @end smallexample
10680
10681 @noindent
10682 if @code{S} is the subtype of floating-point object @code{F}.
10683
10684 In most cases, the vectorizable loops are loops that iterate over arrays.
10685 All kinds of array types are supported, i.e. constrained array types with
10686 static bounds:
10687
10688 @smallexample @c ada
10689 type Array_Type is array (1 .. 4) of Long_Float;
10690 @end smallexample
10691
10692 @noindent
10693 constrained array types with dynamic bounds:
10694
10695 @smallexample @c ada
10696 type Array_Type is array (1 .. Q.N) of Long_Float;
10697
10698 type Array_Type is array (Q.K .. 4) of Long_Float;
10699
10700 type Array_Type is array (Q.K .. Q.N) of Long_Float;
10701 @end smallexample
10702
10703 @noindent
10704 or unconstrained array types:
10705
10706 @smallexample @c ada
10707 type Array_Type is array (Positive range <>) of Long_Float;
10708 @end smallexample
10709
10710 @noindent
10711 The quality of the generated code decreases when the dynamic aspect of the
10712 array type increases, the worst code being generated for unconstrained array
10713 types. This is so because, the less information the compiler has about the
10714 bounds of the array, the more fallback code it needs to generate in order to
10715 fix things up at run time.
10716
10717 It is possible to specify that a given loop should be subject to vectorization
10718 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
10719
10720 @smallexample @c ada
10721 pragma Loop_Optimize (Vector);
10722 @end smallexample
10723
10724 @noindent
10725 placed immediately within the loop will convey the appropriate hint to the
10726 compiler for this loop.
10727
10728 @node Other Optimization Switches
10729 @subsection Other Optimization Switches
10730 @cindex Optimization Switches
10731
10732 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10733 @command{gcc} optimization switches are potentially usable. These switches
10734 have not been extensively tested with GNAT but can generally be expected
10735 to work. Examples of switches in this category are @option{-funroll-loops}
10736 and the various target-specific @option{-m} options (in particular, it has
10737 been observed that @option{-march=xxx} can significantly improve performance
10738 on appropriate machines). For full details of these switches, see
10739 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10740 the GNU Compiler Collection (GCC)}.
10741
10742 @node Optimization and Strict Aliasing
10743 @subsection Optimization and Strict Aliasing
10744 @cindex Aliasing
10745 @cindex Strict Aliasing
10746 @cindex No_Strict_Aliasing
10747
10748 @noindent
10749 The strong typing capabilities of Ada allow an optimizer to generate
10750 efficient code in situations where other languages would be forced to
10751 make worst case assumptions preventing such optimizations. Consider
10752 the following example:
10753
10754 @smallexample @c ada
10755 @cartouche
10756 procedure R is
10757 type Int1 is new Integer;
10758 type Int2 is new Integer;
10759 type Int1A is access Int1;
10760 type Int2A is access Int2;
10761 Int1V : Int1A;
10762 Int2V : Int2A;
10763 @dots{}
10764
10765 begin
10766 @dots{}
10767 for J in Data'Range loop
10768 if Data (J) = Int1V.all then
10769 Int2V.all := Int2V.all + 1;
10770 end if;
10771 end loop;
10772 @dots{}
10773 end R;
10774 @end cartouche
10775 @end smallexample
10776
10777 @noindent
10778 In this example, since the variable @code{Int1V} can only access objects
10779 of type @code{Int1}, and @code{Int2V} can only access objects of type
10780 @code{Int2}, there is no possibility that the assignment to
10781 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10782 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10783 for all iterations of the loop and avoid the extra memory reference
10784 required to dereference it each time through the loop.
10785
10786 This kind of optimization, called strict aliasing analysis, is
10787 triggered by specifying an optimization level of @option{-O2} or
10788 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10789 when access values are involved.
10790
10791 However, although this optimization is always correct in terms of
10792 the formal semantics of the Ada Reference Manual, difficulties can
10793 arise if features like @code{Unchecked_Conversion} are used to break
10794 the typing system. Consider the following complete program example:
10795
10796 @smallexample @c ada
10797 @cartouche
10798 package p1 is
10799 type int1 is new integer;
10800 type int2 is new integer;
10801 type a1 is access int1;
10802 type a2 is access int2;
10803 end p1;
10804
10805 with p1; use p1;
10806 package p2 is
10807 function to_a2 (Input : a1) return a2;
10808 end p2;
10809
10810 with Unchecked_Conversion;
10811 package body p2 is
10812 function to_a2 (Input : a1) return a2 is
10813 function to_a2u is
10814 new Unchecked_Conversion (a1, a2);
10815 begin
10816 return to_a2u (Input);
10817 end to_a2;
10818 end p2;
10819
10820 with p2; use p2;
10821 with p1; use p1;
10822 with Text_IO; use Text_IO;
10823 procedure m is
10824 v1 : a1 := new int1;
10825 v2 : a2 := to_a2 (v1);
10826 begin
10827 v1.all := 1;
10828 v2.all := 0;
10829 put_line (int1'image (v1.all));
10830 end;
10831 @end cartouche
10832 @end smallexample
10833
10834 @noindent
10835 This program prints out 0 in @option{-O0} or @option{-O1}
10836 mode, but it prints out 1 in @option{-O2} mode. That's
10837 because in strict aliasing mode, the compiler can and
10838 does assume that the assignment to @code{v2.all} could not
10839 affect the value of @code{v1.all}, since different types
10840 are involved.
10841
10842 This behavior is not a case of non-conformance with the standard, since
10843 the Ada RM specifies that an unchecked conversion where the resulting
10844 bit pattern is not a correct value of the target type can result in an
10845 abnormal value and attempting to reference an abnormal value makes the
10846 execution of a program erroneous. That's the case here since the result
10847 does not point to an object of type @code{int2}. This means that the
10848 effect is entirely unpredictable.
10849
10850 However, although that explanation may satisfy a language
10851 lawyer, in practice an applications programmer expects an
10852 unchecked conversion involving pointers to create true
10853 aliases and the behavior of printing 1 seems plain wrong.
10854 In this case, the strict aliasing optimization is unwelcome.
10855
10856 Indeed the compiler recognizes this possibility, and the
10857 unchecked conversion generates a warning:
10858
10859 @smallexample
10860 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10861 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10862 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
10863 @end smallexample
10864
10865 @noindent
10866 Unfortunately the problem is recognized when compiling the body of
10867 package @code{p2}, but the actual "bad" code is generated while
10868 compiling the body of @code{m} and this latter compilation does not see
10869 the suspicious @code{Unchecked_Conversion}.
10870
10871 As implied by the warning message, there are approaches you can use to
10872 avoid the unwanted strict aliasing optimization in a case like this.
10873
10874 One possibility is to simply avoid the use of @option{-O2}, but
10875 that is a bit drastic, since it throws away a number of useful
10876 optimizations that do not involve strict aliasing assumptions.
10877
10878 A less drastic approach is to compile the program using the
10879 option @option{-fno-strict-aliasing}. Actually it is only the
10880 unit containing the dereferencing of the suspicious pointer
10881 that needs to be compiled. So in this case, if we compile
10882 unit @code{m} with this switch, then we get the expected
10883 value of zero printed. Analyzing which units might need
10884 the switch can be painful, so a more reasonable approach
10885 is to compile the entire program with options @option{-O2}
10886 and @option{-fno-strict-aliasing}. If the performance is
10887 satisfactory with this combination of options, then the
10888 advantage is that the entire issue of possible "wrong"
10889 optimization due to strict aliasing is avoided.
10890
10891 To avoid the use of compiler switches, the configuration
10892 pragma @code{No_Strict_Aliasing} with no parameters may be
10893 used to specify that for all access types, the strict
10894 aliasing optimization should be suppressed.
10895
10896 However, these approaches are still overkill, in that they causes
10897 all manipulations of all access values to be deoptimized. A more
10898 refined approach is to concentrate attention on the specific
10899 access type identified as problematic.
10900
10901 First, if a careful analysis of uses of the pointer shows
10902 that there are no possible problematic references, then
10903 the warning can be suppressed by bracketing the
10904 instantiation of @code{Unchecked_Conversion} to turn
10905 the warning off:
10906
10907 @smallexample @c ada
10908 pragma Warnings (Off);
10909 function to_a2u is
10910 new Unchecked_Conversion (a1, a2);
10911 pragma Warnings (On);
10912 @end smallexample
10913
10914 @noindent
10915 Of course that approach is not appropriate for this particular
10916 example, since indeed there is a problematic reference. In this
10917 case we can take one of two other approaches.
10918
10919 The first possibility is to move the instantiation of unchecked
10920 conversion to the unit in which the type is declared. In
10921 this example, we would move the instantiation of
10922 @code{Unchecked_Conversion} from the body of package
10923 @code{p2} to the spec of package @code{p1}. Now the
10924 warning disappears. That's because any use of the
10925 access type knows there is a suspicious unchecked
10926 conversion, and the strict aliasing optimization
10927 is automatically suppressed for the type.
10928
10929 If it is not practical to move the unchecked conversion to the same unit
10930 in which the destination access type is declared (perhaps because the
10931 source type is not visible in that unit), you may use pragma
10932 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10933 same declarative sequence as the declaration of the access type:
10934
10935 @smallexample @c ada
10936 type a2 is access int2;
10937 pragma No_Strict_Aliasing (a2);
10938 @end smallexample
10939
10940 @noindent
10941 Here again, the compiler now knows that the strict aliasing optimization
10942 should be suppressed for any reference to type @code{a2} and the
10943 expected behavior is obtained.
10944
10945 Finally, note that although the compiler can generate warnings for
10946 simple cases of unchecked conversions, there are tricker and more
10947 indirect ways of creating type incorrect aliases which the compiler
10948 cannot detect. Examples are the use of address overlays and unchecked
10949 conversions involving composite types containing access types as
10950 components. In such cases, no warnings are generated, but there can
10951 still be aliasing problems. One safe coding practice is to forbid the
10952 use of address clauses for type overlaying, and to allow unchecked
10953 conversion only for primitive types. This is not really a significant
10954 restriction since any possible desired effect can be achieved by
10955 unchecked conversion of access values.
10956
10957 The aliasing analysis done in strict aliasing mode can certainly
10958 have significant benefits. We have seen cases of large scale
10959 application code where the time is increased by up to 5% by turning
10960 this optimization off. If you have code that includes significant
10961 usage of unchecked conversion, you might want to just stick with
10962 @option{-O1} and avoid the entire issue. If you get adequate
10963 performance at this level of optimization level, that's probably
10964 the safest approach. If tests show that you really need higher
10965 levels of optimization, then you can experiment with @option{-O2}
10966 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10967 has on size and speed of the code. If you really need to use
10968 @option{-O2} with strict aliasing in effect, then you should
10969 review any uses of unchecked conversion of access types,
10970 particularly if you are getting the warnings described above.
10971
10972 @node Aliased Variables and Optimization
10973 @subsection Aliased Variables and Optimization
10974 @cindex Aliasing
10975 There are scenarios in which programs may
10976 use low level techniques to modify variables
10977 that otherwise might be considered to be unassigned. For example,
10978 a variable can be passed to a procedure by reference, which takes
10979 the address of the parameter and uses the address to modify the
10980 variable's value, even though it is passed as an IN parameter.
10981 Consider the following example:
10982
10983 @smallexample @c ada
10984 procedure P is
10985 Max_Length : constant Natural := 16;
10986 type Char_Ptr is access all Character;
10987
10988 procedure Get_String(Buffer: Char_Ptr; Size : Integer);
10989 pragma Import (C, Get_String, "get_string");
10990
10991 Name : aliased String (1 .. Max_Length) := (others => ' ');
10992 Temp : Char_Ptr;
10993
10994 function Addr (S : String) return Char_Ptr is
10995 function To_Char_Ptr is
10996 new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
10997 begin
10998 return To_Char_Ptr (S (S'First)'Address);
10999 end;
11000
11001 begin
11002 Temp := Addr (Name);
11003 Get_String (Temp, Max_Length);
11004 end;
11005 @end smallexample
11006
11007 @noindent
11008 where Get_String is a C function that uses the address in Temp to
11009 modify the variable @code{Name}. This code is dubious, and arguably
11010 erroneous, and the compiler would be entitled to assume that
11011 @code{Name} is never modified, and generate code accordingly.
11012
11013 However, in practice, this would cause some existing code that
11014 seems to work with no optimization to start failing at high
11015 levels of optimzization.
11016
11017 What the compiler does for such cases is to assume that marking
11018 a variable as aliased indicates that some "funny business" may
11019 be going on. The optimizer recognizes the aliased keyword and
11020 inhibits optimizations that assume the value cannot be assigned.
11021 This means that the above example will in fact "work" reliably,
11022 that is, it will produce the expected results.
11023
11024 @node Passive Task Optimization
11025 @subsection Passive Task Optimization
11026 @cindex Passive Task
11027
11028 A passive task is one which is sufficiently simple that
11029 in theory a compiler could recognize it an implement it
11030 efficiently without creating a new thread. The original design
11031 of Ada 83 had in mind this kind of passive task optimization, but
11032 only a few Ada 83 compilers attempted it. The problem was that
11033 it was difficult to determine the exact conditions under which
11034 the optimization was possible. The result is a very fragile
11035 optimization where a very minor change in the program can
11036 suddenly silently make a task non-optimizable.
11037
11038 With the revisiting of this issue in Ada 95, there was general
11039 agreement that this approach was fundamentally flawed, and the
11040 notion of protected types was introduced. When using protected
11041 types, the restrictions are well defined, and you KNOW that the
11042 operations will be optimized, and furthermore this optimized
11043 performance is fully portable.
11044
11045 Although it would theoretically be possible for GNAT to attempt to
11046 do this optimization, but it really doesn't make sense in the
11047 context of Ada 95, and none of the Ada 95 compilers implement
11048 this optimization as far as we know. In particular GNAT never
11049 attempts to perform this optimization.
11050
11051 In any new Ada 95 code that is written, you should always
11052 use protected types in place of tasks that might be able to
11053 be optimized in this manner.
11054 Of course this does not help if you have legacy Ada 83 code
11055 that depends on this optimization, but it is unusual to encounter
11056 a case where the performance gains from this optimization
11057 are significant.
11058
11059 Your program should work correctly without this optimization. If
11060 you have performance problems, then the most practical
11061 approach is to figure out exactly where these performance problems
11062 arise, and update those particular tasks to be protected types. Note
11063 that typically clients of the tasks who call entries, will not have
11064 to be modified, only the task definition itself.
11065
11066 @ifset vms
11067 @node Coverage Analysis
11068 @subsection Coverage Analysis
11069
11070 @noindent
11071 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
11072 the user to determine the distribution of execution time across a program,
11073 @pxref{Profiling} for details of usage.
11074 @end ifset
11075
11076
11077 @node Text_IO Suggestions
11078 @section @code{Text_IO} Suggestions
11079 @cindex @code{Text_IO} and performance
11080
11081 @noindent
11082 The @code{Ada.Text_IO} package has fairly high overheads due in part to
11083 the requirement of maintaining page and line counts. If performance
11084 is critical, a recommendation is to use @code{Stream_IO} instead of
11085 @code{Text_IO} for volume output, since this package has less overhead.
11086
11087 If @code{Text_IO} must be used, note that by default output to the standard
11088 output and standard error files is unbuffered (this provides better
11089 behavior when output statements are used for debugging, or if the
11090 progress of a program is observed by tracking the output, e.g. by
11091 using the Unix @command{tail -f} command to watch redirected output.
11092
11093 If you are generating large volumes of output with @code{Text_IO} and
11094 performance is an important factor, use a designated file instead
11095 of the standard output file, or change the standard output file to
11096 be buffered using @code{Interfaces.C_Streams.setvbuf}.
11097
11098
11099
11100 @node Reducing Size of Ada Executables with gnatelim
11101 @section Reducing Size of Ada Executables with @code{gnatelim}
11102 @findex gnatelim
11103
11104 @noindent
11105 This section describes @command{gnatelim}, a tool which detects unused
11106 subprograms and helps the compiler to create a smaller executable for your
11107 program.
11108
11109 @menu
11110 * About gnatelim::
11111 * Running gnatelim::
11112 * Processing Precompiled Libraries::
11113 * Correcting the List of Eliminate Pragmas::
11114 * Making Your Executables Smaller::
11115 * Summary of the gnatelim Usage Cycle::
11116 @end menu
11117
11118 @node About gnatelim
11119 @subsection About @code{gnatelim}
11120
11121 @noindent
11122 When a program shares a set of Ada
11123 packages with other programs, it may happen that this program uses
11124 only a fraction of the subprograms defined in these packages. The code
11125 created for these unused subprograms increases the size of the executable.
11126
11127 @code{gnatelim} tracks unused subprograms in an Ada program and
11128 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
11129 subprograms that are declared but never called. By placing the list of
11130 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
11131 recompiling your program, you may decrease the size of its executable,
11132 because the compiler will not generate the code for 'eliminated' subprograms.
11133 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
11134 information about this pragma.
11135
11136 @code{gnatelim} needs as its input data the name of the main subprogram.
11137
11138 If a set of source files is specified as @code{gnatelim} arguments, it
11139 treats these files as a complete set of sources making up a program to
11140 analyse, and analyses only these sources.
11141
11142 After a full successful build of the main subprogram @code{gnatelim} can be
11143 called without specifying sources to analyse, in this case it computes
11144 the source closure of the main unit from the @file{ALI} files.
11145
11146 The following command will create the set of @file{ALI} files needed for
11147 @code{gnatelim}:
11148
11149 @smallexample
11150 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
11151 @end smallexample
11152
11153 Note that @code{gnatelim} does not need object files.
11154
11155 @node Running gnatelim
11156 @subsection Running @code{gnatelim}
11157
11158 @noindent
11159 @code{gnatelim} has the following command-line interface:
11160
11161 @smallexample
11162 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
11163 @end smallexample
11164
11165 @noindent
11166 @var{main_unit_name} should be a name of a source file that contains the main
11167 subprogram of a program (partition).
11168
11169 Each @var{filename} is the name (including the extension) of a source
11170 file to process. ``Wildcards'' are allowed, and
11171 the file name may contain path information.
11172
11173 @samp{@var{gcc_switches}} is a list of switches for
11174 @command{gcc}. They will be passed on to all compiler invocations made by
11175 @command{gnatelim} to generate the ASIS trees. Here you can provide
11176 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
11177 use the @option{-gnatec} switch to set the configuration file,
11178 use the @option{-gnat05} switch if sources should be compiled in
11179 Ada 2005 mode etc.
11180
11181 @code{gnatelim} has the following switches:
11182
11183 @table @option
11184 @c !sort!
11185 @item --version
11186 @cindex @option{--version} @command{gnatelim}
11187 Display Copyright and version, then exit disregarding all other options.
11188
11189 @item --help
11190 @cindex @option{--help} @command{gnatelim}
11191 Display usage, then exit disregarding all other options.
11192
11193 @item ^-files^/FILES^=@var{filename}
11194 @cindex @option{^-files^/FILES^} (@code{gnatelim})
11195 Take the argument source files from the specified file. This file should be an
11196 ordinary text file containing file names separated by spaces or
11197 line breaks. You can use this switch more than once in the same call to
11198 @command{gnatelim}. You also can combine this switch with
11199 an explicit list of files.
11200
11201 @item ^-log^/LOG^
11202 @cindex @option{^-log^/LOG^} (@command{gnatelim})
11203 Duplicate all the output sent to @file{stderr} into a log file. The log file
11204 is named @file{gnatelim.log} and is located in the current directory.
11205
11206 @item ^-log^/LOGFILE^=@var{filename}
11207 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
11208 Duplicate all the output sent to @file{stderr} into a specified log file.
11209
11210 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
11211 @item ^--no-elim-dispatch^/NO_DISPATCH^
11212 Do not generate pragmas for dispatching operations.
11213
11214 @item ^--ignore^/IGNORE^=@var{filename}
11215 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
11216 Do not generate pragmas for subprograms declared in the sources
11217 listed in a specified file
11218
11219 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
11220 @item ^-o^/OUTPUT^=@var{report_file}
11221 Put @command{gnatelim} output into a specified file. If this file already exists,
11222 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
11223 into @file{stderr}
11224
11225 @item ^-q^/QUIET^
11226 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
11227 Quiet mode: by default @code{gnatelim} outputs to the standard error
11228 stream the number of program units left to be processed. This option turns
11229 this trace off.
11230
11231 @cindex @option{^-t^/TIME^} (@command{gnatelim})
11232 @item ^-t^/TIME^
11233 Print out execution time.
11234
11235 @item ^-v^/VERBOSE^
11236 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
11237 Verbose mode: @code{gnatelim} version information is printed as Ada
11238 comments to the standard output stream. Also, in addition to the number of
11239 program units left @code{gnatelim} will output the name of the current unit
11240 being processed.
11241
11242 @item ^-wq^/WARNINGS=QUIET^
11243 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
11244 Quiet warning mode - some warnings are suppressed. In particular warnings that
11245 indicate that the analysed set of sources is incomplete to make up a
11246 partition and that some subprogram bodies are missing are not generated.
11247 @end table
11248
11249 @noindent
11250 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11251 driver (see @ref{The GNAT Driver and Project Files}).
11252
11253 @node Processing Precompiled Libraries
11254 @subsection Processing Precompiled Libraries
11255
11256 @noindent
11257 If some program uses a precompiled Ada library, it can be processed by
11258 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11259 Eliminate pragma for a subprogram if the body of this subprogram has not
11260 been analysed, this is a typical case for subprograms from precompiled
11261 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11262 warnings about missing source files and non-analyzed subprogram bodies
11263 that can be generated when processing precompiled Ada libraries.
11264
11265 @node Correcting the List of Eliminate Pragmas
11266 @subsection Correcting the List of Eliminate Pragmas
11267
11268 @noindent
11269 In some rare cases @code{gnatelim} may try to eliminate
11270 subprograms that are actually called in the program. In this case, the
11271 compiler will generate an error message of the form:
11272
11273 @smallexample
11274 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11275 @end smallexample
11276
11277 @noindent
11278 You will need to manually remove the wrong @code{Eliminate} pragmas from
11279 the configuration file indicated in the error message. You should recompile
11280 your program from scratch after that, because you need a consistent
11281 configuration file(s) during the entire compilation.
11282
11283 @node Making Your Executables Smaller
11284 @subsection Making Your Executables Smaller
11285
11286 @noindent
11287 In order to get a smaller executable for your program you now have to
11288 recompile the program completely with the configuration file containing
11289 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11290 @file{gnat.adc} file located in your current directory, just do:
11291
11292 @smallexample
11293 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11294 @end smallexample
11295
11296 @noindent
11297 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11298 recompile everything
11299 with the set of pragmas @code{Eliminate} that you have obtained with
11300 @command{gnatelim}).
11301
11302 Be aware that the set of @code{Eliminate} pragmas is specific to each
11303 program. It is not recommended to merge sets of @code{Eliminate}
11304 pragmas created for different programs in one configuration file.
11305
11306 @node Summary of the gnatelim Usage Cycle
11307 @subsection Summary of the @code{gnatelim} Usage Cycle
11308
11309 @noindent
11310 Here is a quick summary of the steps to be taken in order to reduce
11311 the size of your executables with @code{gnatelim}. You may use
11312 other GNAT options to control the optimization level,
11313 to produce the debugging information, to set search path, etc.
11314
11315 @enumerate
11316 @item
11317 Create a complete set of @file{ALI} files (if the program has not been
11318 built already)
11319
11320 @smallexample
11321 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11322 @end smallexample
11323
11324 @item
11325 Generate a list of @code{Eliminate} pragmas in default configuration file
11326 @file{gnat.adc} in the current directory
11327 @smallexample
11328 @ifset vms
11329 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11330 @end ifset
11331 @ifclear vms
11332 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11333 @end ifclear
11334 @end smallexample
11335
11336 @item
11337 Recompile the application
11338
11339 @smallexample
11340 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11341 @end smallexample
11342
11343 @end enumerate
11344
11345 @node Reducing Size of Executables with unused subprogram/data elimination
11346 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11347 @findex unused subprogram/data elimination
11348
11349 @noindent
11350 This section describes how you can eliminate unused subprograms and data from
11351 your executable just by setting options at compilation time.
11352
11353 @menu
11354 * About unused subprogram/data elimination::
11355 * Compilation options::
11356 * Example of unused subprogram/data elimination::
11357 @end menu
11358
11359 @node About unused subprogram/data elimination
11360 @subsection About unused subprogram/data elimination
11361
11362 @noindent
11363 By default, an executable contains all code and data of its composing objects
11364 (directly linked or coming from statically linked libraries), even data or code
11365 never used by this executable.
11366
11367 This feature will allow you to eliminate such unused code from your
11368 executable, making it smaller (in disk and in memory).
11369
11370 This functionality is available on all Linux platforms except for the IA-64
11371 architecture and on all cross platforms using the ELF binary file format.
11372 In both cases GNU binutils version 2.16 or later are required to enable it.
11373
11374 @node Compilation options
11375 @subsection Compilation options
11376
11377 @noindent
11378 The operation of eliminating the unused code and data from the final executable
11379 is directly performed by the linker.
11380
11381 In order to do this, it has to work with objects compiled with the
11382 following options:
11383 @option{-ffunction-sections} @option{-fdata-sections}.
11384 @cindex @option{-ffunction-sections} (@command{gcc})
11385 @cindex @option{-fdata-sections} (@command{gcc})
11386 These options are usable with C and Ada files.
11387 They will place respectively each
11388 function or data in a separate section in the resulting object file.
11389
11390 Once the objects and static libraries are created with these options, the
11391 linker can perform the dead code elimination. You can do this by setting
11392 the @option{-Wl,--gc-sections} option to gcc command or in the
11393 @option{-largs} section of @command{gnatmake}. This will perform a
11394 garbage collection of code and data never referenced.
11395
11396 If the linker performs a partial link (@option{-r} ld linker option), then you
11397 will need to provide one or several entry point using the
11398 @option{-e} / @option{--entry} ld option.
11399
11400 Note that objects compiled without the @option{-ffunction-sections} and
11401 @option{-fdata-sections} options can still be linked with the executable.
11402 However, no dead code elimination will be performed on those objects (they will
11403 be linked as is).
11404
11405 The GNAT static library is now compiled with -ffunction-sections and
11406 -fdata-sections on some platforms. This allows you to eliminate the unused code
11407 and data of the GNAT library from your executable.
11408
11409 @node Example of unused subprogram/data elimination
11410 @subsection Example of unused subprogram/data elimination
11411
11412 @noindent
11413 Here is a simple example:
11414
11415 @smallexample @c ada
11416 with Aux;
11417
11418 procedure Test is
11419 begin
11420 Aux.Used (10);
11421 end Test;
11422
11423 package Aux is
11424 Used_Data : Integer;
11425 Unused_Data : Integer;
11426
11427 procedure Used (Data : Integer);
11428 procedure Unused (Data : Integer);
11429 end Aux;
11430
11431 package body Aux is
11432 procedure Used (Data : Integer) is
11433 begin
11434 Used_Data := Data;
11435 end Used;
11436
11437 procedure Unused (Data : Integer) is
11438 begin
11439 Unused_Data := Data;
11440 end Unused;
11441 end Aux;
11442 @end smallexample
11443
11444 @noindent
11445 @code{Unused} and @code{Unused_Data} are never referenced in this code
11446 excerpt, and hence they may be safely removed from the final executable.
11447
11448 @smallexample
11449 $ gnatmake test
11450
11451 $ nm test | grep used
11452 020015f0 T aux__unused
11453 02005d88 B aux__unused_data
11454 020015cc T aux__used
11455 02005d84 B aux__used_data
11456
11457 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11458 -largs -Wl,--gc-sections
11459
11460 $ nm test | grep used
11461 02005350 T aux__used
11462 0201ffe0 B aux__used_data
11463 @end smallexample
11464
11465 @noindent
11466 It can be observed that the procedure @code{Unused} and the object
11467 @code{Unused_Data} are removed by the linker when using the
11468 appropriate options.
11469
11470 @c ********************************
11471 @node Renaming Files with gnatchop
11472 @chapter Renaming Files with @code{gnatchop}
11473 @findex gnatchop
11474
11475 @noindent
11476 This chapter discusses how to handle files with multiple units by using
11477 the @code{gnatchop} utility. This utility is also useful in renaming
11478 files to meet the standard GNAT default file naming conventions.
11479
11480 @menu
11481 * Handling Files with Multiple Units::
11482 * Operating gnatchop in Compilation Mode::
11483 * Command Line for gnatchop::
11484 * Switches for gnatchop::
11485 * Examples of gnatchop Usage::
11486 @end menu
11487
11488 @node Handling Files with Multiple Units
11489 @section Handling Files with Multiple Units
11490
11491 @noindent
11492 The basic compilation model of GNAT requires that a file submitted to the
11493 compiler have only one unit and there be a strict correspondence
11494 between the file name and the unit name.
11495
11496 The @code{gnatchop} utility allows both of these rules to be relaxed,
11497 allowing GNAT to process files which contain multiple compilation units
11498 and files with arbitrary file names. @code{gnatchop}
11499 reads the specified file and generates one or more output files,
11500 containing one unit per file. The unit and the file name correspond,
11501 as required by GNAT.
11502
11503 If you want to permanently restructure a set of ``foreign'' files so that
11504 they match the GNAT rules, and do the remaining development using the
11505 GNAT structure, you can simply use @command{gnatchop} once, generate the
11506 new set of files and work with them from that point on.
11507
11508 Alternatively, if you want to keep your files in the ``foreign'' format,
11509 perhaps to maintain compatibility with some other Ada compilation
11510 system, you can set up a procedure where you use @command{gnatchop} each
11511 time you compile, regarding the source files that it writes as temporary
11512 files that you throw away.
11513
11514 Note that if your file containing multiple units starts with a byte order
11515 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11516 will each start with a copy of this BOM, meaning that they can be compiled
11517 automatically in UTF-8 mode without needing to specify an explicit encoding.
11518
11519 @node Operating gnatchop in Compilation Mode
11520 @section Operating gnatchop in Compilation Mode
11521
11522 @noindent
11523 The basic function of @code{gnatchop} is to take a file with multiple units
11524 and split it into separate files. The boundary between files is reasonably
11525 clear, except for the issue of comments and pragmas. In default mode, the
11526 rule is that any pragmas between units belong to the previous unit, except
11527 that configuration pragmas always belong to the following unit. Any comments
11528 belong to the following unit. These rules
11529 almost always result in the right choice of
11530 the split point without needing to mark it explicitly and most users will
11531 find this default to be what they want. In this default mode it is incorrect to
11532 submit a file containing only configuration pragmas, or one that ends in
11533 configuration pragmas, to @code{gnatchop}.
11534
11535 However, using a special option to activate ``compilation mode'',
11536 @code{gnatchop}
11537 can perform another function, which is to provide exactly the semantics
11538 required by the RM for handling of configuration pragmas in a compilation.
11539 In the absence of configuration pragmas (at the main file level), this
11540 option has no effect, but it causes such configuration pragmas to be handled
11541 in a quite different manner.
11542
11543 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11544 only configuration pragmas, then this file is appended to the
11545 @file{gnat.adc} file in the current directory. This behavior provides
11546 the required behavior described in the RM for the actions to be taken
11547 on submitting such a file to the compiler, namely that these pragmas
11548 should apply to all subsequent compilations in the same compilation
11549 environment. Using GNAT, the current directory, possibly containing a
11550 @file{gnat.adc} file is the representation
11551 of a compilation environment. For more information on the
11552 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11553
11554 Second, in compilation mode, if @code{gnatchop}
11555 is given a file that starts with
11556 configuration pragmas, and contains one or more units, then these
11557 configuration pragmas are prepended to each of the chopped files. This
11558 behavior provides the required behavior described in the RM for the
11559 actions to be taken on compiling such a file, namely that the pragmas
11560 apply to all units in the compilation, but not to subsequently compiled
11561 units.
11562
11563 Finally, if configuration pragmas appear between units, they are appended
11564 to the previous unit. This results in the previous unit being illegal,
11565 since the compiler does not accept configuration pragmas that follow
11566 a unit. This provides the required RM behavior that forbids configuration
11567 pragmas other than those preceding the first compilation unit of a
11568 compilation.
11569
11570 For most purposes, @code{gnatchop} will be used in default mode. The
11571 compilation mode described above is used only if you need exactly
11572 accurate behavior with respect to compilations, and you have files
11573 that contain multiple units and configuration pragmas. In this
11574 circumstance the use of @code{gnatchop} with the compilation mode
11575 switch provides the required behavior, and is for example the mode
11576 in which GNAT processes the ACVC tests.
11577
11578 @node Command Line for gnatchop
11579 @section Command Line for @code{gnatchop}
11580
11581 @noindent
11582 The @code{gnatchop} command has the form:
11583
11584 @smallexample
11585 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11586 @c @ovar{directory}
11587 @c Expanding @ovar macro inline (explanation in macro def comments)
11588 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11589 @r{[}@var{directory}@r{]}
11590 @end smallexample
11591
11592 @noindent
11593 The only required argument is the file name of the file to be chopped.
11594 There are no restrictions on the form of this file name. The file itself
11595 contains one or more Ada units, in normal GNAT format, concatenated
11596 together. As shown, more than one file may be presented to be chopped.
11597
11598 When run in default mode, @code{gnatchop} generates one output file in
11599 the current directory for each unit in each of the files.
11600
11601 @var{directory}, if specified, gives the name of the directory to which
11602 the output files will be written. If it is not specified, all files are
11603 written to the current directory.
11604
11605 For example, given a
11606 file called @file{hellofiles} containing
11607
11608 @smallexample @c ada
11609 @group
11610 @cartouche
11611 procedure hello;
11612
11613 with Text_IO; use Text_IO;
11614 procedure hello is
11615 begin
11616 Put_Line ("Hello");
11617 end hello;
11618 @end cartouche
11619 @end group
11620 @end smallexample
11621
11622 @noindent
11623 the command
11624
11625 @smallexample
11626 $ gnatchop ^hellofiles^HELLOFILES.^
11627 @end smallexample
11628
11629 @noindent
11630 generates two files in the current directory, one called
11631 @file{hello.ads} containing the single line that is the procedure spec,
11632 and the other called @file{hello.adb} containing the remaining text. The
11633 original file is not affected. The generated files can be compiled in
11634 the normal manner.
11635
11636 @noindent
11637 When gnatchop is invoked on a file that is empty or that contains only empty
11638 lines and/or comments, gnatchop will not fail, but will not produce any
11639 new sources.
11640
11641 For example, given a
11642 file called @file{toto.txt} containing
11643
11644 @smallexample @c ada
11645 @group
11646 @cartouche
11647 -- Just a comment
11648 @end cartouche
11649 @end group
11650 @end smallexample
11651
11652 @noindent
11653 the command
11654
11655 @smallexample
11656 $ gnatchop ^toto.txt^TOT.TXT^
11657 @end smallexample
11658
11659 @noindent
11660 will not produce any new file and will result in the following warnings:
11661
11662 @smallexample
11663 toto.txt:1:01: warning: empty file, contains no compilation units
11664 no compilation units found
11665 no source files written
11666 @end smallexample
11667
11668 @node Switches for gnatchop
11669 @section Switches for @code{gnatchop}
11670
11671 @noindent
11672 @command{gnatchop} recognizes the following switches:
11673
11674 @table @option
11675 @c !sort!
11676
11677 @item --version
11678 @cindex @option{--version} @command{gnatchop}
11679 Display Copyright and version, then exit disregarding all other options.
11680
11681 @item --help
11682 @cindex @option{--help} @command{gnatchop}
11683 If @option{--version} was not used, display usage, then exit disregarding
11684 all other options.
11685
11686 @item ^-c^/COMPILATION^
11687 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11688 Causes @code{gnatchop} to operate in compilation mode, in which
11689 configuration pragmas are handled according to strict RM rules. See
11690 previous section for a full description of this mode.
11691
11692 @ifclear vms
11693 @item -gnat@var{xxx}
11694 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11695 used to parse the given file. Not all @var{xxx} options make sense,
11696 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11697 process a source file that uses Latin-2 coding for identifiers.
11698 @end ifclear
11699
11700 @item ^-h^/HELP^
11701 Causes @code{gnatchop} to generate a brief help summary to the standard
11702 output file showing usage information.
11703
11704 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11705 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11706 Limit generated file names to the specified number @code{mm}
11707 of characters.
11708 This is useful if the
11709 resulting set of files is required to be interoperable with systems
11710 which limit the length of file names.
11711 @ifset vms
11712 If no value is given, or
11713 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11714 a default of 39, suitable for OpenVMS Alpha
11715 Systems, is assumed
11716 @end ifset
11717 @ifclear vms
11718 No space is allowed between the @option{-k} and the numeric value. The numeric
11719 value may be omitted in which case a default of @option{-k8},
11720 suitable for use
11721 with DOS-like file systems, is used. If no @option{-k} switch
11722 is present then
11723 there is no limit on the length of file names.
11724 @end ifclear
11725
11726 @item ^-p^/PRESERVE^
11727 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11728 Causes the file ^modification^creation^ time stamp of the input file to be
11729 preserved and used for the time stamp of the output file(s). This may be
11730 useful for preserving coherency of time stamps in an environment where
11731 @code{gnatchop} is used as part of a standard build process.
11732
11733 @item ^-q^/QUIET^
11734 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11735 Causes output of informational messages indicating the set of generated
11736 files to be suppressed. Warnings and error messages are unaffected.
11737
11738 @item ^-r^/REFERENCE^
11739 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11740 @findex Source_Reference
11741 Generate @code{Source_Reference} pragmas. Use this switch if the output
11742 files are regarded as temporary and development is to be done in terms
11743 of the original unchopped file. This switch causes
11744 @code{Source_Reference} pragmas to be inserted into each of the
11745 generated files to refers back to the original file name and line number.
11746 The result is that all error messages refer back to the original
11747 unchopped file.
11748 In addition, the debugging information placed into the object file (when
11749 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11750 specified)
11751 also refers back to this original file so that tools like profilers and
11752 debuggers will give information in terms of the original unchopped file.
11753
11754 If the original file to be chopped itself contains
11755 a @code{Source_Reference}
11756 pragma referencing a third file, then gnatchop respects
11757 this pragma, and the generated @code{Source_Reference} pragmas
11758 in the chopped file refer to the original file, with appropriate
11759 line numbers. This is particularly useful when @code{gnatchop}
11760 is used in conjunction with @code{gnatprep} to compile files that
11761 contain preprocessing statements and multiple units.
11762
11763 @item ^-v^/VERBOSE^
11764 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11765 Causes @code{gnatchop} to operate in verbose mode. The version
11766 number and copyright notice are output, as well as exact copies of
11767 the gnat1 commands spawned to obtain the chop control information.
11768
11769 @item ^-w^/OVERWRITE^
11770 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11771 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11772 fatal error if there is already a file with the same name as a
11773 file it would otherwise output, in other words if the files to be
11774 chopped contain duplicated units. This switch bypasses this
11775 check, and causes all but the last instance of such duplicated
11776 units to be skipped.
11777
11778 @ifclear vms
11779 @item --GCC=@var{xxxx}
11780 @cindex @option{--GCC=} (@code{gnatchop})
11781 Specify the path of the GNAT parser to be used. When this switch is used,
11782 no attempt is made to add the prefix to the GNAT parser executable.
11783 @end ifclear
11784 @end table
11785
11786 @node Examples of gnatchop Usage
11787 @section Examples of @code{gnatchop} Usage
11788
11789 @table @code
11790 @ifset vms
11791 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11792 @end ifset
11793 @ifclear vms
11794 @item gnatchop -w hello_s.ada prerelease/files
11795 @end ifclear
11796
11797 Chops the source file @file{hello_s.ada}. The output files will be
11798 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11799 overwriting any
11800 files with matching names in that directory (no files in the current
11801 directory are modified).
11802
11803 @item gnatchop ^archive^ARCHIVE.^
11804 Chops the source file @file{^archive^ARCHIVE.^}
11805 into the current directory. One
11806 useful application of @code{gnatchop} is in sending sets of sources
11807 around, for example in email messages. The required sources are simply
11808 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11809 command), and then
11810 @command{gnatchop} is used at the other end to reconstitute the original
11811 file names.
11812
11813 @item gnatchop file1 file2 file3 direc
11814 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11815 the resulting files in the directory @file{direc}. Note that if any units
11816 occur more than once anywhere within this set of files, an error message
11817 is generated, and no files are written. To override this check, use the
11818 @option{^-w^/OVERWRITE^} switch,
11819 in which case the last occurrence in the last file will
11820 be the one that is output, and earlier duplicate occurrences for a given
11821 unit will be skipped.
11822 @end table
11823
11824 @node Configuration Pragmas
11825 @chapter Configuration Pragmas
11826 @cindex Configuration pragmas
11827 @cindex Pragmas, configuration
11828
11829 @menu
11830 * Handling of Configuration Pragmas::
11831 * The Configuration Pragmas Files::
11832 @end menu
11833
11834 @noindent
11835 Configuration pragmas include those pragmas described as
11836 such in the Ada Reference Manual, as well as
11837 implementation-dependent pragmas that are configuration pragmas.
11838 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11839 for details on these additional GNAT-specific configuration pragmas.
11840 Most notably, the pragma @code{Source_File_Name}, which allows
11841 specifying non-default names for source files, is a configuration
11842 pragma. The following is a complete list of configuration pragmas
11843 recognized by GNAT:
11844
11845 @smallexample
11846 Ada_83
11847 Ada_95
11848 Ada_05
11849 Ada_2005
11850 Ada_12
11851 Ada_2012
11852 Allow_Integer_Address
11853 Annotate
11854 Assertion_Policy
11855 Assume_No_Invalid_Values
11856 C_Pass_By_Copy
11857 Check_Name
11858 Check_Policy
11859 Compile_Time_Error
11860 Compile_Time_Warning
11861 Compiler_Unit
11862 Component_Alignment
11863 Convention_Identifier
11864 Debug_Policy
11865 Detect_Blocking
11866 Default_Storage_Pool
11867 Discard_Names
11868 Elaboration_Checks
11869 Eliminate
11870 Extend_System
11871 Extensions_Allowed
11872 External_Name_Casing
11873 Fast_Math
11874 Favor_Top_Level
11875 Float_Representation
11876 Implicit_Packing
11877 Initialize_Scalars
11878 Interrupt_State
11879 License
11880 Locking_Policy
11881 Long_Float
11882 No_Run_Time
11883 No_Strict_Aliasing
11884 Normalize_Scalars
11885 Optimize_Alignment
11886 Persistent_BSS
11887 Polling
11888 Priority_Specific_Dispatching
11889 Profile
11890 Profile_Warnings
11891 Propagate_Exceptions
11892 Queuing_Policy
11893 Ravenscar
11894 Restricted_Run_Time
11895 Restrictions
11896 Restrictions_Warnings
11897 Reviewable
11898 Short_Circuit_And_Or
11899 Source_File_Name
11900 Source_File_Name_Project
11901 SPARK_Mode
11902 Style_Checks
11903 Suppress
11904 Suppress_Exception_Locations
11905 Task_Dispatching_Policy
11906 Universal_Data
11907 Unsuppress
11908 Use_VADS_Size
11909 Validity_Checks
11910 Warnings
11911 Wide_Character_Encoding
11912 @end smallexample
11913
11914 @node Handling of Configuration Pragmas
11915 @section Handling of Configuration Pragmas
11916
11917 Configuration pragmas may either appear at the start of a compilation
11918 unit, or they can appear in a configuration pragma file to apply to
11919 all compilations performed in a given compilation environment.
11920
11921 GNAT also provides the @code{gnatchop} utility to provide an automatic
11922 way to handle configuration pragmas following the semantics for
11923 compilations (that is, files with multiple units), described in the RM.
11924 See @ref{Operating gnatchop in Compilation Mode} for details.
11925 However, for most purposes, it will be more convenient to edit the
11926 @file{gnat.adc} file that contains configuration pragmas directly,
11927 as described in the following section.
11928
11929 In the case of @code{Restrictions} pragmas appearing as configuration
11930 pragmas in individual compilation units, the exact handling depends on
11931 the type of restriction.
11932
11933 Restrictions that require partition-wide consistency (like
11934 @code{No_Tasking}) are
11935 recognized wherever they appear
11936 and can be freely inherited, e.g. from a with'ed unit to the with'ing
11937 unit. This makes sense since the binder will in any case insist on seeing
11938 consistent use, so any unit not conforming to any restrictions that are
11939 anywhere in the partition will be rejected, and you might as well find
11940 that out at compile time rather than at bind time.
11941
11942 For restrictions that do not require partition-wide consistency, e.g.
11943 SPARK or No_Implementation_Attributes, in general the restriction applies
11944 only to the unit in which the pragma appears, and not to any other units.
11945
11946 The exception is No_Elaboration_Code which always applies to the entire
11947 object file from a compilation, i.e. to the body, spec, and all subunits.
11948 This restriction can be specified in a configuration pragma file, or it
11949 can be on the body and/or the spec (in eithe case it applies to all the
11950 relevant units). It can appear on a subunit only if it has previously
11951 appeared in the body of spec.
11952
11953 @node The Configuration Pragmas Files
11954 @section The Configuration Pragmas Files
11955 @cindex @file{gnat.adc}
11956
11957 @noindent
11958 In GNAT a compilation environment is defined by the current
11959 directory at the time that a compile command is given. This current
11960 directory is searched for a file whose name is @file{gnat.adc}. If
11961 this file is present, it is expected to contain one or more
11962 configuration pragmas that will be applied to the current compilation.
11963 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11964 considered.
11965
11966 Configuration pragmas may be entered into the @file{gnat.adc} file
11967 either by running @code{gnatchop} on a source file that consists only of
11968 configuration pragmas, or more conveniently by
11969 direct editing of the @file{gnat.adc} file, which is a standard format
11970 source file.
11971
11972 In addition to @file{gnat.adc}, additional files containing configuration
11973 pragmas may be applied to the current compilation using the switch
11974 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11975 contains only configuration pragmas. These configuration pragmas are
11976 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11977 is present and switch @option{-gnatA} is not used).
11978
11979 It is allowed to specify several switches @option{-gnatec}, all of which
11980 will be taken into account.
11981
11982 If you are using project file, a separate mechanism is provided using
11983 project attributes, see @ref{Specifying Configuration Pragmas} for more
11984 details.
11985
11986 @ifset vms
11987 Of special interest to GNAT OpenVMS Alpha is the following
11988 configuration pragma:
11989
11990 @smallexample @c ada
11991 @cartouche
11992 pragma Extend_System (Aux_DEC);
11993 @end cartouche
11994 @end smallexample
11995
11996 @noindent
11997 In the presence of this pragma, GNAT adds to the definition of the
11998 predefined package SYSTEM all the additional types and subprograms that are
11999 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
12000 @end ifset
12001
12002 @node Handling Arbitrary File Naming Conventions with gnatname
12003 @chapter Handling Arbitrary File Naming Conventions with @code{gnatname}
12004 @cindex Arbitrary File Naming Conventions
12005
12006 @menu
12007 * Arbitrary File Naming Conventions::
12008 * Running gnatname::
12009 * Switches for gnatname::
12010 * Examples of gnatname Usage::
12011 @end menu
12012
12013 @node Arbitrary File Naming Conventions
12014 @section Arbitrary File Naming Conventions
12015
12016 @noindent
12017 The GNAT compiler must be able to know the source file name of a compilation
12018 unit. When using the standard GNAT default file naming conventions
12019 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
12020 does not need additional information.
12021
12022 @noindent
12023 When the source file names do not follow the standard GNAT default file naming
12024 conventions, the GNAT compiler must be given additional information through
12025 a configuration pragmas file (@pxref{Configuration Pragmas})
12026 or a project file.
12027 When the non-standard file naming conventions are well-defined,
12028 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
12029 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
12030 if the file naming conventions are irregular or arbitrary, a number
12031 of pragma @code{Source_File_Name} for individual compilation units
12032 must be defined.
12033 To help maintain the correspondence between compilation unit names and
12034 source file names within the compiler,
12035 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
12036 set of files.
12037
12038 @node Running gnatname
12039 @section Running @code{gnatname}
12040
12041 @noindent
12042 The usual form of the @code{gnatname} command is
12043
12044 @smallexample
12045 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
12046 @c @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
12047 @c Expanding @ovar macro inline (explanation in macro def comments)
12048 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
12049 @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
12050 @end smallexample
12051
12052 @noindent
12053 All of the arguments are optional. If invoked without any argument,
12054 @code{gnatname} will display its usage.
12055
12056 @noindent
12057 When used with at least one naming pattern, @code{gnatname} will attempt to
12058 find all the compilation units in files that follow at least one of the
12059 naming patterns. To find these compilation units,
12060 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
12061 regular files.
12062
12063 @noindent
12064 One or several Naming Patterns may be given as arguments to @code{gnatname}.
12065 Each Naming Pattern is enclosed between double quotes (or single
12066 quotes on Windows).
12067 A Naming Pattern is a regular expression similar to the wildcard patterns
12068 used in file names by the Unix shells or the DOS prompt.
12069
12070 @noindent
12071 @code{gnatname} may be called with several sections of directories/patterns.
12072 Sections are separated by switch @code{--and}. In each section, there must be
12073 at least one pattern. If no directory is specified in a section, the current
12074 directory (or the project directory is @code{-P} is used) is implied.
12075 The options other that the directory switches and the patterns apply globally
12076 even if they are in different sections.
12077
12078 @noindent
12079 Examples of Naming Patterns are
12080
12081 @smallexample
12082 "*.[12].ada"
12083 "*.ad[sb]*"
12084 "body_*" "spec_*"
12085 @end smallexample
12086
12087 @noindent
12088 For a more complete description of the syntax of Naming Patterns,
12089 see the second kind of regular expressions described in @file{g-regexp.ads}
12090 (the ``Glob'' regular expressions).
12091
12092 @noindent
12093 When invoked with no switch @code{-P}, @code{gnatname} will create a
12094 configuration pragmas file @file{gnat.adc} in the current working directory,
12095 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
12096 unit.
12097
12098 @node Switches for gnatname
12099 @section Switches for @code{gnatname}
12100
12101 @noindent
12102 Switches for @code{gnatname} must precede any specified Naming Pattern.
12103
12104 @noindent
12105 You may specify any of the following switches to @code{gnatname}:
12106
12107 @table @option
12108 @c !sort!
12109
12110 @item --version
12111 @cindex @option{--version} @command{gnatname}
12112 Display Copyright and version, then exit disregarding all other options.
12113
12114 @item --help
12115 @cindex @option{--help} @command{gnatname}
12116 If @option{--version} was not used, display usage, then exit disregarding
12117 all other options.
12118
12119 @item --subdirs=<dir>
12120 Real object, library or exec directories are subdirectories <dir> of the
12121 specified ones.
12122
12123 @item --no-backup
12124 Do not create a backup copy of an existing project file.
12125
12126 @item --and
12127 Start another section of directories/patterns.
12128
12129 @item ^-c^/CONFIG_FILE=^@file{file}
12130 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
12131 Create a configuration pragmas file @file{file} (instead of the default
12132 @file{gnat.adc}).
12133 @ifclear vms
12134 There may be zero, one or more space between @option{-c} and
12135 @file{file}.
12136 @end ifclear
12137 @file{file} may include directory information. @file{file} must be
12138 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
12139 When a switch @option{^-c^/CONFIG_FILE^} is
12140 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
12141
12142 @item ^-d^/SOURCE_DIRS=^@file{dir}
12143 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
12144 Look for source files in directory @file{dir}. There may be zero, one or more
12145 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
12146 @file{dir} may end with @code{/**}, that is it may be of the form
12147 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
12148 subdirectories, recursively, have to be searched for sources.
12149 When a switch @option{^-d^/SOURCE_DIRS^}
12150 is specified, the current working directory will not be searched for source
12151 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
12152 or @option{^-D^/DIR_FILES^} switch.
12153 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
12154 If @file{dir} is a relative path, it is relative to the directory of
12155 the configuration pragmas file specified with switch
12156 @option{^-c^/CONFIG_FILE^},
12157 or to the directory of the project file specified with switch
12158 @option{^-P^/PROJECT_FILE^} or,
12159 if neither switch @option{^-c^/CONFIG_FILE^}
12160 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
12161 current working directory. The directory
12162 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
12163
12164 @item ^-D^/DIRS_FILE=^@file{file}
12165 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
12166 Look for source files in all directories listed in text file @file{file}.
12167 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
12168 and @file{file}.
12169 @file{file} must be an existing, readable text file.
12170 Each nonempty line in @file{file} must be a directory.
12171 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
12172 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
12173 @file{file}.
12174
12175 @item -eL
12176 Follow symbolic links when processing project files.
12177
12178 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
12179 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
12180 Foreign patterns. Using this switch, it is possible to add sources of languages
12181 other than Ada to the list of sources of a project file.
12182 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
12183 For example,
12184 @smallexample
12185 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
12186 @end smallexample
12187 @noindent
12188 will look for Ada units in all files with the @file{.ada} extension,
12189 and will add to the list of file for project @file{prj.gpr} the C files
12190 with extension @file{.^c^C^}.
12191
12192 @item ^-h^/HELP^
12193 @cindex @option{^-h^/HELP^} (@code{gnatname})
12194 Output usage (help) information. The output is written to @file{stdout}.
12195
12196 @item ^-P^/PROJECT_FILE=^@file{proj}
12197 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
12198 Create or update project file @file{proj}. There may be zero, one or more space
12199 between @option{-P} and @file{proj}. @file{proj} may include directory
12200 information. @file{proj} must be writable.
12201 There may be only one switch @option{^-P^/PROJECT_FILE^}.
12202 When a switch @option{^-P^/PROJECT_FILE^} is specified,
12203 no switch @option{^-c^/CONFIG_FILE^} may be specified.
12204 On all platforms, except on VMS, when @code{gnatname} is invoked for an
12205 existing project file <proj>.gpr, a backup copy of the project file is created
12206 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
12207 non negative number that makes this backup copy a new file.
12208
12209 @item ^-v^/VERBOSE^
12210 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
12211 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
12212 This includes name of the file written, the name of the directories to search
12213 and, for each file in those directories whose name matches at least one of
12214 the Naming Patterns, an indication of whether the file contains a unit,
12215 and if so the name of the unit.
12216
12217 @item ^-v -v^/VERBOSE /VERBOSE^
12218 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
12219 Very Verbose mode. In addition to the output produced in verbose mode,
12220 for each file in the searched directories whose name matches none of
12221 the Naming Patterns, an indication is given that there is no match.
12222
12223 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
12224 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
12225 Excluded patterns. Using this switch, it is possible to exclude some files
12226 that would match the name patterns. For example,
12227 @smallexample
12228 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
12229 @end smallexample
12230 @noindent
12231 will look for Ada units in all files with the @file{.ada} extension,
12232 except those whose names end with @file{_nt.ada}.
12233
12234 @end table
12235
12236 @node Examples of gnatname Usage
12237 @section Examples of @code{gnatname} Usage
12238
12239 @ifset vms
12240 @smallexample
12241 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
12242 @end smallexample
12243 @end ifset
12244
12245 @ifclear vms
12246 @smallexample
12247 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
12248 @end smallexample
12249 @end ifclear
12250
12251 @noindent
12252 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
12253 and be writable. In addition, the directory
12254 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
12255 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
12256
12257 @ifclear vms
12258 Note the optional spaces after @option{-c} and @option{-d}.
12259 @end ifclear
12260
12261 @smallexample
12262 @ifclear vms
12263 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
12264 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12265 @end ifclear
12266 @ifset vms
12267 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
12268 /EXCLUDED_PATTERN=*_nt_body.ada
12269 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
12270 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
12271 @end ifset
12272 @end smallexample
12273
12274 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
12275 even in conjunction with one or several switches
12276 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
12277 are used in this example.
12278
12279 @c *****************************************
12280 @c * G N A T P r o j e c t M a n a g e r *
12281 @c *****************************************
12282
12283 @c ------ macros for projects.texi
12284 @c These macros are needed when building the gprbuild documentation, but
12285 @c should have no effect in the gnat user's guide
12286
12287 @macro CODESAMPLE{TXT}
12288 @smallexample
12289 @group
12290 \TXT\
12291 @end group
12292 @end smallexample
12293 @end macro
12294
12295 @macro PROJECTFILE{TXT}
12296 @CODESAMPLE{\TXT\}
12297 @end macro
12298
12299 @c simulates a newline when in a @CODESAMPLE
12300 @macro NL{}
12301 @end macro
12302
12303 @macro TIP{TXT}
12304 @quotation
12305 @noindent
12306 \TXT\
12307 @end quotation
12308 @end macro
12309
12310 @macro TIPHTML{TXT}
12311 \TXT\
12312 @end macro
12313
12314 @macro IMPORTANT{TXT}
12315 @quotation
12316 @noindent
12317 \TXT\
12318 @end quotation
12319
12320 @end macro
12321
12322 @macro NOTE{TXT}
12323 @quotation
12324 @noindent
12325 \TXT\
12326 @end quotation
12327 @end macro
12328
12329 @include projects.texi
12330
12331 @c ---------------------------------------------
12332 @c Tools Supporting Project Files
12333 @c ---------------------------------------------
12334
12335 @node Tools Supporting Project Files
12336 @chapter Tools Supporting Project Files
12337
12338 @noindent
12339
12340 @menu
12341 * gnatmake and Project Files::
12342 * The GNAT Driver and Project Files::
12343 @end menu
12344
12345 @c ---------------------------------------------
12346 @node gnatmake and Project Files
12347 @section gnatmake and Project Files
12348 @c ---------------------------------------------
12349
12350 @noindent
12351 This section covers several topics related to @command{gnatmake} and
12352 project files: defining ^switches^switches^ for @command{gnatmake}
12353 and for the tools that it invokes; specifying configuration pragmas;
12354 the use of the @code{Main} attribute; building and rebuilding library project
12355 files.
12356
12357 @menu
12358 * Switches Related to Project Files::
12359 * Switches and Project Files::
12360 * Specifying Configuration Pragmas::
12361 * Project Files and Main Subprograms::
12362 * Library Project Files::
12363 @end menu
12364
12365 @c ---------------------------------------------
12366 @node Switches Related to Project Files
12367 @subsection Switches Related to Project Files
12368 @c ---------------------------------------------
12369
12370 @noindent
12371 The following switches are used by GNAT tools that support project files:
12372
12373 @table @option
12374
12375 @item ^-P^/PROJECT_FILE=^@var{project}
12376 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
12377 Indicates the name of a project file. This project file will be parsed with
12378 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12379 if any, and using the external references indicated
12380 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12381 @ifclear vms
12382 There may zero, one or more spaces between @option{-P} and @var{project}.
12383 @end ifclear
12384
12385 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12386
12387 Since the Project Manager parses the project file only after all the switches
12388 on the command line are checked, the order of the switches
12389 @option{^-P^/PROJECT_FILE^},
12390 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12391 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12392
12393 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12394 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
12395 Indicates that external variable @var{name} has the value @var{value}.
12396 The Project Manager will use this value for occurrences of
12397 @code{external(name)} when parsing the project file.
12398
12399 @ifclear vms
12400 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12401 put between quotes.
12402 @smallexample
12403 -XOS=NT
12404 -X"user=John Doe"
12405 @end smallexample
12406 @end ifclear
12407
12408 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12409 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12410 @var{name}, only the last one is used.
12411
12412 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12413 takes precedence over the value of the same name in the environment.
12414
12415 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12416 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
12417 Indicates the verbosity of the parsing of GNAT project files.
12418
12419 @ifclear vms
12420 @option{-vP0} means Default;
12421 @option{-vP1} means Medium;
12422 @option{-vP2} means High.
12423 @end ifclear
12424
12425 @ifset vms
12426 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12427 HIGH.
12428 @end ifset
12429
12430 The default is ^Default^DEFAULT^: no output for syntactically correct
12431 project files.
12432 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12433 only the last one is used.
12434
12435 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
12436 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
12437 Add directory <dir> at the beginning of the project search path, in order,
12438 after the current working directory.
12439
12440 @ifclear vms
12441 @item -eL
12442 @cindex @option{-eL} (any project-aware tool)
12443 Follow all symbolic links when processing project files.
12444 @end ifclear
12445
12446 @item ^--subdirs^/SUBDIRS^=<subdir>
12447 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
12448 This switch is recognized by @command{gnatmake} and @command{gnatclean}. It
12449 indicate that the real directories (except the source directories) are the
12450 subdirectories <subdir> of the directories specified in the project files.
12451 This applies in particular to object directories, library directories and
12452 exec directories. If the subdirectories do not exist, they are created
12453 automatically.
12454
12455 @end table
12456
12457 @c ---------------------------------------------
12458 @node Switches and Project Files
12459 @subsection Switches and Project Files
12460 @c ---------------------------------------------
12461
12462 @noindent
12463 @ifset vms
12464 It is not currently possible to specify VMS style qualifiers in the project
12465 files; only Unix style ^switches^switches^ may be specified.
12466 @end ifset
12467
12468 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12469 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12470 attribute, a @code{Switches} attribute, or both;
12471 as their names imply, these ^switch^switch^-related
12472 attributes affect the ^switches^switches^ that are used for each of these GNAT
12473 components when
12474 @command{gnatmake} is invoked. As will be explained below, these
12475 component-specific ^switches^switches^ precede
12476 the ^switches^switches^ provided on the @command{gnatmake} command line.
12477
12478 The @code{^Default_Switches^Default_Switches^} attribute is an attribute
12479 indexed by language name (case insensitive) whose value is a string list.
12480 For example:
12481
12482 @smallexample @c projectfile
12483 @group
12484 package Compiler is
12485 for ^Default_Switches^Default_Switches^ ("Ada")
12486 use ("^-gnaty^-gnaty^",
12487 "^-v^-v^");
12488 end Compiler;
12489 @end group
12490 @end smallexample
12491
12492 @noindent
12493 The @code{Switches} attribute is indexed on a file name (which may or may
12494 not be case sensitive, depending
12495 on the operating system) whose value is a string list. For example:
12496
12497 @smallexample @c projectfile
12498 @group
12499 package Builder is
12500 for Switches ("main1.adb")
12501 use ("^-O2^-O2^");
12502 for Switches ("main2.adb")
12503 use ("^-g^-g^");
12504 end Builder;
12505 @end group
12506 @end smallexample
12507
12508 @noindent
12509 For the @code{Builder} package, the file names must designate source files
12510 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
12511 file names must designate @file{ALI} or source files for main subprograms.
12512 In each case just the file name without an explicit extension is acceptable.
12513
12514 For each tool used in a program build (@command{gnatmake}, the compiler, the
12515 binder, and the linker), the corresponding package @dfn{contributes} a set of
12516 ^switches^switches^ for each file on which the tool is invoked, based on the
12517 ^switch^switch^-related attributes defined in the package.
12518 In particular, the ^switches^switches^
12519 that each of these packages contributes for a given file @var{f} comprise:
12520
12521 @itemize @bullet
12522 @item the value of attribute @code{Switches (@var{f})},
12523 if it is specified in the package for the given file,
12524 @item otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12525 if it is specified in the package.
12526
12527 @end itemize
12528
12529 @noindent
12530 If neither of these attributes is defined in the package, then the package does
12531 not contribute any ^switches^switches^ for the given file.
12532
12533 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12534 two sets, in the following order: those contributed for the file
12535 by the @code{Builder} package;
12536 and the switches passed on the command line.
12537
12538 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12539 the ^switches^switches^ passed to the tool comprise three sets,
12540 in the following order:
12541
12542 @enumerate
12543 @item
12544 the applicable ^switches^switches^ contributed for the file
12545 by the @code{Builder} package in the project file supplied on the command line;
12546
12547 @item
12548 those contributed for the file by the package (in the relevant project file --
12549 see below) corresponding to the tool; and
12550
12551 @item
12552 the applicable switches passed on the command line.
12553 @end enumerate
12554
12555 The term @emph{applicable ^switches^switches^} reflects the fact that
12556 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12557 tools, depending on the individual ^switch^switch^.
12558
12559 @command{gnatmake} may invoke the compiler on source files from different
12560 projects. The Project Manager will use the appropriate project file to
12561 determine the @code{Compiler} package for each source file being compiled.
12562 Likewise for the @code{Binder} and @code{Linker} packages.
12563
12564 As an example, consider the following package in a project file:
12565
12566 @smallexample @c projectfile
12567 @group
12568 project Proj1 is
12569 package Compiler is
12570 for ^Default_Switches^Default_Switches^ ("Ada")
12571 use ("^-g^-g^");
12572 for Switches ("a.adb")
12573 use ("^-O1^-O1^");
12574 for Switches ("b.adb")
12575 use ("^-O2^-O2^",
12576 "^-gnaty^-gnaty^");
12577 end Compiler;
12578 end Proj1;
12579 @end group
12580 @end smallexample
12581
12582 @noindent
12583 If @command{gnatmake} is invoked with this project file, and it needs to
12584 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12585 @file{a.adb} will be compiled with the ^switch^switch^
12586 @option{^-O1^-O1^},
12587 @file{b.adb} with ^switches^switches^
12588 @option{^-O2^-O2^}
12589 and @option{^-gnaty^-gnaty^},
12590 and @file{c.adb} with @option{^-g^-g^}.
12591
12592 The following example illustrates the ordering of the ^switches^switches^
12593 contributed by different packages:
12594
12595 @smallexample @c projectfile
12596 @group
12597 project Proj2 is
12598 package Builder is
12599 for Switches ("main.adb")
12600 use ("^-g^-g^",
12601 "^-O1^-)1^",
12602 "^-f^-f^");
12603 end Builder;
12604 @end group
12605
12606 @group
12607 package Compiler is
12608 for Switches ("main.adb")
12609 use ("^-O2^-O2^");
12610 end Compiler;
12611 end Proj2;
12612 @end group
12613 @end smallexample
12614
12615 @noindent
12616 If you issue the command:
12617
12618 @smallexample
12619 gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
12620 @end smallexample
12621
12622 @noindent
12623 then the compiler will be invoked on @file{main.adb} with the following
12624 sequence of ^switches^switches^
12625
12626 @smallexample
12627 ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
12628 @end smallexample
12629
12630 @noindent
12631 with the last @option{^-O^-O^}
12632 ^switch^switch^ having precedence over the earlier ones;
12633 several other ^switches^switches^
12634 (such as @option{^-c^-c^}) are added implicitly.
12635
12636 The ^switches^switches^
12637 @option{^-g^-g^}
12638 and @option{^-O1^-O1^} are contributed by package
12639 @code{Builder}, @option{^-O2^-O2^} is contributed
12640 by the package @code{Compiler}
12641 and @option{^-O0^-O0^} comes from the command line.
12642
12643 The @option{^-g^-g^}
12644 ^switch^switch^ will also be passed in the invocation of
12645 @command{Gnatlink.}
12646
12647 A final example illustrates switch contributions from packages in different
12648 project files:
12649
12650 @smallexample @c projectfile
12651 @group
12652 project Proj3 is
12653 for Source_Files use ("pack.ads", "pack.adb");
12654 package Compiler is
12655 for ^Default_Switches^Default_Switches^ ("Ada")
12656 use ("^-gnata^-gnata^");
12657 end Compiler;
12658 end Proj3;
12659 @end group
12660
12661 @group
12662 with "Proj3";
12663 project Proj4 is
12664 for Source_Files use ("foo_main.adb", "bar_main.adb");
12665 package Builder is
12666 for Switches ("foo_main.adb")
12667 use ("^-s^-s^",
12668 "^-g^-g^");
12669 end Builder;
12670 end Proj4;
12671 @end group
12672
12673 @group
12674 -- Ada source file:
12675 with Pack;
12676 procedure Foo_Main is
12677 @dots{}
12678 end Foo_Main;
12679 @end group
12680 @end smallexample
12681
12682 @noindent
12683 If the command is
12684 @smallexample
12685 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
12686 @end smallexample
12687
12688 @noindent
12689 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
12690 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
12691 @option{^-gnato^-gnato^} (passed on the command line).
12692 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
12693 are @option{^-g^-g^} from @code{Proj4.Builder},
12694 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
12695 and @option{^-gnato^-gnato^} from the command line.
12696
12697 When using @command{gnatmake} with project files, some ^switches^switches^ or
12698 arguments may be expressed as relative paths. As the working directory where
12699 compilation occurs may change, these relative paths are converted to absolute
12700 paths. For the ^switches^switches^ found in a project file, the relative paths
12701 are relative to the project file directory, for the switches on the command
12702 line, they are relative to the directory where @command{gnatmake} is invoked.
12703 The ^switches^switches^ for which this occurs are:
12704 ^-I^-I^,
12705 ^-A^-A^,
12706 ^-L^-L^,
12707 ^-aO^-aO^,
12708 ^-aL^-aL^,
12709 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
12710 ^switch^switch^
12711 ^-o^-o^, object files specified in package @code{Linker} or after
12712 -largs on the command line). The exception to this rule is the ^switch^switch^
12713 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
12714
12715 @c ---------------------------------------------
12716 @node Specifying Configuration Pragmas
12717 @subsection Specifying Configuration Pragmas
12718 @c ---------------------------------------------
12719
12720 @noindent
12721 When using @command{gnatmake} with project files, if there exists a file
12722 @file{gnat.adc} that contains configuration pragmas, this file will be
12723 ignored.
12724
12725 Configuration pragmas can be defined by means of the following attributes in
12726 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
12727 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
12728
12729 Both these attributes are single string attributes. Their values is the path
12730 name of a file containing configuration pragmas. If a path name is relative,
12731 then it is relative to the project directory of the project file where the
12732 attribute is defined.
12733
12734 When compiling a source, the configuration pragmas used are, in order,
12735 those listed in the file designated by attribute
12736 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
12737 project file, if it is specified, and those listed in the file designated by
12738 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
12739 the project file of the source, if it exists.
12740
12741 @c ---------------------------------------------
12742 @node Project Files and Main Subprograms
12743 @subsection Project Files and Main Subprograms
12744 @c ---------------------------------------------
12745
12746 @noindent
12747 When using a project file, you can invoke @command{gnatmake}
12748 with one or several main subprograms, by specifying their source files on the
12749 command line.
12750
12751 @smallexample
12752 gnatmake ^-P^/PROJECT_FILE=^prj main1.adb main2.adb main3.adb
12753 @end smallexample
12754
12755 @noindent
12756 Each of these needs to be a source file of the same project, except
12757 when the switch ^-u^/UNIQUE^ is used.
12758
12759 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
12760 same project, one of the project in the tree rooted at the project specified
12761 on the command line. The package @code{Builder} of this common project, the
12762 "main project" is the one that is considered by @command{gnatmake}.
12763
12764 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
12765 imported directly or indirectly by the project specified on the command line.
12766 Note that if such a source file is not part of the project specified on the
12767 command line, the ^switches^switches^ found in package @code{Builder} of the
12768 project specified on the command line, if any, that are transmitted
12769 to the compiler will still be used, not those found in the project file of
12770 the source file.
12771
12772 When using a project file, you can also invoke @command{gnatmake} without
12773 explicitly specifying any main, and the effect depends on whether you have
12774 defined the @code{Main} attribute. This attribute has a string list value,
12775 where each element in the list is the name of a source file (the file
12776 extension is optional) that contains a unit that can be a main subprogram.
12777
12778 If the @code{Main} attribute is defined in a project file as a non-empty
12779 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
12780 line, then invoking @command{gnatmake} with this project file but without any
12781 main on the command line is equivalent to invoking @command{gnatmake} with all
12782 the file names in the @code{Main} attribute on the command line.
12783
12784 Example:
12785 @smallexample @c projectfile
12786 @group
12787 project Prj is
12788 for Main use ("main1.adb", "main2.adb", "main3.adb");
12789 end Prj;
12790 @end group
12791 @end smallexample
12792
12793 @noindent
12794 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
12795 is equivalent to
12796 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1.adb main2.adb main3.adb"}.
12797
12798 When the project attribute @code{Main} is not specified, or is specified
12799 as an empty string list, or when the switch @option{-u} is used on the command
12800 line, then invoking @command{gnatmake} with no main on the command line will
12801 result in all immediate sources of the project file being checked, and
12802 potentially recompiled. Depending on the presence of the switch @option{-u},
12803 sources from other project files on which the immediate sources of the main
12804 project file depend are also checked and potentially recompiled. In other
12805 words, the @option{-u} switch is applied to all of the immediate sources of the
12806 main project file.
12807
12808 When no main is specified on the command line and attribute @code{Main} exists
12809 and includes several mains, or when several mains are specified on the
12810 command line, the default ^switches^switches^ in package @code{Builder} will
12811 be used for all mains, even if there are specific ^switches^switches^
12812 specified for one or several mains.
12813
12814 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
12815 the specific ^switches^switches^ for each main, if they are specified.
12816
12817 @c ---------------------------------------------
12818 @node Library Project Files
12819 @subsection Library Project Files
12820 @c ---------------------------------------------
12821
12822 @noindent
12823 When @command{gnatmake} is invoked with a main project file that is a library
12824 project file, it is not allowed to specify one or more mains on the command
12825 line.
12826
12827 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
12828 ^-l^/ACTION=LINK^ have special meanings.
12829
12830 @itemize @bullet
12831 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
12832 to @command{gnatmake} that @command{gnatbind} should be invoked for the
12833 library.
12834
12835 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
12836 to @command{gnatmake} that the binder generated file should be compiled
12837 (in the case of a stand-alone library) and that the library should be built.
12838 @end itemize
12839
12840 @c ---------------------------------------------
12841 @node The GNAT Driver and Project Files
12842 @section The GNAT Driver and Project Files
12843 @c ---------------------------------------------
12844
12845 @noindent
12846 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
12847 can benefit from project files:
12848 (@command{^gnatbind^gnatbind^},
12849 @command{^gnatcheck^gnatcheck^},
12850 @command{^gnatclean^gnatclean^},
12851 @command{^gnatelim^gnatelim^},
12852 @command{^gnatfind^gnatfind^},
12853 @command{^gnatlink^gnatlink^},
12854 @command{^gnatls^gnatls^},
12855 @command{^gnatmetric^gnatmetric^},
12856 @command{^gnatpp^gnatpp^},
12857 @command{^gnatstub^gnatstub^},
12858 and @command{^gnatxref^gnatxref^}). However, none of these tools can be invoked
12859 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
12860 They must be invoked through the @command{gnat} driver.
12861
12862 The @command{gnat} driver is a wrapper that accepts a number of commands and
12863 calls the corresponding tool. It was designed initially for VMS platforms (to
12864 convert VMS qualifiers to Unix-style switches), but it is now available on all
12865 GNAT platforms.
12866
12867 On non-VMS platforms, the @command{gnat} driver accepts the following commands
12868 (case insensitive):
12869
12870 @itemize @bullet
12871 @item BIND to invoke @command{^gnatbind^gnatbind^}
12872 @item CHOP to invoke @command{^gnatchop^gnatchop^}
12873 @item CLEAN to invoke @command{^gnatclean^gnatclean^}
12874 @item COMP or COMPILE to invoke the compiler
12875 @item ELIM to invoke @command{^gnatelim^gnatelim^}
12876 @item FIND to invoke @command{^gnatfind^gnatfind^}
12877 @item KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
12878 @item LINK to invoke @command{^gnatlink^gnatlink^}
12879 @item LS or LIST to invoke @command{^gnatls^gnatls^}
12880 @item MAKE to invoke @command{^gnatmake^gnatmake^}
12881 @item NAME to invoke @command{^gnatname^gnatname^}
12882 @item PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
12883 @item PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
12884 @item METRIC to invoke @command{^gnatmetric^gnatmetric^}
12885 @item STUB to invoke @command{^gnatstub^gnatstub^}
12886 @item XREF to invoke @command{^gnatxref^gnatxref^}
12887
12888 @end itemize
12889
12890 @noindent
12891 (note that the compiler is invoked using the command
12892 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
12893
12894 On non-VMS platforms, between @command{gnat} and the command, two
12895 special switches may be used:
12896
12897 @itemize @bullet
12898 @item @command{-v} to display the invocation of the tool.
12899 @item @command{-dn} to prevent the @command{gnat} driver from removing
12900 the temporary files it has created. These temporary files are
12901 configuration files and temporary file list files.
12902
12903 @end itemize
12904
12905 @noindent
12906 The command may be followed by switches and arguments for the invoked
12907 tool.
12908
12909 @smallexample
12910 gnat bind -C main.ali
12911 gnat ls -a main
12912 gnat chop foo.txt
12913 @end smallexample
12914
12915 @noindent
12916 Switches may also be put in text files, one switch per line, and the text
12917 files may be specified with their path name preceded by '@@'.
12918
12919 @smallexample
12920 gnat bind @@args.txt main.ali
12921 @end smallexample
12922
12923 @noindent
12924 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
12925 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
12926 (@option{^-P^/PROJECT_FILE^},
12927 @option{^-X^/EXTERNAL_REFERENCE^} and
12928 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
12929 the switches of the invoking tool.
12930
12931 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
12932 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
12933 the immediate sources of the specified project file.
12934
12935 When GNAT METRIC is used with a project file, but with no source
12936 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
12937 with all the immediate sources of the specified project file and with
12938 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
12939 of the project.
12940
12941 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
12942 a project file, no source is specified on the command line and
12943 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
12944 the underlying tool (^gnatpp^gnatpp^ or
12945 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
12946 not only for the immediate sources of the main project.
12947 @ifclear vms
12948 (-U stands for Universal or Union of the project files of the project tree)
12949 @end ifclear
12950
12951 For each of the following commands, there is optionally a corresponding
12952 package in the main project.
12953
12954 @itemize @bullet
12955 @item package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
12956
12957 @item package @code{Check} for command CHECK (invoking
12958 @code{^gnatcheck^gnatcheck^})
12959
12960 @item package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
12961
12962 @item package @code{Cross_Reference} for command XREF (invoking
12963 @code{^gnatxref^gnatxref^})
12964
12965 @item package @code{Eliminate} for command ELIM (invoking
12966 @code{^gnatelim^gnatelim^})
12967
12968 @item package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
12969
12970 @item package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
12971
12972 @item package @code{Gnatstub} for command STUB
12973 (invoking @code{^gnatstub^gnatstub^})
12974
12975 @item package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
12976
12977 @item package @code{Check} for command CHECK
12978 (invoking @code{^gnatcheck^gnatcheck^})
12979
12980 @item package @code{Metrics} for command METRIC
12981 (invoking @code{^gnatmetric^gnatmetric^})
12982
12983 @item package @code{Pretty_Printer} for command PP or PRETTY
12984 (invoking @code{^gnatpp^gnatpp^})
12985
12986 @end itemize
12987
12988 @noindent
12989 Package @code{Gnatls} has a unique attribute @code{Switches},
12990 a simple variable with a string list value. It contains ^switches^switches^
12991 for the invocation of @code{^gnatls^gnatls^}.
12992
12993 @smallexample @c projectfile
12994 @group
12995 project Proj1 is
12996 package gnatls is
12997 for Switches
12998 use ("^-a^-a^",
12999 "^-v^-v^");
13000 end gnatls;
13001 end Proj1;
13002 @end group
13003 @end smallexample
13004
13005 @noindent
13006 All other packages have two attribute @code{Switches} and
13007 @code{^Default_Switches^Default_Switches^}.
13008
13009 @code{Switches} is an indexed attribute, indexed by the
13010 source file name, that has a string list value: the ^switches^switches^ to be
13011 used when the tool corresponding to the package is invoked for the specific
13012 source file.
13013
13014 @code{^Default_Switches^Default_Switches^} is an attribute,
13015 indexed by the programming language that has a string list value.
13016 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13017 ^switches^switches^ for the invocation of the tool corresponding
13018 to the package, except if a specific @code{Switches} attribute
13019 is specified for the source file.
13020
13021 @smallexample @c projectfile
13022 @group
13023 project Proj is
13024
13025 for Source_Dirs use ("**");
13026
13027 package gnatls is
13028 for Switches use
13029 ("^-a^-a^",
13030 "^-v^-v^");
13031 end gnatls;
13032 @end group
13033 @group
13034
13035 package Compiler is
13036 for ^Default_Switches^Default_Switches^ ("Ada")
13037 use ("^-gnatv^-gnatv^",
13038 "^-gnatwa^-gnatwa^");
13039 end Binder;
13040 @end group
13041 @group
13042
13043 package Binder is
13044 for ^Default_Switches^Default_Switches^ ("Ada")
13045 use ("^-C^-C^",
13046 "^-e^-e^");
13047 end Binder;
13048 @end group
13049 @group
13050
13051 package Linker is
13052 for ^Default_Switches^Default_Switches^ ("Ada")
13053 use ("^-C^-C^");
13054 for Switches ("main.adb")
13055 use ("^-C^-C^",
13056 "^-v^-v^",
13057 "^-v^-v^");
13058 end Linker;
13059 @end group
13060 @group
13061
13062 package Finder is
13063 for ^Default_Switches^Default_Switches^ ("Ada")
13064 use ("^-a^-a^",
13065 "^-f^-f^");
13066 end Finder;
13067 @end group
13068 @group
13069
13070 package Cross_Reference is
13071 for ^Default_Switches^Default_Switches^ ("Ada")
13072 use ("^-a^-a^",
13073 "^-f^-f^",
13074 "^-d^-d^",
13075 "^-u^-u^");
13076 end Cross_Reference;
13077 end Proj;
13078 @end group
13079 @end smallexample
13080
13081 @noindent
13082 With the above project file, commands such as
13083
13084 @smallexample
13085 ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13086 ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13087 ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13088 ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13089 ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13090 @end smallexample
13091
13092 @noindent
13093 will set up the environment properly and invoke the tool with the switches
13094 found in the package corresponding to the tool:
13095 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13096 except @code{Switches ("main.adb")}
13097 for @code{^gnatlink^gnatlink^}.
13098 It is also possible to invoke some of the tools,
13099 (@code{^gnatcheck^gnatcheck^},
13100 @code{^gnatmetric^gnatmetric^},
13101 and @code{^gnatpp^gnatpp^})
13102 on a set of project units thanks to the combination of the switches
13103 @option{-P}, @option{-U} and possibly the main unit when one is interested
13104 in its closure. For instance,
13105 @smallexample
13106 gnat metric -Pproj
13107 @end smallexample
13108
13109 @noindent
13110 will compute the metrics for all the immediate units of project
13111 @code{proj}.
13112 @smallexample
13113 gnat metric -Pproj -U
13114 @end smallexample
13115
13116 @noindent
13117 will compute the metrics for all the units of the closure of projects
13118 rooted at @code{proj}.
13119 @smallexample
13120 gnat metric -Pproj -U main_unit
13121 @end smallexample
13122
13123 @noindent
13124 will compute the metrics for the closure of units rooted at
13125 @code{main_unit}. This last possibility relies implicitly
13126 on @command{gnatbind}'s option @option{-R}. But if the argument files for the
13127 tool invoked by the @command{gnat} driver are explicitly specified
13128 either directly or through the tool @option{-files} option, then the tool
13129 is called only for these explicitly specified files.
13130
13131 @c *****************************************
13132 @c * Cross-referencing tools
13133 @c *****************************************
13134
13135 @node The Cross-Referencing Tools gnatxref and gnatfind
13136 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13137 @findex gnatxref
13138 @findex gnatfind
13139
13140 @noindent
13141 The compiler generates cross-referencing information (unless
13142 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13143 This information indicates where in the source each entity is declared and
13144 referenced. Note that entities in package Standard are not included, but
13145 entities in all other predefined units are included in the output.
13146
13147 Before using any of these two tools, you need to compile successfully your
13148 application, so that GNAT gets a chance to generate the cross-referencing
13149 information.
13150
13151 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13152 information to provide the user with the capability to easily locate the
13153 declaration and references to an entity. These tools are quite similar,
13154 the difference being that @code{gnatfind} is intended for locating
13155 definitions and/or references to a specified entity or entities, whereas
13156 @code{gnatxref} is oriented to generating a full report of all
13157 cross-references.
13158
13159 To use these tools, you must not compile your application using the
13160 @option{-gnatx} switch on the @command{gnatmake} command line
13161 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13162 information will not be generated.
13163
13164 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
13165 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
13166
13167 @menu
13168 * Switches for gnatxref::
13169 * Switches for gnatfind::
13170 * Project Files for gnatxref and gnatfind::
13171 * Regular Expressions in gnatfind and gnatxref::
13172 * Examples of gnatxref Usage::
13173 * Examples of gnatfind Usage::
13174 @end menu
13175
13176 @node Switches for gnatxref
13177 @section @code{gnatxref} Switches
13178
13179 @noindent
13180 The command invocation for @code{gnatxref} is:
13181 @smallexample
13182 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
13183 @c Expanding @ovar macro inline (explanation in macro def comments)
13184 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
13185 @end smallexample
13186
13187 @noindent
13188 where
13189
13190 @table @var
13191 @item sourcefile1
13192 @itemx sourcefile2
13193 identifies the source files for which a report is to be generated. The
13194 ``with''ed units will be processed too. You must provide at least one file.
13195
13196 These file names are considered to be regular expressions, so for instance
13197 specifying @file{source*.adb} is the same as giving every file in the current
13198 directory whose name starts with @file{source} and whose extension is
13199 @file{adb}.
13200
13201 You shouldn't specify any directory name, just base names. @command{gnatxref}
13202 and @command{gnatfind} will be able to locate these files by themselves using
13203 the source path. If you specify directories, no result is produced.
13204
13205 @end table
13206
13207 @noindent
13208 The switches can be:
13209 @table @option
13210 @c !sort!
13211 @item --version
13212 @cindex @option{--version} @command{gnatxref}
13213 Display Copyright and version, then exit disregarding all other options.
13214
13215 @item --help
13216 @cindex @option{--help} @command{gnatxref}
13217 If @option{--version} was not used, display usage, then exit disregarding
13218 all other options.
13219
13220 @item ^-a^/ALL_FILES^
13221 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13222 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13223 the read-only files found in the library search path. Otherwise, these files
13224 will be ignored. This option can be used to protect Gnat sources or your own
13225 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13226 much faster, and their output much smaller. Read-only here refers to access
13227 or permissions status in the file system for the current user.
13228
13229 @item -aIDIR
13230 @cindex @option{-aIDIR} (@command{gnatxref})
13231 When looking for source files also look in directory DIR. The order in which
13232 source file search is undertaken is the same as for @command{gnatmake}.
13233
13234 @item -aODIR
13235 @cindex @option{-aODIR} (@command{gnatxref})
13236 When searching for library and object files, look in directory
13237 DIR. The order in which library files are searched is the same as for
13238 @command{gnatmake}.
13239
13240 @item -nostdinc
13241 @cindex @option{-nostdinc} (@command{gnatxref})
13242 Do not look for sources in the system default directory.
13243
13244 @item -nostdlib
13245 @cindex @option{-nostdlib} (@command{gnatxref})
13246 Do not look for library files in the system default directory.
13247
13248 @item --ext=@var{extension}
13249 @cindex @option{--ext} (@command{gnatxref})
13250 Specify an alternate ali file extension. The default is @code{ali} and other
13251 extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
13252 may be specified via this switch. Note that if this switch overrides the
13253 default, which means that only the new extension will be considered.
13254
13255 @item --RTS=@var{rts-path}
13256 @cindex @option{--RTS} (@command{gnatxref})
13257 Specifies the default location of the runtime library. Same meaning as the
13258 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13259
13260 @item ^-d^/DERIVED_TYPES^
13261 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13262 If this switch is set @code{gnatxref} will output the parent type
13263 reference for each matching derived types.
13264
13265 @item ^-f^/FULL_PATHNAME^
13266 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13267 If this switch is set, the output file names will be preceded by their
13268 directory (if the file was found in the search path). If this switch is
13269 not set, the directory will not be printed.
13270
13271 @item ^-g^/IGNORE_LOCALS^
13272 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13273 If this switch is set, information is output only for library-level
13274 entities, ignoring local entities. The use of this switch may accelerate
13275 @code{gnatfind} and @code{gnatxref}.
13276
13277 @item -IDIR
13278 @cindex @option{-IDIR} (@command{gnatxref})
13279 Equivalent to @samp{-aODIR -aIDIR}.
13280
13281 @item -pFILE
13282 @cindex @option{-pFILE} (@command{gnatxref})
13283 Specify a project file to use @xref{GNAT Project Manager}.
13284 If you need to use the @file{.gpr}
13285 project files, you should use gnatxref through the GNAT driver
13286 (@command{gnat xref -Pproject}).
13287
13288 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13289 project file in the current directory.
13290
13291 If a project file is either specified or found by the tools, then the content
13292 of the source directory and object directory lines are added as if they
13293 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13294 and @samp{^-aO^OBJECT_SEARCH^}.
13295 @item ^-u^/UNUSED^
13296 Output only unused symbols. This may be really useful if you give your
13297 main compilation unit on the command line, as @code{gnatxref} will then
13298 display every unused entity and 'with'ed package.
13299
13300 @ifclear vms
13301 @item -v
13302 Instead of producing the default output, @code{gnatxref} will generate a
13303 @file{tags} file that can be used by vi. For examples how to use this
13304 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
13305 to the standard output, thus you will have to redirect it to a file.
13306 @end ifclear
13307
13308 @end table
13309
13310 @noindent
13311 All these switches may be in any order on the command line, and may even
13312 appear after the file names. They need not be separated by spaces, thus
13313 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13314 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13315
13316 @node Switches for gnatfind
13317 @section @code{gnatfind} Switches
13318
13319 @noindent
13320 The command line for @code{gnatfind} is:
13321
13322 @smallexample
13323 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13324 @c @r{[}@var{file1} @var{file2} @dots{}]
13325 @c Expanding @ovar macro inline (explanation in macro def comments)
13326 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13327 @r{[}@var{file1} @var{file2} @dots{}@r{]}
13328 @end smallexample
13329
13330 @noindent
13331 where
13332
13333 @table @var
13334 @item pattern
13335 An entity will be output only if it matches the regular expression found
13336 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
13337
13338 Omitting the pattern is equivalent to specifying @samp{*}, which
13339 will match any entity. Note that if you do not provide a pattern, you
13340 have to provide both a sourcefile and a line.
13341
13342 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13343 for matching purposes. At the current time there is no support for
13344 8-bit codes other than Latin-1, or for wide characters in identifiers.
13345
13346 @item sourcefile
13347 @code{gnatfind} will look for references, bodies or declarations
13348 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
13349 and column @var{column}. See @ref{Examples of gnatfind Usage}
13350 for syntax examples.
13351
13352 @item line
13353 is a decimal integer identifying the line number containing
13354 the reference to the entity (or entities) to be located.
13355
13356 @item column
13357 is a decimal integer identifying the exact location on the
13358 line of the first character of the identifier for the
13359 entity reference. Columns are numbered from 1.
13360
13361 @item file1 file2 @dots{}
13362 The search will be restricted to these source files. If none are given, then
13363 the search will be done for every library file in the search path.
13364 These file must appear only after the pattern or sourcefile.
13365
13366 These file names are considered to be regular expressions, so for instance
13367 specifying @file{source*.adb} is the same as giving every file in the current
13368 directory whose name starts with @file{source} and whose extension is
13369 @file{adb}.
13370
13371 The location of the spec of the entity will always be displayed, even if it
13372 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{} The
13373 occurrences of the entity in the separate units of the ones given on the
13374 command line will also be displayed.
13375
13376 Note that if you specify at least one file in this part, @code{gnatfind} may
13377 sometimes not be able to find the body of the subprograms.
13378
13379 @end table
13380
13381 @noindent
13382 At least one of 'sourcefile' or 'pattern' has to be present on
13383 the command line.
13384
13385 The following switches are available:
13386 @table @option
13387 @c !sort!
13388
13389 @cindex @option{--version} @command{gnatfind}
13390 Display Copyright and version, then exit disregarding all other options.
13391
13392 @item --help
13393 @cindex @option{--help} @command{gnatfind}
13394 If @option{--version} was not used, display usage, then exit disregarding
13395 all other options.
13396
13397 @item ^-a^/ALL_FILES^
13398 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
13399 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13400 the read-only files found in the library search path. Otherwise, these files
13401 will be ignored. This option can be used to protect Gnat sources or your own
13402 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13403 much faster, and their output much smaller. Read-only here refers to access
13404 or permission status in the file system for the current user.
13405
13406 @item -aIDIR
13407 @cindex @option{-aIDIR} (@command{gnatfind})
13408 When looking for source files also look in directory DIR. The order in which
13409 source file search is undertaken is the same as for @command{gnatmake}.
13410
13411 @item -aODIR
13412 @cindex @option{-aODIR} (@command{gnatfind})
13413 When searching for library and object files, look in directory
13414 DIR. The order in which library files are searched is the same as for
13415 @command{gnatmake}.
13416
13417 @item -nostdinc
13418 @cindex @option{-nostdinc} (@command{gnatfind})
13419 Do not look for sources in the system default directory.
13420
13421 @item -nostdlib
13422 @cindex @option{-nostdlib} (@command{gnatfind})
13423 Do not look for library files in the system default directory.
13424
13425 @item --ext=@var{extension}
13426 @cindex @option{--ext} (@command{gnatfind})
13427 Specify an alternate ali file extension. The default is @code{ali} and other
13428 extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
13429 may be specified via this switch. Note that if this switch overrides the
13430 default, which means that only the new extension will be considered.
13431
13432 @item --RTS=@var{rts-path}
13433 @cindex @option{--RTS} (@command{gnatfind})
13434 Specifies the default location of the runtime library. Same meaning as the
13435 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13436
13437 @item ^-d^/DERIVED_TYPE_INFORMATION^
13438 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
13439 If this switch is set, then @code{gnatfind} will output the parent type
13440 reference for each matching derived types.
13441
13442 @item ^-e^/EXPRESSIONS^
13443 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
13444 By default, @code{gnatfind} accept the simple regular expression set for
13445 @samp{pattern}. If this switch is set, then the pattern will be
13446 considered as full Unix-style regular expression.
13447
13448 @item ^-f^/FULL_PATHNAME^
13449 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
13450 If this switch is set, the output file names will be preceded by their
13451 directory (if the file was found in the search path). If this switch is
13452 not set, the directory will not be printed.
13453
13454 @item ^-g^/IGNORE_LOCALS^
13455 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
13456 If this switch is set, information is output only for library-level
13457 entities, ignoring local entities. The use of this switch may accelerate
13458 @code{gnatfind} and @code{gnatxref}.
13459
13460 @item -IDIR
13461 @cindex @option{-IDIR} (@command{gnatfind})
13462 Equivalent to @samp{-aODIR -aIDIR}.
13463
13464 @item -pFILE
13465 @cindex @option{-pFILE} (@command{gnatfind})
13466 Specify a project file (@pxref{GNAT Project Manager}) to use.
13467 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13468 project file in the current directory.
13469
13470 If a project file is either specified or found by the tools, then the content
13471 of the source directory and object directory lines are added as if they
13472 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
13473 @samp{^-aO^/OBJECT_SEARCH^}.
13474
13475 @item ^-r^/REFERENCES^
13476 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
13477 By default, @code{gnatfind} will output only the information about the
13478 declaration, body or type completion of the entities. If this switch is
13479 set, the @code{gnatfind} will locate every reference to the entities in
13480 the files specified on the command line (or in every file in the search
13481 path if no file is given on the command line).
13482
13483 @item ^-s^/PRINT_LINES^
13484 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
13485 If this switch is set, then @code{gnatfind} will output the content
13486 of the Ada source file lines were the entity was found.
13487
13488 @item ^-t^/TYPE_HIERARCHY^
13489 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
13490 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13491 the specified type. It act like -d option but recursively from parent
13492 type to parent type. When this switch is set it is not possible to
13493 specify more than one file.
13494
13495 @end table
13496
13497 @noindent
13498 All these switches may be in any order on the command line, and may even
13499 appear after the file names. They need not be separated by spaces, thus
13500 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13501 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13502
13503 As stated previously, gnatfind will search in every directory in the
13504 search path. You can force it to look only in the current directory if
13505 you specify @code{*} at the end of the command line.
13506
13507 @node Project Files for gnatxref and gnatfind
13508 @section Project Files for @command{gnatxref} and @command{gnatfind}
13509
13510 @noindent
13511 Project files allow a programmer to specify how to compile its
13512 application, where to find sources, etc. These files are used
13513 @ifclear vms
13514 primarily by GPS, but they can also be used
13515 @end ifclear
13516 by the two tools
13517 @code{gnatxref} and @code{gnatfind}.
13518
13519 A project file name must end with @file{.gpr}. If a single one is
13520 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13521 extract the information from it. If multiple project files are found, none of
13522 them is read, and you have to use the @samp{-p} switch to specify the one
13523 you want to use.
13524
13525 The following lines can be included, even though most of them have default
13526 values which can be used in most cases.
13527 The lines can be entered in any order in the file.
13528 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
13529 each line. If you have multiple instances, only the last one is taken into
13530 account.
13531
13532 @table @code
13533 @item src_dir=DIR
13534 [default: @code{"^./^[]^"}]
13535 specifies a directory where to look for source files. Multiple @code{src_dir}
13536 lines can be specified and they will be searched in the order they
13537 are specified.
13538
13539 @item obj_dir=DIR
13540 [default: @code{"^./^[]^"}]
13541 specifies a directory where to look for object and library files. Multiple
13542 @code{obj_dir} lines can be specified, and they will be searched in the order
13543 they are specified
13544
13545 @item comp_opt=SWITCHES
13546 [default: @code{""}]
13547 creates a variable which can be referred to subsequently by using
13548 the @code{$@{comp_opt@}} notation. This is intended to store the default
13549 switches given to @command{gnatmake} and @command{gcc}.
13550
13551 @item bind_opt=SWITCHES
13552 [default: @code{""}]
13553 creates a variable which can be referred to subsequently by using
13554 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13555 switches given to @command{gnatbind}.
13556
13557 @item link_opt=SWITCHES
13558 [default: @code{""}]
13559 creates a variable which can be referred to subsequently by using
13560 the @samp{$@{link_opt@}} notation. This is intended to store the default
13561 switches given to @command{gnatlink}.
13562
13563 @item main=EXECUTABLE
13564 [default: @code{""}]
13565 specifies the name of the executable for the application. This variable can
13566 be referred to in the following lines by using the @samp{$@{main@}} notation.
13567
13568 @ifset vms
13569 @item comp_cmd=COMMAND
13570 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
13571 @end ifset
13572 @ifclear vms
13573 @item comp_cmd=COMMAND
13574 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
13575 @end ifclear
13576 specifies the command used to compile a single file in the application.
13577
13578 @ifset vms
13579 @item make_cmd=COMMAND
13580 [default: @code{"GNAT MAKE $@{main@}
13581 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
13582 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
13583 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
13584 @end ifset
13585 @ifclear vms
13586 @item make_cmd=COMMAND
13587 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
13588 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
13589 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
13590 @end ifclear
13591 specifies the command used to recompile the whole application.
13592
13593 @item run_cmd=COMMAND
13594 [default: @code{"$@{main@}"}]
13595 specifies the command used to run the application.
13596
13597 @item debug_cmd=COMMAND
13598 [default: @code{"gdb $@{main@}"}]
13599 specifies the command used to debug the application
13600
13601 @end table
13602
13603 @noindent
13604 @command{gnatxref} and @command{gnatfind} only take into account the
13605 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
13606
13607 @node Regular Expressions in gnatfind and gnatxref
13608 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
13609
13610 @noindent
13611 As specified in the section about @command{gnatfind}, the pattern can be a
13612 regular expression. Actually, there are to set of regular expressions
13613 which are recognized by the program:
13614
13615 @table @code
13616 @item globbing patterns
13617 These are the most usual regular expression. They are the same that you
13618 generally used in a Unix shell command line, or in a DOS session.
13619
13620 Here is a more formal grammar:
13621 @smallexample
13622 @group
13623 @iftex
13624 @leftskip=.5cm
13625 @end iftex
13626 regexp ::= term
13627 term ::= elmt -- matches elmt
13628 term ::= elmt elmt -- concatenation (elmt then elmt)
13629 term ::= * -- any string of 0 or more characters
13630 term ::= ? -- matches any character
13631 term ::= [char @{char@}] -- matches any character listed
13632 term ::= [char - char] -- matches any character in range
13633 @end group
13634 @end smallexample
13635
13636 @item full regular expression
13637 The second set of regular expressions is much more powerful. This is the
13638 type of regular expressions recognized by utilities such a @file{grep}.
13639
13640 The following is the form of a regular expression, expressed in Ada
13641 reference manual style BNF is as follows
13642
13643 @smallexample
13644 @iftex
13645 @leftskip=.5cm
13646 @end iftex
13647 @group
13648 regexp ::= term @{| term@} -- alternation (term or term @dots{})
13649
13650 term ::= item @{item@} -- concatenation (item then item)
13651
13652 item ::= elmt -- match elmt
13653 item ::= elmt * -- zero or more elmt's
13654 item ::= elmt + -- one or more elmt's
13655 item ::= elmt ? -- matches elmt or nothing
13656 @end group
13657 @group
13658 elmt ::= nschar -- matches given character
13659 elmt ::= [nschar @{nschar@}] -- matches any character listed
13660 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
13661 elmt ::= [char - char] -- matches chars in given range
13662 elmt ::= \ char -- matches given character
13663 elmt ::= . -- matches any single character
13664 elmt ::= ( regexp ) -- parens used for grouping
13665
13666 char ::= any character, including special characters
13667 nschar ::= any character except ()[].*+?^^^
13668 @end group
13669 @end smallexample
13670
13671 Following are a few examples:
13672
13673 @table @samp
13674 @item abcde|fghi
13675 will match any of the two strings @samp{abcde} and @samp{fghi},
13676
13677 @item abc*d
13678 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
13679 @samp{abcccd}, and so on,
13680
13681 @item [a-z]+
13682 will match any string which has only lowercase characters in it (and at
13683 least one character.
13684
13685 @end table
13686 @end table
13687
13688 @node Examples of gnatxref Usage
13689 @section Examples of @code{gnatxref} Usage
13690
13691 @subsection General Usage
13692
13693 @noindent
13694 For the following examples, we will consider the following units:
13695
13696 @smallexample @c ada
13697 @group
13698 @cartouche
13699 main.ads:
13700 1: with Bar;
13701 2: package Main is
13702 3: procedure Foo (B : in Integer);
13703 4: C : Integer;
13704 5: private
13705 6: D : Integer;
13706 7: end Main;
13707
13708 main.adb:
13709 1: package body Main is
13710 2: procedure Foo (B : in Integer) is
13711 3: begin
13712 4: C := B;
13713 5: D := B;
13714 6: Bar.Print (B);
13715 7: Bar.Print (C);
13716 8: end Foo;
13717 9: end Main;
13718
13719 bar.ads:
13720 1: package Bar is
13721 2: procedure Print (B : Integer);
13722 3: end bar;
13723 @end cartouche
13724 @end group
13725 @end smallexample
13726
13727 @table @code
13728
13729 @noindent
13730 The first thing to do is to recompile your application (for instance, in
13731 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13732 the cross-referencing information.
13733 You can then issue any of the following commands:
13734
13735 @item gnatxref main.adb
13736 @code{gnatxref} generates cross-reference information for main.adb
13737 and every unit 'with'ed by main.adb.
13738
13739 The output would be:
13740 @smallexample
13741 @iftex
13742 @leftskip=0cm
13743 @end iftex
13744 B Type: Integer
13745 Decl: bar.ads 2:22
13746 B Type: Integer
13747 Decl: main.ads 3:20
13748 Body: main.adb 2:20
13749 Ref: main.adb 4:13 5:13 6:19
13750 Bar Type: Unit
13751 Decl: bar.ads 1:9
13752 Ref: main.adb 6:8 7:8
13753 main.ads 1:6
13754 C Type: Integer
13755 Decl: main.ads 4:5
13756 Modi: main.adb 4:8
13757 Ref: main.adb 7:19
13758 D Type: Integer
13759 Decl: main.ads 6:5
13760 Modi: main.adb 5:8
13761 Foo Type: Unit
13762 Decl: main.ads 3:15
13763 Body: main.adb 2:15
13764 Main Type: Unit
13765 Decl: main.ads 2:9
13766 Body: main.adb 1:14
13767 Print Type: Unit
13768 Decl: bar.ads 2:15
13769 Ref: main.adb 6:12 7:12
13770 @end smallexample
13771
13772 @noindent
13773 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13774 its body is in main.adb, line 1, column 14 and is not referenced any where.
13775
13776 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13777 is referenced in main.adb, line 6 column 12 and line 7 column 12.
13778
13779 @item gnatxref package1.adb package2.ads
13780 @code{gnatxref} will generates cross-reference information for
13781 package1.adb, package2.ads and any other package 'with'ed by any
13782 of these.
13783
13784 @end table
13785
13786 @ifclear vms
13787 @subsection Using gnatxref with vi
13788
13789 @code{gnatxref} can generate a tags file output, which can be used
13790 directly from @command{vi}. Note that the standard version of @command{vi}
13791 will not work properly with overloaded symbols. Consider using another
13792 free implementation of @command{vi}, such as @command{vim}.
13793
13794 @smallexample
13795 $ gnatxref -v gnatfind.adb > tags
13796 @end smallexample
13797
13798 @noindent
13799 will generate the tags file for @code{gnatfind} itself (if the sources
13800 are in the search path!).
13801
13802 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
13803 (replacing @var{entity} by whatever you are looking for), and vi will
13804 display a new file with the corresponding declaration of entity.
13805 @end ifclear
13806
13807 @node Examples of gnatfind Usage
13808 @section Examples of @code{gnatfind} Usage
13809
13810 @table @code
13811
13812 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
13813 Find declarations for all entities xyz referenced at least once in
13814 main.adb. The references are search in every library file in the search
13815 path.
13816
13817 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
13818 switch is set)
13819
13820 The output will look like:
13821 @smallexample
13822 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13823 ^directory/^[directory]^main.adb:24:10: xyz <= body
13824 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13825 @end smallexample
13826
13827 @noindent
13828 that is to say, one of the entities xyz found in main.adb is declared at
13829 line 12 of main.ads (and its body is in main.adb), and another one is
13830 declared at line 45 of foo.ads
13831
13832 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
13833 This is the same command as the previous one, instead @code{gnatfind} will
13834 display the content of the Ada source file lines.
13835
13836 The output will look like:
13837
13838 @smallexample
13839 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13840 procedure xyz;
13841 ^directory/^[directory]^main.adb:24:10: xyz <= body
13842 procedure xyz is
13843 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13844 xyz : Integer;
13845 @end smallexample
13846
13847 @noindent
13848 This can make it easier to find exactly the location your are looking
13849 for.
13850
13851 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
13852 Find references to all entities containing an x that are
13853 referenced on line 123 of main.ads.
13854 The references will be searched only in main.ads and foo.adb.
13855
13856 @item gnatfind main.ads:123
13857 Find declarations and bodies for all entities that are referenced on
13858 line 123 of main.ads.
13859
13860 This is the same as @code{gnatfind "*":main.adb:123}.
13861
13862 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
13863 Find the declaration for the entity referenced at column 45 in
13864 line 123 of file main.adb in directory mydir. Note that it
13865 is usual to omit the identifier name when the column is given,
13866 since the column position identifies a unique reference.
13867
13868 The column has to be the beginning of the identifier, and should not
13869 point to any character in the middle of the identifier.
13870
13871 @end table
13872
13873 @c *********************************
13874 @node The GNAT Pretty-Printer gnatpp
13875 @chapter The GNAT Pretty-Printer @command{gnatpp}
13876 @findex gnatpp
13877 @cindex Pretty-Printer
13878
13879 @menu
13880 * Switches for gnatpp::
13881 * Formatting Rules::
13882 @end menu
13883
13884 @noindent
13885 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
13886 for source reformatting / pretty-printing.
13887 It takes an Ada source file as input and generates a reformatted
13888 version as output.
13889 You can specify various style directives via switches; e.g.,
13890 identifier case conventions, rules of indentation, and comment layout.
13891
13892 Note: A newly-redesigned set of formatting algorithms used by gnatpp
13893 is now available.
13894 To invoke the old formatting algorithms, use the @option{--pp-old} switch.
13895 Support for @option{--pp-old} will be removed in some future version.
13896
13897 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
13898 tree for the input source and thus requires the input to be syntactically and
13899 semantically legal.
13900 If this condition is not met, @command{gnatpp} will terminate with an
13901 error message; no output file will be generated.
13902
13903 @command{gnatpp} cannot process sources that contain
13904 preprocessing directives.
13905
13906 If the compilation unit
13907 contained in the input source depends semantically upon units located
13908 outside the current directory, you have to provide the source search path
13909 when invoking @command{gnatpp}, if these units are contained in files with
13910 names that do not follow the GNAT file naming rules, you have to provide
13911 the configuration file describing the corresponding naming scheme;
13912 see the description of the @command{gnatpp}
13913 switches below. Another possibility is to use a project file and to
13914 call @command{gnatpp} through the @command{gnat} driver
13915 (see @ref{The GNAT Driver and Project Files}).
13916
13917 The @command{gnatpp} command has the form
13918
13919 @smallexample
13920 @c $ gnatpp @ovar{switches} @var{filename}
13921 @c Expanding @ovar macro inline (explanation in macro def comments)
13922 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
13923 @end smallexample
13924
13925 @noindent
13926 where
13927 @itemize @bullet
13928 @item
13929 @var{switches} is an optional sequence of switches defining such properties as
13930 the formatting rules, the source search path, and the destination for the
13931 output source file
13932
13933 @item
13934 @var{filename} is the name (including the extension) of the source file to
13935 reformat; ``wildcards'' or several file names on the same gnatpp command are
13936 allowed. The file name may contain path information; it does not have to
13937 follow the GNAT file naming rules
13938
13939 @item
13940 @samp{@var{gcc_switches}} is a list of switches for
13941 @command{gcc}. They will be passed on to all compiler invocations made by
13942 @command{gnatelim} to generate the ASIS trees. Here you can provide
13943 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13944 use the @option{-gnatec} switch to set the configuration file,
13945 use the @option{-gnat05} switch if sources should be compiled in
13946 Ada 2005 mode etc.
13947 @end itemize
13948
13949 @node Switches for gnatpp
13950 @section Switches for @command{gnatpp}
13951
13952 @noindent
13953 The following subsections describe the various switches accepted by
13954 @command{gnatpp}, organized by category.
13955
13956 @ifclear vms
13957 You specify a switch by supplying a name and generally also a value.
13958 In many cases the values for a switch with a given name are incompatible with
13959 each other
13960 (for example the switch that controls the casing of a reserved word may have
13961 exactly one value: upper case, lower case, or
13962 mixed case) and thus exactly one such switch can be in effect for an
13963 invocation of @command{gnatpp}.
13964 If more than one is supplied, the last one is used.
13965 However, some values for the same switch are mutually compatible.
13966 You may supply several such switches to @command{gnatpp}, but then
13967 each must be specified in full, with both the name and the value.
13968 Abbreviated forms (the name appearing once, followed by each value) are
13969 not permitted.
13970 For example, to set
13971 the alignment of the assignment delimiter both in declarations and in
13972 assignment statements, you must write @option{-A2A3}
13973 (or @option{-A2 -A3}), but not @option{-A23}.
13974 @end ifclear
13975
13976 @ifset vms
13977 In many cases the set of options for a given qualifier are incompatible with
13978 each other (for example the qualifier that controls the casing of a reserved
13979 word may have exactly one option, which specifies either upper case, lower
13980 case, or mixed case), and thus exactly one such option can be in effect for
13981 an invocation of @command{gnatpp}.
13982 If more than one is supplied, the last one is used.
13983 However, some qualifiers have options that are mutually compatible,
13984 and then you may then supply several such options when invoking
13985 @command{gnatpp}.
13986 @end ifset
13987
13988 In most cases, it is obvious whether or not the
13989 ^values for a switch with a given name^options for a given qualifier^
13990 are compatible with each other.
13991 When the semantics might not be evident, the summaries below explicitly
13992 indicate the effect.
13993
13994 @menu
13995 * Alignment Control::
13996 * Casing Control::
13997 * Construct Layout Control::
13998 * General Text Layout Control::
13999 * Other Formatting Options::
14000 * Setting the Source Search Path::
14001 * Output File Control::
14002 * Other gnatpp Switches::
14003 @end menu
14004
14005 @node Alignment Control
14006 @subsection Alignment Control
14007 @cindex Alignment control in @command{gnatpp}
14008
14009 @noindent
14010 Programs can be easier to read if certain constructs are vertically aligned.
14011 By default all alignments are set ON.
14012 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
14013 OFF, and then use one or more of the other
14014 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
14015 to activate alignment for specific constructs.
14016
14017 @table @option
14018 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14019
14020 @ifset vms
14021 @item /ALIGN=ON
14022 Set all alignments to ON
14023 @end ifset
14024
14025 @item ^-A0^/ALIGN=OFF^
14026 Set all alignments to OFF
14027
14028 @item ^-A1^/ALIGN=COLONS^
14029 Align @code{:} in declarations
14030
14031 @item ^-A2^/ALIGN=DECLARATIONS^
14032 Align @code{:=} in initializations in declarations
14033
14034 @item ^-A3^/ALIGN=STATEMENTS^
14035 Align @code{:=} in assignment statements
14036
14037 @item ^-A4^/ALIGN=ARROWS^
14038 Align @code{=>} in associations
14039
14040 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
14041 Align @code{at} keywords in the component clauses in record
14042 representation clauses
14043 @end table
14044
14045 @noindent
14046 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
14047 is allowed.
14048
14049 @node Casing Control
14050 @subsection Casing Control
14051 @cindex Casing control in @command{gnatpp}
14052
14053 @noindent
14054 @command{gnatpp} allows you to specify the casing for reserved words,
14055 pragma names, attribute designators and identifiers.
14056 For identifiers you may define a
14057 general rule for name casing but also override this rule
14058 via a set of dictionary files.
14059
14060 Three types of casing are supported: lower case, upper case, and mixed case.
14061 Lower and upper case are self-explanatory (but since some letters in
14062 Latin1 and other GNAT-supported character sets
14063 exist only in lower-case form, an upper case conversion will have no
14064 effect on them.)
14065 ``Mixed case'' means that the first letter, and also each letter immediately
14066 following an underscore, are converted to their uppercase forms;
14067 all the other letters are converted to their lowercase forms.
14068
14069 @table @option
14070 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14071 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14072 Attribute designators are lower case
14073
14074 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14075 Attribute designators are upper case
14076
14077 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14078 Attribute designators are mixed case (this is the default)
14079
14080 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14081 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14082 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14083 lower case (this is the default)
14084
14085 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14086 Keywords are upper case
14087
14088 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14089 @item ^-nD^/NAME_CASING=AS_DECLARED^
14090 Name casing for defining occurrences are as they appear in the source file
14091 (this is the default)
14092
14093 @item ^-nU^/NAME_CASING=UPPER_CASE^
14094 Names are in upper case
14095
14096 @item ^-nL^/NAME_CASING=LOWER_CASE^
14097 Names are in lower case
14098
14099 @item ^-nM^/NAME_CASING=MIXED_CASE^
14100 Names are in mixed case
14101
14102 @cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
14103 @item ^-neD^/ENUM_CASING=AS_DECLARED^
14104 Enumeration literal casing for defining occurrences are as they appear in the
14105 source file. Overrides ^-n^/NAME_CASING^ casing setting.
14106
14107 @item ^-neU^/ENUM_CASING=UPPER_CASE^
14108 Enumeration literals are in upper case. Overrides ^-n^/NAME_CASING^ casing
14109 setting.
14110
14111 @item ^-neL^/ENUM_CASING=LOWER_CASE^
14112 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
14113 setting.
14114
14115 @item ^-neM^/ENUM_CASING=MIXED_CASE^
14116 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
14117 setting.
14118
14119 @cindex @option{^-nt@var{x}^/TYPE_CASING^} (@command{gnatpp})
14120 @item ^-neD^/TYPE_CASING=AS_DECLARED^
14121 Names introduced by type and subtype declarations are always
14122 cased as they appear in the declaration in the source file.
14123 Overrides ^-n^/NAME_CASING^ casing setting.
14124
14125 @item ^-ntU^/TYPE_CASING=UPPER_CASE^
14126 Names introduced by type and subtype declarations are always in
14127 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
14128
14129 @item ^-ntL^/TYPE_CASING=LOWER_CASE^
14130 Names introduced by type and subtype declarations are always in
14131 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
14132
14133 @item ^-ntM^/TYPE_CASING=MIXED_CASE^
14134 Names introduced by type and subtype declarations are always in
14135 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
14136
14137 @item ^-nnU^/NUMBER_CASING=UPPER_CASE^
14138 Names introduced by number declarations are always in
14139 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
14140
14141 @item ^-nnL^/NUMBER_CASING=LOWER_CASE^
14142 Names introduced by number declarations are always in
14143 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
14144
14145 @item ^-nnM^/NUMBER_CASING=MIXED_CASE^
14146 Names introduced by number declarations are always in
14147 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
14148
14149 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14150 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14151 Pragma names are lower case
14152
14153 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14154 Pragma names are upper case
14155
14156 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14157 Pragma names are mixed case (this is the default)
14158
14159 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14160 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14161 Use @var{file} as a @emph{dictionary file} that defines
14162 the casing for a set of specified names,
14163 thereby overriding the effect on these names by
14164 any explicit or implicit
14165 ^-n^/NAME_CASING^ switch.
14166 To supply more than one dictionary file,
14167 use ^several @option{-D} switches^a list of files as options^.
14168
14169 @noindent
14170 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14171 to define the casing for the Ada predefined names and
14172 the names declared in the GNAT libraries.
14173
14174 @item ^-D-^/SPECIFIC_CASING^
14175 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14176 Do not use the default dictionary file;
14177 instead, use the casing
14178 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14179 dictionary file(s)
14180 @end table
14181
14182 @noindent
14183 The structure of a dictionary file, and details on the conventions
14184 used in the default dictionary file, are defined in @ref{Name Casing}.
14185
14186 The @option{^-D-^/SPECIFIC_CASING^} and
14187 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14188 compatible.
14189
14190 @node Construct Layout Control
14191 @subsection Construct Layout Control
14192 @cindex Layout control in @command{gnatpp}
14193
14194 @noindent
14195 This group of @command{gnatpp} switches controls the layout of comments and
14196 complex syntactic constructs. See @ref{Formatting Comments} for details
14197 on their effect.
14198
14199 @table @option
14200 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14201 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14202 All the comments remain unchanged
14203
14204 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14205 GNAT-style comment line indentation (this is the default).
14206
14207 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
14208 Reference-manual comment line indentation.
14209
14210 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14211 GNAT-style comment beginning
14212
14213 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14214 Reformat comment blocks
14215
14216 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
14217 Keep unchanged special form comments
14218
14219 @item --comments-only
14220 @cindex @option{--comments-only} @command{gnatpp}
14221 Format just the comments.
14222
14223 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14224 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14225 GNAT-style layout (this is the default)
14226
14227 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14228 Compact layout
14229
14230 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14231 Uncompact layout
14232
14233 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
14234 @item ^-N^/NOTABS^
14235 All the VT characters are removed from the comment text. All the HT characters
14236 are expanded with the sequences of space characters to get to the next tab
14237 stops.
14238
14239 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
14240 @item ^--no-separate-is^/NO_SEPARATE_IS^
14241 Do not place the keyword @code{is} on a separate line in a subprogram body in
14242 case if the spec occupies more than one line.
14243
14244 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
14245 @item ^--separate-label^/SEPARATE_LABEL^
14246 Place statement label(s) on a separate line, with the following statement
14247 on the next line.
14248
14249 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
14250 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
14251 Place the keyword @code{loop} in FOR and WHILE loop statements and the
14252 keyword @code{then} in IF statements on a separate line.
14253
14254 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
14255 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
14256 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
14257 keyword @code{then} in IF statements on a separate line. This option is
14258 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
14259
14260 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
14261 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
14262 Start each USE clause in a context clause from a separate line.
14263
14264 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
14265 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
14266 Use a separate line for a loop or block statement name, but do not use an extra
14267 indentation level for the statement itself.
14268
14269 @end table
14270
14271 @ifclear vms
14272 @noindent
14273 The @option{-c1} and @option{-c2} switches are incompatible.
14274 The @option{-c3} and @option{-c4} switches are compatible with each other and
14275 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
14276 the other comment formatting switches.
14277
14278 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14279 @end ifclear
14280
14281 @ifset vms
14282 @noindent
14283 For the @option{/COMMENTS_LAYOUT} qualifier:
14284 @itemize @bullet
14285 @item
14286 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14287 @item
14288 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14289 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14290 @end itemize
14291
14292 @noindent
14293 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14294 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14295 @end ifset
14296
14297 @node General Text Layout Control
14298 @subsection General Text Layout Control
14299
14300 @noindent
14301 These switches allow control over line length and indentation.
14302
14303 @table @option
14304 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
14305 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14306 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
14307
14308 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
14309 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14310 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
14311
14312 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
14313 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14314 Indentation level for continuation lines (relative to the line being
14315 continued), @var{nnn} from 1@dots{}9.
14316 The default
14317 value is one less than the (normal) indentation level, unless the
14318 indentation is set to 1 (in which case the default value for continuation
14319 line indentation is also 1)
14320 @end table
14321
14322 @node Other Formatting Options
14323 @subsection Other Formatting Options
14324
14325 @noindent
14326 These switches control the inclusion of missing end/exit labels, and
14327 the indentation level in @b{case} statements.
14328
14329 @table @option
14330 @item ^-e^/NO_MISSED_LABELS^
14331 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14332 Do not insert missing end/exit labels. An end label is the name of
14333 a construct that may optionally be repeated at the end of the
14334 construct's declaration;
14335 e.g., the names of packages, subprograms, and tasks.
14336 An exit label is the name of a loop that may appear as target
14337 of an exit statement within the loop.
14338 By default, @command{gnatpp} inserts these end/exit labels when
14339 they are absent from the original source. This option suppresses such
14340 insertion, so that the formatted source reflects the original.
14341
14342 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14343 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14344 Insert a Form Feed character after a pragma Page.
14345
14346 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
14347 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14348 Do not use an additional indentation level for @b{case} alternatives
14349 and variants if there are @var{nnn} or more (the default
14350 value is 10).
14351 If @var{nnn} is 0, an additional indentation level is
14352 used for @b{case} alternatives and variants regardless of their number.
14353
14354 @item ^--call_threshold=@var{nnn}^/MAX_ACT=@var{nnn}^
14355 @cindex @option{^--call_threshold^/MAX_ACT^} (@command{gnatpp})
14356 If the number of parameter associations is greater than @var{nnn} and if at
14357 least one association uses named notation, start each association from
14358 a new line. If @var{nnn} is 0, no check for the number of associations
14359 is made, this is the default.
14360
14361 @item ^--par_threshold=@var{nnn}^/MAX_PAR=@var{nnn}^
14362 @cindex @option{^--par_threshold^/MAX_PAR^} (@command{gnatpp})
14363 If the number of parameter specifications is greater than @var{nnn}
14364 (or equal to @var{nnn} in case of a function), start each specification from
14365 a new line. The default for @var{nnn} is 3.
14366 @end table
14367
14368 @node Setting the Source Search Path
14369 @subsection Setting the Source Search Path
14370
14371 @noindent
14372 To define the search path for the input source file, @command{gnatpp}
14373 uses the same switches as the GNAT compiler, with the same effects.
14374
14375 @table @option
14376 @item ^-I^/SEARCH=^@var{dir}
14377 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
14378 The same as the corresponding gcc switch
14379
14380 @item ^-I-^/NOCURRENT_DIRECTORY^
14381 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
14382 The same as the corresponding gcc switch
14383
14384 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14385 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
14386 The same as the corresponding gcc switch
14387
14388 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14389 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
14390 The same as the corresponding gcc switch
14391
14392 @end table
14393
14394 @node Output File Control
14395 @subsection Output File Control
14396
14397 @noindent
14398 By default the output is sent to the file whose name is obtained by appending
14399 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
14400 (if the file with this name already exists, it is unconditionally overwritten).
14401 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14402 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14403 as output file.
14404 The output may be redirected by the following switches:
14405
14406 @table @option
14407 @item ^-pipe^/STANDARD_OUTPUT^
14408 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
14409 Send the output to @code{Standard_Output}
14410
14411 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14412 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14413 Write the output into @var{output_file}.
14414 If @var{output_file} already exists, @command{gnatpp} terminates without
14415 reading or processing the input file.
14416
14417 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14418 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
14419 Write the output into @var{output_file}, overwriting the existing file
14420 (if one is present).
14421
14422 @item ^-r^/REPLACE^
14423 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
14424 Replace the input source file with the reformatted output, and copy the
14425 original input source into the file whose name is obtained by appending the
14426 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14427 If a file with this name already exists, @command{gnatpp} terminates without
14428 reading or processing the input file.
14429
14430 @item ^-rf^/OVERRIDING_REPLACE^
14431 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14432 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14433 already exists, it is overwritten.
14434
14435 @item ^-rnb^/REPLACE_NO_BACKUP^
14436 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
14437 Replace the input source file with the reformatted output without
14438 creating any backup copy of the input source.
14439
14440 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
14441 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
14442 Specifies the format of the reformatted output file. The @var{xxx}
14443 ^string specified with the switch^option^ may be either
14444 @itemize @bullet
14445 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
14446 @item ``@option{^crlf^CRLF^}''
14447 the same as @option{^crlf^CRLF^}
14448 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
14449 @item ``@option{^lf^LF^}''
14450 the same as @option{^unix^UNIX^}
14451 @end itemize
14452
14453 @item ^-W^/RESULT_ENCODING=^@var{e}
14454 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
14455 Specify the wide character encoding method used to write the code in the
14456 result file
14457 @var{e} is one of the following:
14458
14459 @itemize @bullet
14460
14461 @item ^h^HEX^
14462 Hex encoding
14463
14464 @item ^u^UPPER^
14465 Upper half encoding
14466
14467 @item ^s^SHIFT_JIS^
14468 Shift/JIS encoding
14469
14470 @item ^e^EUC^
14471 EUC encoding
14472
14473 @item ^8^UTF8^
14474 UTF-8 encoding
14475
14476 @item ^b^BRACKETS^
14477 Brackets encoding (default value)
14478 @end itemize
14479
14480 @end table
14481
14482 @noindent
14483 Options @option{^-pipe^/STANDARD_OUTPUT^},
14484 @option{^-o^/OUTPUT^} and
14485 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14486 contains only one file to reformat.
14487 Option
14488 @option{^--eol^/END_OF_LINE^}
14489 and
14490 @option{^-W^/RESULT_ENCODING^}
14491 cannot be used together
14492 with @option{^-pipe^/STANDARD_OUTPUT^} option.
14493
14494 @node Other gnatpp Switches
14495 @subsection Other @code{gnatpp} Switches
14496
14497 @noindent
14498 The additional @command{gnatpp} switches are defined in this subsection.
14499
14500 @table @option
14501 @item --version
14502 @cindex @option{--version} @command{gnatpp}
14503 Display Copyright and version, then exit disregarding all other options.
14504
14505 @item --help
14506 @cindex @option{--help} @command{gnatpp}
14507 Display usage, then exit disregarding all other options.
14508
14509 @item --pp-off=@var{xxx}
14510 @cindex @option{--pp-off} @command{gnatpp}
14511 Use @code{--xxx} as the command to turn off pretty printing, instead
14512 of the default @code{--!pp off}.
14513
14514 @item --pp-on=@var{xxx}
14515 @cindex @option{--pp-on} @command{gnatpp}
14516 Use @code{--xxx} as the command to turn pretty printing back on, instead
14517 of the default @code{--!pp on}.
14518
14519 @item --pp-old
14520 @cindex @option{--pp-old} @command{gnatpp}
14521 Use the old formatting algorithms.
14522
14523 @item ^-files @var{filename}^/FILES=@var{filename}^
14524 @cindex @option{^-files^/FILES^} (@code{gnatpp})
14525 Take the argument source files from the specified file. This file should be an
14526 ordinary text file containing file names separated by spaces or
14527 line breaks. You can use this switch more than once in the same call to
14528 @command{gnatpp}. You also can combine this switch with an explicit list of
14529 files.
14530
14531 @item ^-v^/VERBOSE^
14532 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
14533 Verbose mode;
14534 @command{gnatpp} generates version information and then
14535 a trace of the actions it takes to produce or obtain the ASIS tree.
14536
14537 @item ^-w^/WARNINGS^
14538 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
14539 Warning mode;
14540 @command{gnatpp} generates a warning whenever it cannot provide
14541 a required layout in the result source.
14542 @end table
14543
14544 @node Formatting Rules
14545 @section Formatting Rules
14546
14547 @noindent
14548 The following subsections show how @command{gnatpp} treats ``white space'',
14549 comments, program layout, and name casing.
14550 They provide the detailed descriptions of the switches shown above.
14551
14552 @menu
14553 * Disabling Pretty Printing::
14554 * White Space and Empty Lines::
14555 * Formatting Comments::
14556 * Construct Layout::
14557 * Name Casing::
14558 @end menu
14559
14560 @node Disabling Pretty Printing
14561 @subsection Disabling Pretty Printing
14562
14563 @noindent
14564 Pretty printing is highly heuristic in nature, and sometimes doesn't
14565 do exactly what you want. If you wish to format a certain region of
14566 code by hand, you can turn off pretty printing in that region by
14567 surrounding it with special comments that start with @code{--!pp off}
14568 and @code{--!pp on}. The text in that region will then be reproduced
14569 verbatim in the output with no formatting.
14570
14571 To disable pretty printing for the whole file, put @code{--!pp off} at
14572 the top, with no following @code{--!pp on}.
14573
14574 The comments must appear on a line by themselves, with nothing
14575 preceding except spaces. The initial text of the comment must be
14576 exactly @code{--!pp off} or @code{--!pp on} (case sensitive), but may
14577 be followed by arbitrary additional text. For example:
14578
14579 @smallexample @c ada
14580 @cartouche
14581 package Interrupts is
14582 --!pp off -- turn off pretty printing so "Interrupt_Kind" lines up
14583 type Interrupt_Kind is
14584 (Asynchronous_Interrupt_Kind,
14585 Synchronous_Interrupt_Kind,
14586 Green_Interrupt_Kind);
14587 --!pp on -- reenable pretty printing
14588
14589 ...
14590 @end cartouche
14591 @end smallexample
14592
14593 You can specify different comment strings using the gnatpp
14594 @code{--pp-off} and @code{--pp-on} switches. For example, if you say
14595 @code{gnatpp --pp-off=' pp-' *.ad?} then gnatpp will recognize
14596 comments of the form @code{-- pp-} instead of @code{--!pp off} for
14597 disabling pretty printing. Note that the leading @code{--} of the
14598 comment is not included in the argument to these switches.
14599
14600 @node White Space and Empty Lines
14601 @subsection White Space and Empty Lines
14602
14603 @noindent
14604 @command{gnatpp} does not have an option to control space characters.
14605 It will add or remove spaces according to the style illustrated by the
14606 examples in the @cite{Ada Reference Manual}.
14607
14608 The only format effectors
14609 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
14610 that will appear in the output file are platform-specific line breaks,
14611 and also format effectors within (but not at the end of) comments.
14612 In particular, each horizontal tab character that is not inside
14613 a comment will be treated as a space and thus will appear in the
14614 output file as zero or more spaces depending on
14615 the reformatting of the line in which it appears.
14616 The only exception is a Form Feed character, which is inserted after a
14617 pragma @code{Page} when @option{-ff} is set.
14618
14619 The output file will contain no lines with trailing ``white space'' (spaces,
14620 format effectors).
14621
14622 Empty lines in the original source are preserved
14623 only if they separate declarations or statements.
14624 In such contexts, a
14625 sequence of two or more empty lines is replaced by exactly one empty line.
14626 Note that a blank line will be removed if it separates two ``comment blocks''
14627 (a comment block is a sequence of whole-line comments).
14628 In order to preserve a visual separation between comment blocks, use an
14629 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
14630 Likewise, if for some reason you wish to have a sequence of empty lines,
14631 use a sequence of empty comments instead.
14632
14633 @node Formatting Comments
14634 @subsection Formatting Comments
14635
14636 @noindent
14637 Comments in Ada code are of two kinds:
14638 @itemize @bullet
14639 @item
14640 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14641 ``white space'') on a line
14642
14643 @item
14644 an @emph{end-of-line comment}, which follows some other Ada lexical element
14645 on the same line.
14646 @end itemize
14647
14648 @noindent
14649 The indentation of a whole-line comment is that of either
14650 the preceding or following line in
14651 the formatted source, depending on switch settings as will be described below.
14652
14653 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
14654 between the end of the preceding Ada lexical element and the beginning
14655 of the comment as appear in the original source,
14656 unless either the comment has to be split to
14657 satisfy the line length limitation, or else the next line contains a
14658 whole line comment that is considered a continuation of this end-of-line
14659 comment (because it starts at the same position).
14660 In the latter two
14661 cases, the start of the end-of-line comment is moved right to the nearest
14662 multiple of the indentation level.
14663 This may result in a ``line overflow'' (the right-shifted comment extending
14664 beyond the maximum line length), in which case the comment is split as
14665 described below.
14666
14667 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
14668 (GNAT-style comment line indentation)
14669 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
14670 (reference-manual comment line indentation).
14671 With reference-manual style, a whole-line comment is indented as if it
14672 were a declaration or statement at the same place
14673 (i.e., according to the indentation of the preceding line(s)).
14674 With GNAT style, a whole-line comment that is immediately followed by an
14675 @b{if} or @b{case} statement alternative, a record variant, or the reserved
14676 word @b{begin}, is indented based on the construct that follows it.
14677
14678 For example:
14679 @smallexample @c ada
14680 @cartouche
14681 if A then
14682 null;
14683 -- some comment
14684 else
14685 null;
14686 end if;
14687 @end cartouche
14688 @end smallexample
14689
14690 @noindent
14691 Reference-manual indentation produces:
14692
14693 @smallexample @c ada
14694 @cartouche
14695 if A then
14696 null;
14697 -- some comment
14698 else
14699 null;
14700 end if;
14701 @end cartouche
14702 @end smallexample
14703
14704 @noindent
14705 while GNAT-style indentation produces:
14706
14707 @smallexample @c ada
14708 @cartouche
14709 if A then
14710 null;
14711 -- some comment
14712 else
14713 null;
14714 end if;
14715 @end cartouche
14716 @end smallexample
14717
14718 @noindent
14719 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
14720 (GNAT style comment beginning) has the following
14721 effect:
14722
14723 @itemize @bullet
14724 @item
14725 For each whole-line comment that does not end with two hyphens,
14726 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
14727 to ensure that there are at least two spaces between these hyphens and the
14728 first non-blank character of the comment.
14729 @end itemize
14730
14731 @noindent
14732 For an end-of-line comment, if in the original source the next line is a
14733 whole-line comment that starts at the same position
14734 as the end-of-line comment,
14735 then the whole-line comment (and all whole-line comments
14736 that follow it and that start at the same position)
14737 will start at this position in the output file.
14738
14739 @noindent
14740 That is, if in the original source we have:
14741
14742 @smallexample @c ada
14743 @cartouche
14744 begin
14745 A := B + C; -- B must be in the range Low1..High1
14746 -- C must be in the range Low2..High2
14747 --B+C will be in the range Low1+Low2..High1+High2
14748 X := X + 1;
14749 @end cartouche
14750 @end smallexample
14751
14752 @noindent
14753 Then in the formatted source we get
14754
14755 @smallexample @c ada
14756 @cartouche
14757 begin
14758 A := B + C; -- B must be in the range Low1..High1
14759 -- C must be in the range Low2..High2
14760 -- B+C will be in the range Low1+Low2..High1+High2
14761 X := X + 1;
14762 @end cartouche
14763 @end smallexample
14764
14765 @noindent
14766 A comment that exceeds the line length limit will be split.
14767 Unless switch
14768 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
14769 the line belongs to a reformattable block, splitting the line generates a
14770 @command{gnatpp} warning.
14771 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
14772 comments may be reformatted in typical
14773 word processor style (that is, moving words between lines and putting as
14774 many words in a line as possible).
14775
14776 @noindent
14777 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
14778 that has a special format (that is, a character that is neither a letter nor digit
14779 not white space nor line break immediately following the leading @code{--} of
14780 the comment) should be without any change moved from the argument source
14781 into reformatted source. This switch allows to preserve comments that are used
14782 as a special marks in the code (e.g.@: SPARK annotation).
14783
14784 @noindent
14785 The @option{--comments-only} switch specifies that only the comments
14786 are formatted; the rest of the program text is left alone. The
14787 comments are formatted according to the -c3 and -c4 switches; other
14788 formatting switches are ignored. For example, @option{--comments-only
14789 -c4} means to fill comment paragraphs, and do nothing else. Likewise,
14790 @option{--comments-only -c3} ensures comments start with at least two
14791 spaces after @code{--}, and @option{--comments-only -c3 -c4} does
14792 both. If @option{--comments-only} is given without @option{-c3} or
14793 @option{-c4}, then gnatpp doesn't format anything.
14794
14795 @node Construct Layout
14796 @subsection Construct Layout
14797
14798 @noindent
14799 In several cases the suggested layout in the Ada Reference Manual includes
14800 an extra level of indentation that many programmers prefer to avoid. The
14801 affected cases include:
14802
14803 @itemize @bullet
14804
14805 @item Record type declaration (RM 3.8)
14806
14807 @item Record representation clause (RM 13.5.1)
14808
14809 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
14810
14811 @item Block statement in case if a block has a statement identifier (RM 5.6)
14812 @end itemize
14813
14814 @noindent
14815 In compact mode (when GNAT style layout or compact layout is set),
14816 the pretty printer uses one level of indentation instead
14817 of two. This is achieved in the record definition and record representation
14818 clause cases by putting the @code{record} keyword on the same line as the
14819 start of the declaration or representation clause, and in the block and loop
14820 case by putting the block or loop header on the same line as the statement
14821 identifier.
14822
14823 @noindent
14824 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
14825 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
14826 layout on the one hand, and uncompact layout
14827 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
14828 can be illustrated by the following examples:
14829
14830 @iftex
14831 @cartouche
14832 @multitable @columnfractions .5 .5
14833 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
14834
14835 @item
14836 @smallexample @c ada
14837 type q is record
14838 a : integer;
14839 b : integer;
14840 end record;
14841 @end smallexample
14842 @tab
14843 @smallexample @c ada
14844 type q is
14845 record
14846 a : integer;
14847 b : integer;
14848 end record;
14849 @end smallexample
14850
14851 @item
14852 @smallexample @c ada
14853 for q use record
14854 a at 0 range 0 .. 31;
14855 b at 4 range 0 .. 31;
14856 end record;
14857 @end smallexample
14858 @tab
14859 @smallexample @c ada
14860 for q use
14861 record
14862 a at 0 range 0 .. 31;
14863 b at 4 range 0 .. 31;
14864 end record;
14865 @end smallexample
14866
14867 @item
14868 @smallexample @c ada
14869 Block : declare
14870 A : Integer := 3;
14871 begin
14872 Proc (A, A);
14873 end Block;
14874 @end smallexample
14875 @tab
14876 @smallexample @c ada
14877 Block :
14878 declare
14879 A : Integer := 3;
14880 begin
14881 Proc (A, A);
14882 end Block;
14883 @end smallexample
14884
14885 @item
14886 @smallexample @c ada
14887 Clear : for J in 1 .. 10 loop
14888 A (J) := 0;
14889 end loop Clear;
14890 @end smallexample
14891 @tab
14892 @smallexample @c ada
14893 Clear :
14894 for J in 1 .. 10 loop
14895 A (J) := 0;
14896 end loop Clear;
14897 @end smallexample
14898 @end multitable
14899 @end cartouche
14900 @end iftex
14901
14902 @ifnottex
14903 @smallexample
14904 @cartouche
14905 GNAT style, compact layout Uncompact layout
14906
14907 type q is record type q is
14908 a : integer; record
14909 b : integer; a : integer;
14910 end record; b : integer;
14911 end record;
14912
14913 for q use record for q use
14914 a at 0 range 0 .. 31; record
14915 b at 4 range 0 .. 31; a at 0 range 0 .. 31;
14916 end record; b at 4 range 0 .. 31;
14917 end record;
14918
14919 Block : declare Block :
14920 A : Integer := 3; declare
14921 begin A : Integer := 3;
14922 Proc (A, A); begin
14923 end Block; Proc (A, A);
14924 end Block;
14925
14926 Clear : for J in 1 .. 10 loop Clear :
14927 A (J) := 0; for J in 1 .. 10 loop
14928 end loop Clear; A (J) := 0;
14929 end loop Clear;
14930 @end cartouche
14931 @end smallexample
14932 @end ifnottex
14933
14934 @noindent
14935 A further difference between GNAT style layout and compact layout is that
14936 GNAT style layout inserts empty lines as separation for
14937 compound statements, return statements and bodies.
14938
14939 Note that the layout specified by
14940 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
14941 for named block and loop statements overrides the layout defined by these
14942 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
14943 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
14944 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
14945
14946 @node Name Casing
14947 @subsection Name Casing
14948
14949 @noindent
14950 @command{gnatpp} always converts the usage occurrence of a (simple) name to
14951 the same casing as the corresponding defining identifier.
14952
14953 You control the casing for defining occurrences via the
14954 @option{^-n^/NAME_CASING^} switch.
14955 @ifclear vms
14956 With @option{-nD} (``as declared'', which is the default),
14957 @end ifclear
14958 @ifset vms
14959 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
14960 @end ifset
14961 defining occurrences appear exactly as in the source file
14962 where they are declared.
14963 The other ^values for this switch^options for this qualifier^ ---
14964 @option{^-nU^UPPER_CASE^},
14965 @option{^-nL^LOWER_CASE^},
14966 @option{^-nM^MIXED_CASE^} ---
14967 result in
14968 ^upper, lower, or mixed case, respectively^the corresponding casing^.
14969 If @command{gnatpp} changes the casing of a defining
14970 occurrence, it analogously changes the casing of all the
14971 usage occurrences of this name.
14972
14973 If the defining occurrence of a name is not in the source compilation unit
14974 currently being processed by @command{gnatpp}, the casing of each reference to
14975 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
14976 switch (subject to the dictionary file mechanism described below).
14977 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
14978 had affected the
14979 casing for the defining occurrence of the name.
14980
14981 Some names may need to be spelled with casing conventions that are not
14982 covered by the upper-, lower-, and mixed-case transformations.
14983 You can arrange correct casing by placing such names in a
14984 @emph{dictionary file},
14985 and then supplying a @option{^-D^/DICTIONARY^} switch.
14986 The casing of names from dictionary files overrides
14987 any @option{^-n^/NAME_CASING^} switch.
14988
14989 To handle the casing of Ada predefined names and the names from GNAT libraries,
14990 @command{gnatpp} assumes a default dictionary file.
14991 The name of each predefined entity is spelled with the same casing as is used
14992 for the entity in the @cite{Ada Reference Manual}.
14993 The name of each entity in the GNAT libraries is spelled with the same casing
14994 as is used in the declaration of that entity.
14995
14996 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
14997 default dictionary file.
14998 Instead, the casing for predefined and GNAT-defined names will be established
14999 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
15000 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
15001 will appear as just shown,
15002 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
15003 To ensure that even such names are rendered in uppercase,
15004 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
15005 (or else, less conveniently, place these names in upper case in a dictionary
15006 file).
15007
15008 A dictionary file is
15009 a plain text file; each line in this file can be either a blank line
15010 (containing only space characters and ASCII.HT characters), an Ada comment
15011 line, or the specification of exactly one @emph{casing schema}.
15012
15013 A casing schema is a string that has the following syntax:
15014
15015 @smallexample
15016 @cartouche
15017 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
15018
15019 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15020 @end cartouche
15021 @end smallexample
15022
15023 @noindent
15024 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15025 @var{identifier} lexical element and the @var{letter_or_digit} category.)
15026
15027 The casing schema string can be followed by white space and/or an Ada-style
15028 comment; any amount of white space is allowed before the string.
15029
15030 If a dictionary file is passed as
15031 @ifclear vms
15032 the value of a @option{-D@var{file}} switch
15033 @end ifclear
15034 @ifset vms
15035 an option to the @option{/DICTIONARY} qualifier
15036 @end ifset
15037 then for every
15038 simple name and every identifier, @command{gnatpp} checks if the dictionary
15039 defines the casing for the name or for some of its parts (the term ``subword''
15040 is used below to denote the part of a name which is delimited by ``_'' or by
15041 the beginning or end of the word and which does not contain any ``_'' inside):
15042
15043 @itemize @bullet
15044 @item
15045 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15046 the casing defined by the dictionary; no subwords are checked for this word
15047
15048 @item
15049 for every subword @command{gnatpp} checks if the dictionary contains the
15050 corresponding string of the form @code{*@var{simple_identifier}*},
15051 and if it does, the casing of this @var{simple_identifier} is used
15052 for this subword
15053
15054 @item
15055 if the whole name does not contain any ``_'' inside, and if for this name
15056 the dictionary contains two entries - one of the form @var{identifier},
15057 and another - of the form *@var{simple_identifier}*, then the first one
15058 is applied to define the casing of this name
15059
15060 @item
15061 if more than one dictionary file is passed as @command{gnatpp} switches, each
15062 dictionary adds new casing exceptions and overrides all the existing casing
15063 exceptions set by the previous dictionaries
15064
15065 @item
15066 when @command{gnatpp} checks if the word or subword is in the dictionary,
15067 this check is not case sensitive
15068 @end itemize
15069
15070 @noindent
15071 For example, suppose we have the following source to reformat:
15072
15073 @smallexample @c ada
15074 @cartouche
15075 procedure test is
15076 name1 : integer := 1;
15077 name4_name3_name2 : integer := 2;
15078 name2_name3_name4 : Boolean;
15079 name1_var : Float;
15080 begin
15081 name2_name3_name4 := name4_name3_name2 > name1;
15082 end;
15083 @end cartouche
15084 @end smallexample
15085
15086 @noindent
15087 And suppose we have two dictionaries:
15088
15089 @smallexample
15090 @cartouche
15091 @i{dict1:}
15092 NAME1
15093 *NaMe3*
15094 *Name1*
15095 @end cartouche
15096
15097 @cartouche
15098 @i{dict2:}
15099 *NAME3*
15100 @end cartouche
15101 @end smallexample
15102
15103 @noindent
15104 If @command{gnatpp} is called with the following switches:
15105
15106 @smallexample
15107 @ifclear vms
15108 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15109 @end ifclear
15110 @ifset vms
15111 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15112 @end ifset
15113 @end smallexample
15114
15115 @noindent
15116 then we will get the following name casing in the @command{gnatpp} output:
15117
15118 @smallexample @c ada
15119 @cartouche
15120 procedure Test is
15121 NAME1 : Integer := 1;
15122 Name4_NAME3_Name2 : Integer := 2;
15123 Name2_NAME3_Name4 : Boolean;
15124 Name1_Var : Float;
15125 begin
15126 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
15127 end Test;
15128 @end cartouche
15129 @end smallexample
15130
15131 @ifclear vms
15132 @c *********************************
15133 @node The Ada-to-XML converter gnat2xml
15134 @chapter The Ada-to-XML converter @command{gnat2xml}
15135 @findex gnat2xml
15136 @cindex XML generation
15137
15138 @noindent
15139 The @command{gnat2xml} tool is an ASIS-based utility that converts
15140 Ada source code into XML.
15141
15142 @menu
15143 * Switches for gnat2xml::
15144 * Driving gnat2xml with gnatmake or gprbuild::
15145 * Other Programs::
15146 * Structure of the XML::
15147 @end menu
15148
15149 @node Switches for gnat2xml
15150 @section Switches for @command{gnat2xml}
15151
15152 @noindent
15153 @command{gnat2xml} takes Ada source code as input, and produces XML
15154 that conforms to the schema.
15155
15156 Usage:
15157
15158 @smallexample
15159 gnat2xml [options] files
15160 @end smallexample
15161
15162 ``files'' are the Ada source file names.
15163
15164 @noindent
15165 Options:
15166 @smallexample
15167 -h
15168 --help -- generate usage information and quit, ignoring all other options
15169
15170 -mdir -- generate one .xml file for each Ada source file, in directory
15171 @file{dir}. (Default is to generate the XML to standard output.)
15172
15173 -q -- debugging version, with interspersed source, and a more
15174 compact representation of "sloc". This version does not conform
15175 to any schema.
15176
15177 -I <include-dir>
15178 directories to search for dependencies
15179 You can also set the ADA_INCLUDE_PATH environment variable for this.
15180
15181 -v -- verbose (print out the command line options, and the names of
15182 output files as they are generated).
15183
15184 -t -- do not delete tree files when done (they are deleted by default).
15185
15186 -cargs ... -- options to pass to gcc
15187 @end smallexample
15188
15189 @noindent
15190 You can generate the ``tree files'' ahead of time using the -gnatct switch:
15191
15192 @smallexample
15193 gnatmake -gnat2012 -gnatct *.ad[sb]
15194 @end smallexample
15195
15196 @noindent
15197 If tree files do not exist, @command{gnat2xml} will create them by running gcc.
15198 See the ASIS documentation for more information on tree files.
15199
15200 Example:
15201
15202 @smallexample
15203 mkdir xml-files
15204 gnat2xml -v -mxml-files *.ad[sb] -cargs -gnat2012
15205 @end smallexample
15206
15207 @noindent
15208 The above will create *.xml files in the @file{xml-files} subdirectory.
15209 For example, if there is an Ada package Mumble.Dumble, whose spec and
15210 body source code lives in mumble-dumble.ads and mumble-dumble.adb,
15211 the above will produce xml-files/mumble-dumble.ads.xml and
15212 xml-files/mumble-dumble.adb.xml.
15213
15214 @node Driving gnat2xml with gnatmake or gprbuild
15215 @section Driving @command{gnat2xml} with @command{gnatmake} or @command{gprbuild}
15216
15217 @noindent
15218 You can use gnatmake or gprbuild to drive @command{gnat2xml} to get
15219 incremental updates of the XML files on a per-source-file basis. For
15220 example, if you already have a bunch of XML files, and then you change
15221 one source file, it will regenerate XML files only for that source
15222 file, and other source files that depend on it. Gnatmake and gprbuild
15223 take care of tracking inter-file dependencies. For example, if
15224 this.adb says @code{with That;}, then this.adb depends on that.ads.
15225
15226 To do this, you tell gnatmake/gprbuild to pretend that
15227 @command{gnat2xml} is the Ada compiler (instead of using gcc as the
15228 Ada compiler, as is normal).
15229
15230 To tell gnatmake to use @command{gnat2xml} instead of gcc as the
15231 ``compiler'', for example:
15232
15233 @smallexample
15234 gnatmake -gnatc *.adb --GCC="gnat2xml -t -mxml"
15235 @end smallexample
15236
15237 @noindent
15238 The @option{--GCC=} switch tells gnatmake that the ``compiler'' to run
15239 is @command{gnat2xml -t -mxml}. The @option{-t} switch means to keep the tree
15240 files, so they can be reused on the next run. (@command{gnat2xml}
15241 deletes them by default.) As usual, @option{-mxml} means to put the
15242 XML files in the @file{xml} subdirectory.
15243
15244 You must give the @option{-gnatc} switch to gnatmake, which means
15245 ``compile only; do not generate object code''. Otherwise, gnatmake will
15246 complain about missing object (*.o) files; @command{gnat2xml} of
15247 course does not generate *.o files.
15248
15249 Using gprbuild is similar: you tell it to use @command{gnat2xml}
15250 instead of gcc. First write a project file, such as my_project.gpr:
15251
15252 @smallexample @c projectfile
15253 project My_Project is
15254
15255 package Compiler is
15256 for Driver ("ada") use "gnat2xml";
15257 -- Use gnat2xml instead of the usual gcc.
15258
15259 for Default_Switches ("ada") use ("-t", "-mxml");
15260 -- Same switches as in the gnatmake case.
15261 end Compiler;
15262
15263 end My_Project;
15264 @end smallexample
15265
15266 @noindent
15267 Then:
15268
15269 @smallexample @c projectfile
15270 gprbuild --no-object-check -P my_project.gpr
15271 @end smallexample
15272
15273 @noindent
15274 The @option{--no-object-check} switch serves the same purpose as
15275 @option{-gnatc} in the gnatmake case --- it tells gprbuild not to
15276 expect that the ``compiler'' (really @command{gnat2xml}) will produce
15277 *.o files.
15278
15279 See the gprbuild documentation for information on many other things
15280 you can put in the project file, such as telling it where to find
15281 the source files.
15282
15283 @node Other Programs
15284 @section Other Programs
15285
15286 @noindent
15287 The distribution includes two other programs that are related to
15288 @command{gnat2xml}:
15289
15290 @command{gnat2xsd} is the schema generator, which generates the schema
15291 to standard output, based on the structure of Ada as encoded by
15292 ASIS. You don't need to run @command{gnat2xsd} in order to use
15293 @command{gnat2xml}. To generate the schema, type:
15294
15295 @smallexample
15296 gnat2xsd > ada-schema.xsd
15297 @end smallexample
15298
15299 @noindent
15300 @command{gnat2xml} generates XML files that will validate against
15301 @file{ada-schema.xsd}.
15302
15303 @command{xml2gnat} is a back-translator that translates the XML back
15304 into Ada source code. The Ada generated by @command{xml2gnat} has
15305 identical semantics to the original Ada code passed to
15306 @command{gnat2xml}. It is not textually identical, however --- for
15307 example, no attempt is made to preserve the original indentation.
15308
15309 @node Structure of the XML
15310 @section Structure of the XML
15311
15312 @noindent
15313 The primary documentation for the structure of the XML generated by
15314 @command{gnat2xml} is the schema (see @command{gnat2xsd} above). The
15315 following documentation gives additional details needed to understand
15316 the schema and therefore the XML.
15317
15318 The elements listed under Defining Occurrences, Usage Occurrences, and
15319 Other Elements represent the syntactic structure of the Ada program.
15320 Element names are given in lower case, with the corresponding element
15321 type Capitalized_Like_This. The element and element type names are
15322 derived directly from the ASIS enumeration type Flat_Element_Kinds,
15323 declared in Asis.Extensions.Flat_Kinds, with the leading ``An_'' or ``A_''
15324 removed. For example, the ASIS enumeration literal
15325 An_Assignment_Statement corresponds to the XML element
15326 assignment_statement of XML type Assignment_Statement.
15327
15328 To understand the details of the schema and the corresponding XML, it is
15329 necessary to understand the ASIS standard, as well as the GNAT-specific
15330 extension to ASIS.
15331
15332 A defining occurrence is an identifier (or character literal or operator
15333 symbol) declared by a declaration. A usage occurrence is an identifier
15334 (or ...) that references such a declared entity. For example, in:
15335
15336 @smallexample
15337 type T is range 1..10;
15338 X, Y : constant T := 1;
15339 @end smallexample
15340
15341 @noindent
15342 The first ``T'' is the defining occurrence of a type. The ``X'' is the
15343 defining occurrence of a constant, as is the ``Y'', and the second ``T'' is
15344 a usage occurrence referring to the defining occurrence of T.
15345
15346 Each element has a 'sloc' (source location), and subelements for each
15347 syntactic subtree, reflecting the Ada grammar as implemented by ASIS.
15348 The types of subelements are as defined in the ASIS standard. For
15349 example, for the right-hand side of an assignment_statement we have
15350 the following comment in asis-statements.ads:
15351
15352 @smallexample
15353 ------------------------------------------------------------------------------
15354 -- 18.3 function Assignment_Expression
15355 ------------------------------------------------------------------------------
15356
15357 function Assignment_Expression
15358 (Statement : Asis.Statement)
15359 return Asis.Expression;
15360
15361 ------------------------------------------------------------------------------
15362 ...
15363 -- Returns the expression from the right hand side of the assignment.
15364 ...
15365 -- Returns Element_Kinds:
15366 -- An_Expression
15367 @end smallexample
15368
15369 @noindent
15370 The corresponding sub-element of type Assignment_Statement is:
15371
15372 @smallexample
15373 <xsd:element name="assignment_expression_q" type="Expression_Class"/>
15374 @end smallexample
15375
15376 @noindent
15377 where Expression_Class is defined by an xsd:choice of all the
15378 various kinds of expression.
15379
15380 The 'sloc' of each element indicates the starting and ending line and
15381 column numbers. Column numbers are character counts; that is, a tab
15382 counts as 1, not as however many spaces it might expand to.
15383
15384 Subelements of type Element have names ending in ``_q'' (for ASIS
15385 ``Query''), and those of type Element_List end in ``_ql'' (``Query returning
15386 List'').
15387
15388 Some subelements are ``Boolean''. For example, Private_Type_Definition
15389 has has_abstract_q and has_limited_q, to indicate whether those
15390 keywords are present, as in @code{type T is abstract limited
15391 private;}. False is represented by a Nil_Element. True is represented
15392 by an element type specific to that query (for example, Abstract and
15393 Limited).
15394
15395 The root of the tree is a Compilation_Unit, with attributes:
15396
15397 @itemize @bullet
15398 @item
15399 unit_kind, unit_class, and unit_origin. These are strings that match the
15400 enumeration literals of types Unit_Kinds, Unit_Classes, and Unit_Origins
15401 in package Asis.
15402
15403 @item
15404 unit_full_name is the full expanded name of the unit, starting from a
15405 root library unit. So for @code{package P.Q.R is ...},
15406 @code{unit_full_name="P.Q.R"}. Same for @code{separate (P.Q) package R is ...}.
15407
15408 @item
15409 def_name is the same as unit_full_name for library units; for subunits,
15410 it is just the simple name.
15411
15412 @item
15413 source_file is the name of the Ada source file. For example, for
15414 the spec of @code{P.Q.R}, @code{source_file="p-q-r.ads"}. This allows one to
15415 interpret the source locations --- the ``sloc'' of all elements
15416 within this Compilation_Unit refers to line and column numbers
15417 within the named file.
15418 @end itemize
15419
15420 @noindent
15421 Defining occurrences have these attributes:
15422
15423 @itemize @bullet
15424 @item
15425 def_name is the simple name of the declared entity, as written in the Ada
15426 source code.
15427
15428 @item
15429 def is a unique URI of the form:
15430
15431 ada://kind/fully/qualified/name
15432
15433 where:
15434
15435 kind indicates the kind of Ada entity being declared (see below), and
15436
15437 fully/qualified/name, is the fully qualified name of the Ada
15438 entity, with each of ``fully'', ``qualified'', and ``name'' being
15439 mangled for uniqueness. We do not document the mangling
15440 algorithm, which is subject to change; we just guarantee that the
15441 names are unique in the face of overloading.
15442
15443 @item
15444 type is the type of the declared object, or @code{null} for
15445 declarations of things other than objects.
15446 @end itemize
15447
15448 @noindent
15449 Usage occurrences have these attributes:
15450
15451 @itemize @bullet
15452 @item
15453 ref_name is the same as the def_name of the corresponding defining
15454 occurrence. This attribute is not of much use, because of
15455 overloading; use ref for lookups, instead.
15456
15457 @item
15458 ref is the same as the def of the corresponding defining
15459 occurrence.
15460 @end itemize
15461
15462 @noindent
15463 In summary, @code{def_name} and @code{ref_name} are as in the source
15464 code of the declaration, possibly overloaded, whereas @code{def} and
15465 @code{ref} are unique-ified.
15466
15467 Literal elements have this attribute:
15468
15469 @itemize @bullet
15470 @item
15471 lit_val is the value of the literal as written in the source text,
15472 appropriately escaped (e.g. @code{"} ---> @code{&quot;}). This applies
15473 only to numeric and string literals. Enumeration literals in Ada are
15474 not really "literals" in the usual sense; they are usage occurrences,
15475 and have ref_name and ref as described above. Note also that string
15476 literals used as operator symbols are treated as defining or usage
15477 occurrences, not as literals.
15478 @end itemize
15479
15480 @noindent
15481 Elements that can syntactically represent names and expressions (which
15482 includes usage occurrences, plus function calls and so forth) have this
15483 attribute:
15484
15485 @itemize @bullet
15486 @item
15487 type. If the element represents an expression or the name of an object,
15488 'type' is the 'def' for the defining occurrence of the type of that
15489 expression or name. Names of other kinds of entities, such as package
15490 names and type names, do not have a type in Ada; these have type="null"
15491 in the XML.
15492 @end itemize
15493
15494 @noindent
15495 Pragma elements have this attribute:
15496
15497 @itemize @bullet
15498 @item
15499 pragma_name is the name of the pragma. For language-defined pragmas, the
15500 pragma name is redundant with the element kind (for example, an
15501 assert_pragma element necessarily has pragma_name="Assert"). However, all
15502 implementation-defined pragmas are lumped together in ASIS as a single
15503 element kind (for example, the GNAT-specific pragma Unreferenced is
15504 represented by an implementation_defined_pragma element with
15505 pragma_name="Unreferenced").
15506 @end itemize
15507
15508 @noindent
15509 Defining occurrences of formal parameters and generic formal objects have this
15510 attribute:
15511
15512 @itemize @bullet
15513 @item
15514 mode indicates that the parameter is of mode 'in', 'in out', or 'out'.
15515 @end itemize
15516
15517 @noindent
15518 All elements other than Not_An_Element have this attribute:
15519
15520 @itemize @bullet
15521 @item
15522 checks is a comma-separated list of run-time checks that are needed
15523 for that element. The possible checks are: do_accessibility_check,
15524 do_discriminant_check,do_division_check,do_length_check,
15525 do_overflow_check,do_range_check,do_storage_check,do_tag_check.
15526 @end itemize
15527
15528 @noindent
15529 The "kind" part of the "def" and "ref" attributes is taken from the ASIS
15530 enumeration type Flat_Declaration_Kinds, declared in
15531 Asis.Extensions.Flat_Kinds, with the leading "An_" or "A_" removed, and
15532 any trailing "_Declaration" or "_Specification" removed. Thus, the
15533 possible kinds are as follows:
15534
15535 @smallexample
15536 ordinary_type
15537 task_type
15538 protected_type
15539 incomplete_type
15540 tagged_incomplete_type
15541 private_type
15542 private_extension
15543 subtype
15544 variable
15545 constant
15546 deferred_constant
15547 single_task
15548 single_protected
15549 integer_number
15550 real_number
15551 enumeration_literal
15552 discriminant
15553 component
15554 loop_parameter
15555 generalized_iterator
15556 element_iterator
15557 procedure
15558 function
15559 parameter
15560 procedure_body
15561 function_body
15562 return_variable
15563 return_constant
15564 null_procedure
15565 expression_function
15566 package
15567 package_body
15568 object_renaming
15569 exception_renaming
15570 package_renaming
15571 procedure_renaming
15572 function_renaming
15573 generic_package_renaming
15574 generic_procedure_renaming
15575 generic_function_renaming
15576 task_body
15577 protected_body
15578 entry
15579 entry_body
15580 entry_index
15581 procedure_body_stub
15582 function_body_stub
15583 package_body_stub
15584 task_body_stub
15585 protected_body_stub
15586 exception
15587 choice_parameter
15588 generic_procedure
15589 generic_function
15590 generic_package
15591 package_instantiation
15592 procedure_instantiation
15593 function_instantiation
15594 formal_object
15595 formal_type
15596 formal_incomplete_type
15597 formal_procedure
15598 formal_function
15599 formal_package
15600 formal_package_declaration_with_box
15601 @end smallexample
15602 @end ifclear
15603
15604 @c *********************************
15605 @node The GNAT Metrics Tool gnatmetric
15606 @chapter The GNAT Metrics Tool @command{gnatmetric}
15607 @findex gnatmetric
15608 @cindex Metric tool
15609
15610 @noindent
15611 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
15612 for computing various program metrics.
15613 It takes an Ada source file as input and generates a file containing the
15614 metrics data as output. Various switches control which
15615 metrics are computed and output.
15616
15617 @menu
15618 * Switches for gnatmetric::
15619 @end menu
15620
15621 @command{gnatmetric} generates and uses the ASIS
15622 tree for the input source and thus requires the input to be syntactically and
15623 semantically legal.
15624 If this condition is not met, @command{gnatmetric} will generate
15625 an error message; no metric information for this file will be
15626 computed and reported.
15627
15628 If the compilation unit contained in the input source depends semantically
15629 upon units in files located outside the current directory, you have to provide
15630 the source search path when invoking @command{gnatmetric}.
15631 If it depends semantically upon units that are contained
15632 in files with names that do not follow the GNAT file naming rules, you have to
15633 provide the configuration file describing the corresponding naming scheme (see
15634 the description of the @command{gnatmetric} switches below.)
15635 Alternatively, you may use a project file and invoke @command{gnatmetric}
15636 through the @command{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15637
15638 The @command{gnatmetric} command has the form
15639
15640 @smallexample
15641 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15642 @c Expanding @ovar macro inline (explanation in macro def comments)
15643 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15644 @end smallexample
15645
15646 @noindent
15647 where
15648 @itemize @bullet
15649 @item
15650 @var{switches} specify the metrics to compute and define the destination for
15651 the output
15652
15653 @item
15654 Each @var{filename} is the name (including the extension) of a source
15655 file to process. ``Wildcards'' are allowed, and
15656 the file name may contain path information.
15657 If no @var{filename} is supplied, then the @var{switches} list must contain
15658 at least one
15659 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15660 Including both a @option{-files} switch and one or more
15661 @var{filename} arguments is permitted.
15662
15663 @item
15664 @samp{@var{gcc_switches}} is a list of switches for
15665 @command{gcc}. They will be passed on to all compiler invocations made by
15666 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15667 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
15668 and use the @option{-gnatec} switch to set the configuration file,
15669 use the @option{-gnat05} switch if sources should be compiled in
15670 Ada 2005 mode etc.
15671 @end itemize
15672
15673 @node Switches for gnatmetric
15674 @section Switches for @command{gnatmetric}
15675
15676 @noindent
15677 The following subsections describe the various switches accepted by
15678 @command{gnatmetric}, organized by category.
15679
15680 @menu
15681 * Output Files Control::
15682 * Disable Metrics For Local Units::
15683 * Specifying a set of metrics to compute::
15684 * Other gnatmetric Switches::
15685 * Generate project-wide metrics::
15686 @end menu
15687
15688 @node Output Files Control
15689 @subsection Output File Control
15690 @cindex Output file control in @command{gnatmetric}
15691
15692 @noindent
15693 @command{gnatmetric} has two output formats. It can generate a
15694 textual (human-readable) form, and also XML. By default only textual
15695 output is generated.
15696
15697 When generating the output in textual form, @command{gnatmetric} creates
15698 for each Ada source file a corresponding text file
15699 containing the computed metrics, except for the case when the set of metrics
15700 specified by gnatmetric parameters consists only of metrics that are computed
15701 for the whole set of analyzed sources, but not for each Ada source.
15702 By default, this file is placed in the same directory as where the source
15703 file is located, and its name is obtained
15704 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
15705 input file.
15706
15707 All the output information generated in XML format is placed in a single
15708 file. By default this file is placed in the current directory and has the
15709 name ^@file{metrix.xml}^@file{METRIX$XML}^.
15710
15711 Some of the computed metrics are summed over the units passed to
15712 @command{gnatmetric}; for example, the total number of lines of code.
15713 By default this information is sent to @file{stdout}, but a file
15714 can be specified with the @option{-og} switch.
15715
15716 The following switches control the @command{gnatmetric} output:
15717
15718 @table @option
15719 @cindex @option{^-x^/XML^} (@command{gnatmetric})
15720 @item ^-x^/XML^
15721 Generate the XML output
15722
15723 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
15724 @item ^-xs^/XSD^
15725 Generate the XML output and the XML schema file that describes the structure
15726 of the XML metric report, this schema is assigned to the XML file. The schema
15727 file has the same name as the XML output file with @file{.xml} suffix replaced
15728 with @file{.xsd}
15729
15730 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
15731 @item ^-nt^/NO_TEXT^
15732 Do not generate the output in text form (implies @option{^-x^/XML^})
15733
15734 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
15735 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
15736 Put text files with detailed metrics into @var{output_dir}
15737
15738 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
15739 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
15740 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
15741 in the name of the output file.
15742
15743 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
15744 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
15745 Put global metrics into @var{file_name}
15746
15747 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
15748 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
15749 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
15750
15751 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
15752 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
15753 Use ``short'' source file names in the output. (The @command{gnatmetric}
15754 output includes the name(s) of the Ada source file(s) from which the metrics
15755 are computed. By default each name includes the absolute path. The
15756 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
15757 to exclude all directory information from the file names that are output.)
15758
15759 @end table
15760
15761 @node Disable Metrics For Local Units
15762 @subsection Disable Metrics For Local Units
15763 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15764
15765 @noindent
15766 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15767 one compilation
15768 unit per one source file. It computes line metrics for the whole source
15769 file, and it also computes syntax
15770 and complexity metrics for the file's outermost unit.
15771
15772 By default, @command{gnatmetric} will also compute all metrics for certain
15773 kinds of locally declared program units:
15774
15775 @itemize @bullet
15776 @item
15777 subprogram (and generic subprogram) bodies;
15778
15779 @item
15780 package (and generic package) specs and bodies;
15781
15782 @item
15783 task object and type specifications and bodies;
15784
15785 @item
15786 protected object and type specifications and bodies.
15787 @end itemize
15788
15789 @noindent
15790 These kinds of entities will be referred to as
15791 @emph{eligible local program units}, or simply @emph{eligible local units},
15792 @cindex Eligible local unit (for @command{gnatmetric})
15793 in the discussion below.
15794
15795 Note that a subprogram declaration, generic instantiation,
15796 or renaming declaration only receives metrics
15797 computation when it appear as the outermost entity
15798 in a source file.
15799
15800 Suppression of metrics computation for eligible local units can be
15801 obtained via the following switch:
15802
15803 @table @option
15804 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
15805 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
15806 Do not compute detailed metrics for eligible local program units
15807
15808 @end table
15809
15810 @node Specifying a set of metrics to compute
15811 @subsection Specifying a set of metrics to compute
15812
15813 @noindent
15814 By default all the metrics are computed and reported. The switches
15815 described in this subsection allow you to control, on an individual
15816 basis, whether metrics are computed and
15817 reported. If at least one positive metric
15818 switch is specified (that is, a switch that defines that a given
15819 metric or set of metrics is to be computed), then only
15820 explicitly specified metrics are reported.
15821
15822 @menu
15823 * Line Metrics Control::
15824 * Syntax Metrics Control::
15825 * Complexity Metrics Control::
15826 * Coupling Metrics Control::
15827 @end menu
15828
15829 @node Line Metrics Control
15830 @subsubsection Line Metrics Control
15831 @cindex Line metrics control in @command{gnatmetric}
15832
15833 @noindent
15834 For any (legal) source file, and for each of its
15835 eligible local program units, @command{gnatmetric} computes the following
15836 metrics:
15837
15838 @itemize @bullet
15839 @item
15840 the total number of lines;
15841
15842 @item
15843 the total number of code lines (i.e., non-blank lines that are not comments)
15844
15845 @item
15846 the number of comment lines
15847
15848 @item
15849 the number of code lines containing end-of-line comments;
15850
15851 @item
15852 the comment percentage: the ratio between the number of lines that contain
15853 comments and the number of all non-blank lines, expressed as a percentage;
15854
15855 @item
15856 the number of empty lines and lines containing only space characters and/or
15857 format effectors (blank lines)
15858
15859 @item
15860 the average number of code lines in subprogram bodies, task bodies, entry
15861 bodies and statement sequences in package bodies (this metric is only computed
15862 across the whole set of the analyzed units)
15863
15864 @end itemize
15865
15866 @noindent
15867 @command{gnatmetric} sums the values of the line metrics for all the
15868 files being processed and then generates the cumulative results. The tool
15869 also computes for all the files being processed the average number of code
15870 lines in bodies.
15871
15872 You can use the following switches to select the specific line metrics
15873 to be computed and reported.
15874
15875 @table @option
15876 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
15877
15878 @ifclear vms
15879 @cindex @option{--no-lines@var{x}}
15880 @end ifclear
15881
15882 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
15883 Report all the line metrics
15884
15885 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
15886 Do not report any of line metrics
15887
15888 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
15889 Report the number of all lines
15890
15891 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
15892 Do not report the number of all lines
15893
15894 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
15895 Report the number of code lines
15896
15897 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
15898 Do not report the number of code lines
15899
15900 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
15901 Report the number of comment lines
15902
15903 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
15904 Do not report the number of comment lines
15905
15906 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
15907 Report the number of code lines containing
15908 end-of-line comments
15909
15910 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
15911 Do not report the number of code lines containing
15912 end-of-line comments
15913
15914 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
15915 Report the comment percentage in the program text
15916
15917 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
15918 Do not report the comment percentage in the program text
15919
15920 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
15921 Report the number of blank lines
15922
15923 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
15924 Do not report the number of blank lines
15925
15926 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
15927 Report the average number of code lines in subprogram bodies, task bodies,
15928 entry bodies and statement sequences in package bodies. The metric is computed
15929 and reported for the whole set of processed Ada sources only.
15930
15931 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
15932 Do not report the average number of code lines in subprogram bodies,
15933 task bodies, entry bodies and statement sequences in package bodies.
15934
15935 @end table
15936
15937 @node Syntax Metrics Control
15938 @subsubsection Syntax Metrics Control
15939 @cindex Syntax metrics control in @command{gnatmetric}
15940
15941 @noindent
15942 @command{gnatmetric} computes various syntactic metrics for the
15943 outermost unit and for each eligible local unit:
15944
15945 @table @emph
15946 @item LSLOC (``Logical Source Lines Of Code'')
15947 The total number of declarations and the total number of statements. Note
15948 that the definition of declarations is the one given in the reference
15949 manual:
15950
15951 @noindent
15952 ``Each of the following is defined to be a declaration: any basic_declaration;
15953 an enumeration_literal_specification; a discriminant_specification;
15954 a component_declaration; a loop_parameter_specification; a
15955 parameter_specification; a subprogram_body; an entry_declaration;
15956 an entry_index_specification; a choice_parameter_specification;
15957 a generic_formal_parameter_declaration.''
15958
15959 This means for example that each enumeration literal adds one to the count,
15960 as well as each subprogram parameter.
15961
15962 Thus the results from this metric will be significantly greater than might
15963 be expected from a naive view of counting semicolons.
15964
15965 @item Maximal static nesting level of inner program units
15966 According to
15967 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
15968 package, a task unit, a protected unit, a
15969 protected entry, a generic unit, or an explicitly declared subprogram other
15970 than an enumeration literal.''
15971
15972 @item Maximal nesting level of composite syntactic constructs
15973 This corresponds to the notion of the
15974 maximum nesting level in the GNAT built-in style checks
15975 (@pxref{Style Checking})
15976 @end table
15977
15978 @noindent
15979 For the outermost unit in the file, @command{gnatmetric} additionally computes
15980 the following metrics:
15981
15982 @table @emph
15983 @item Public subprograms
15984 This metric is computed for package specs. It is the
15985 number of subprograms and generic subprograms declared in the visible
15986 part (including the visible part of nested packages, protected objects, and
15987 protected types).
15988
15989 @item All subprograms
15990 This metric is computed for bodies and subunits. The
15991 metric is equal to a total number of subprogram bodies in the compilation
15992 unit.
15993 Neither generic instantiations nor renamings-as-a-body nor body stubs
15994 are counted. Any subprogram body is counted, independently of its nesting
15995 level and enclosing constructs. Generic bodies and bodies of protected
15996 subprograms are counted in the same way as ``usual'' subprogram bodies.
15997
15998 @item Public types
15999 This metric is computed for package specs and
16000 generic package declarations. It is the total number of types
16001 that can be referenced from outside this compilation unit, plus the
16002 number of types from all the visible parts of all the visible generic
16003 packages. Generic formal types are not counted. Only types, not subtypes,
16004 are included.
16005
16006 @noindent
16007 Along with the total number of public types, the following
16008 types are counted and reported separately:
16009
16010 @itemize @bullet
16011 @item
16012 Abstract types
16013
16014 @item
16015 Root tagged types (abstract, non-abstract, private, non-private). Type
16016 extensions are @emph{not} counted
16017
16018 @item
16019 Private types (including private extensions)
16020
16021 @item
16022 Task types
16023
16024 @item
16025 Protected types
16026
16027 @end itemize
16028
16029 @item All types
16030 This metric is computed for any compilation unit. It is equal to the total
16031 number of the declarations of different types given in the compilation unit.
16032 The private and the corresponding full type declaration are counted as one
16033 type declaration. Incomplete type declarations and generic formal types
16034 are not counted.
16035 No distinction is made among different kinds of types (abstract,
16036 private etc.); the total number of types is computed and reported.
16037
16038 @end table
16039
16040 @noindent
16041 By default, all the syntax metrics are computed and reported. You can use the
16042 following switches to select specific syntax metrics.
16043
16044 @table @option
16045
16046 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
16047
16048 @ifclear vms
16049 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
16050 @end ifclear
16051
16052 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
16053 Report all the syntax metrics
16054
16055 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
16056 Do not report any of syntax metrics
16057
16058 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
16059 Report the total number of declarations
16060
16061 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
16062 Do not report the total number of declarations
16063
16064 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
16065 Report the total number of statements
16066
16067 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
16068 Do not report the total number of statements
16069
16070 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
16071 Report the number of public subprograms in a compilation unit
16072
16073 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
16074 Do not report the number of public subprograms in a compilation unit
16075
16076 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
16077 Report the number of all the subprograms in a compilation unit
16078
16079 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
16080 Do not report the number of all the subprograms in a compilation unit
16081
16082 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
16083 Report the number of public types in a compilation unit
16084
16085 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
16086 Do not report the number of public types in a compilation unit
16087
16088 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
16089 Report the number of all the types in a compilation unit
16090
16091 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
16092 Do not report the number of all the types in a compilation unit
16093
16094 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
16095 Report the maximal program unit nesting level
16096
16097 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
16098 Do not report the maximal program unit nesting level
16099
16100 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
16101 Report the maximal construct nesting level
16102
16103 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
16104 Do not report the maximal construct nesting level
16105
16106 @end table
16107
16108 @node Complexity Metrics Control
16109 @subsubsection Complexity Metrics Control
16110 @cindex Complexity metrics control in @command{gnatmetric}
16111
16112 @noindent
16113 For a program unit that is an executable body (a subprogram body (including
16114 generic bodies), task body, entry body or a package body containing
16115 its own statement sequence) @command{gnatmetric} computes the following
16116 complexity metrics:
16117
16118 @itemize @bullet
16119 @item
16120 McCabe cyclomatic complexity;
16121
16122 @item
16123 McCabe essential complexity;
16124
16125 @item
16126 maximal loop nesting level;
16127
16128 @item
16129 extra exit points (for subprograms);
16130 @end itemize
16131
16132 @noindent
16133 The McCabe cyclomatic complexity metric is defined
16134 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
16135
16136 According to McCabe, both control statements and short-circuit control forms
16137 should be taken into account when computing cyclomatic complexity.
16138 For Ada 2012 we have also take into account conditional expressions
16139 and quantified expressions. For each body, we compute three metric values:
16140
16141 @itemize @bullet
16142 @item
16143 the complexity introduced by control
16144 statements only, without taking into account short-circuit forms,
16145
16146 @item
16147 the complexity introduced by short-circuit control forms only, and
16148
16149 @item
16150 the total
16151 cyclomatic complexity, which is the sum of these two values.
16152 @end itemize
16153
16154 @noindent
16155
16156 The cyclomatic complexity is also computed for Ada 2012 expression functions.
16157 An expression function cannot have statements as its components, so only one
16158 metric value is computed as a cyclomatic complexity of an expression function.
16159
16160 The origin of cyclomatic complexity metric is the need to estimate the number
16161 of independent paths in the control flow graph that in turn gives the number
16162 of tests needed to satisfy paths coverage testing completeness criterion.
16163 Considered from the testing point of view, a static Ada @code{loop} (that is,
16164 the @code{loop} statement having static subtype in loop parameter
16165 specification) does not add to cyclomatic complexity. By providing
16166 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
16167 may specify that such loops should not be counted when computing the
16168 cyclomatic complexity metric
16169
16170 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
16171 counted for the code that is reduced by excluding all the pure structural Ada
16172 control statements. An compound statement is considered as a non-structural
16173 if it contains a @code{raise} or @code{return} statement as it subcomponent,
16174 or if it contains a @code{goto} statement that transfers the control outside
16175 the operator. A selective accept statement with @code{terminate} alternative
16176 is considered as non-structural statement. When computing this metric,
16177 @code{exit} statements are treated in the same way as @code{goto}
16178 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
16179
16180 The Ada essential complexity metric defined here is intended to quantify
16181 the extent to which the software is unstructured. It is adapted from
16182 the McCabe essential complexity metric defined in
16183 @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more
16184 suitable for typical Ada usage. For example, short circuit forms
16185 are not penalized as unstructured in the Ada essential complexity metric.
16186
16187 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
16188 the code in the exception handlers and in all the nested program units. The
16189 code of assertions and predicates (that is, subprogram preconditions and
16190 postconditions, subtype predicates and type invariants) is also skipped.
16191
16192 By default, all the complexity metrics are computed and reported.
16193 For more fine-grained control you can use
16194 the following switches:
16195
16196 @table @option
16197 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
16198
16199 @ifclear vms
16200 @cindex @option{--no-complexity@var{x}}
16201 @end ifclear
16202
16203 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
16204 Report all the complexity metrics
16205
16206 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
16207 Do not report any of complexity metrics
16208
16209 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
16210 Report the McCabe Cyclomatic Complexity
16211
16212 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
16213 Do not report the McCabe Cyclomatic Complexity
16214
16215 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
16216 Report the Essential Complexity
16217
16218 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
16219 Do not report the Essential Complexity
16220
16221 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
16222 Report maximal loop nesting level
16223
16224 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
16225 Do not report maximal loop nesting level
16226
16227 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
16228 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
16229 task bodies, entry bodies and statement sequences in package bodies.
16230 The metric is computed and reported for whole set of processed Ada sources
16231 only.
16232
16233 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
16234 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
16235 bodies, task bodies, entry bodies and statement sequences in package bodies
16236
16237 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
16238 @item ^-ne^/NO_EXITS_AS_GOTOS^
16239 Do not consider @code{exit} statements as @code{goto}s when
16240 computing Essential Complexity
16241
16242 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
16243 @item ^--no-static-loop^/NO_STATIC_LOOP^
16244 Do not consider static loops when computing cyclomatic complexity
16245
16246 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
16247 Report the extra exit points for subprogram bodies. As an exit point, this
16248 metric counts @code{return} statements and raise statements in case when the
16249 raised exception is not handled in the same body. In case of a function this
16250 metric subtracts 1 from the number of exit points, because a function body
16251 must contain at least one @code{return} statement.
16252
16253 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
16254 Do not report the extra exit points for subprogram bodies
16255 @end table
16256
16257
16258 @node Coupling Metrics Control
16259 @subsubsection Coupling Metrics Control
16260 @cindex Coupling metrics control in @command{gnatmetric}
16261
16262 @noindent
16263 @cindex Coupling metrics (in in @command{gnatmetric})
16264 Coupling metrics measure the dependencies between a given entity and other
16265 entities the program consists of. The goal of these metrics is to estimate the
16266 stability of the whole program considered as the collection of entities
16267 (modules, classes etc.).
16268
16269 Gnatmetric computes the following coupling metrics:
16270
16271 @itemize @bullet
16272
16273 @item
16274 @emph{object-oriented coupling} - for classes in traditional object-oriented
16275 sense;
16276
16277 @item
16278 @emph{unit coupling} - for all the program units making up a program;
16279
16280 @item
16281 @emph{control coupling} - this metric counts dependencies between a unit and
16282 only those units that define subprograms;
16283 @end itemize
16284
16285 @noindent
16286 Two kinds of coupling metrics are computed:
16287
16288 @table @asis
16289 @item fan-out coupling (efferent coupling)
16290 @cindex fan-out coupling
16291 @cindex efferent coupling
16292 the number of entities the given entity depends upon. It
16293 estimates in what extent the given entity depends on the changes in
16294 ``external world''
16295
16296 @item fan-in coupling (afferent coupling)
16297 @cindex fan-in coupling
16298 @cindex afferent coupling
16299 the number of entities that depend on a given entity.
16300 It estimates in what extent the ``external world'' depends on the changes in a
16301 given entity
16302 @end table
16303
16304 @noindent
16305
16306 Object-oriented coupling metrics are metrics that measure the dependencies
16307 between a given class (or a group of classes) and the other classes in the
16308 program. In this subsection the term ``class'' is used in its traditional
16309 object-oriented programming sense (an instantiable module that contains data
16310 and/or method members). A @emph{category} (of classes) is a group of closely
16311 related classes that are reused and/or modified together.
16312
16313 A class @code{K}'s fan-out coupling is the number of classes
16314 that @code{K} depends upon.
16315 A category's fan-out coupling is the number of classes outside the
16316 category that the classes inside the category depend upon.
16317
16318 A class @code{K}'s fan-in coupling is the number of classes
16319 that depend upon @code{K}.
16320 A category's fan-in coupling is the number of classes outside the
16321 category that depend on classes belonging to the category.
16322
16323 Ada's implementation of the object-oriented paradigm does not use the
16324 traditional class notion, so the definition of the coupling
16325 metrics for Ada maps the class and class category notions
16326 onto Ada constructs.
16327
16328 For the coupling metrics, several kinds of modules -- a library package,
16329 a library generic package, and a library generic package instantiation --
16330 that define a tagged type or an interface type are
16331 considered to be a class. A category consists of a library package (or
16332 a library generic package) that defines a tagged or an interface type,
16333 together with all its descendant (generic) packages that define tagged
16334 or interface types. That is a
16335 category is an Ada hierarchy of library-level program units. So class coupling
16336 in case of Ada is called as tagged coupling, and category coupling - as
16337 hierarchy coupling.
16338
16339 For any package counted as a class, its body and subunits (if any) are
16340 considered together with its spec when counting the dependencies, and coupling
16341 metrics are reported for spec units only. For dependencies between classes,
16342 the Ada semantic dependencies are considered. For object-oriented coupling
16343 metrics, only dependencies on units that are considered as classes, are
16344 considered.
16345
16346 For unit and control coupling also not compilation units but program units are
16347 counted. That is, for a package, its spec, its body and its subunits (if any)
16348 are considered as making up one unit, and the dependencies that are counted
16349 are the dependencies of all these compilation units collected together as
16350 the dependencies as a (whole) unit. And metrics are reported for spec
16351 compilation units only (or for a subprogram body unit in case if there is no
16352 separate spec for the given subprogram).
16353
16354 For unit coupling, dependencies between all kinds of program units are
16355 considered. For control coupling, for each unit the dependencies of this unit
16356 upon units that define subprograms are counted, so control fan-out coupling
16357 is reported for all units, but control fan-in coupling - only for the units
16358 that define subprograms.
16359
16360 The following simple example illustrates the difference between unit coupling
16361 and control coupling metrics:
16362
16363 @smallexample @c ada
16364 package Lib_1 is
16365 function F_1 (I : Integer) return Integer;
16366 end Lib_1;
16367
16368 package Lib_2 is
16369 type T_2 is new Integer;
16370 end Lib_2;
16371
16372 package body Lib_1 is
16373 function F_1 (I : Integer) return Integer is
16374 begin
16375 return I + 1;
16376 end F_1;
16377 end Lib_1;
16378
16379 with Lib_2; use Lib_2;
16380 package Pack is
16381 Var : T_2;
16382 function Fun (I : Integer) return Integer;
16383 end Pack;
16384
16385 with Lib_1; use Lib_1;
16386 package body Pack is
16387 function Fun (I : Integer) return Integer is
16388 begin
16389 return F_1 (I);
16390 end Fun;
16391 end Pack;
16392 @end smallexample
16393
16394 @noindent
16395 if we apply @command{gnatmetric} with @code{--coupling-all} option to these
16396 units, the result will be:
16397
16398 @smallexample
16399 Coupling metrics:
16400 =================
16401 Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads)
16402 control fan-out coupling : 0
16403 control fan-in coupling : 1
16404 unit fan-out coupling : 0
16405 unit fan-in coupling : 1
16406
16407 Unit Pack (C:\customers\662\L406-007\pack.ads)
16408 control fan-out coupling : 1
16409 control fan-in coupling : 0
16410 unit fan-out coupling : 2
16411 unit fan-in coupling : 0
16412
16413 Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads)
16414 control fan-out coupling : 0
16415 unit fan-out coupling : 0
16416 unit fan-in coupling : 1
16417 @end smallexample
16418
16419 @noindent
16420 The result does not contain values for object-oriented
16421 coupling because none of the argument unit contains a tagged type and
16422 therefore none of these units can be treated as a class.
16423
16424 @code{Pack} (considered as a program unit, that is spec+body) depends on two
16425 units - @code{Lib_1} @code{and Lib_2}, therefore it has unit fan-out coupling
16426 equals to 2. And nothing depend on it, so its unit fan-in coupling is 0 as
16427 well as control fan-in coupling. Only one of the units @code{Pack} depends
16428 upon defines a subprogram, so its control fan-out coupling is 1.
16429
16430 @code{Lib_2} depends on nothing, so fan-out metrics for it are 0. It does
16431 not define a subprogram, so control fan-in metric cannot be applied to it,
16432 and there is one unit that depends on it (@code{Pack}), so it has
16433 unit fan-in coupling equals to 1.
16434
16435 @code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram.
16436 So it has control fan-in coupling equals to 1 (because there is a unit
16437 depending on it).
16438
16439 When computing coupling metrics, @command{gnatmetric} counts only
16440 dependencies between units that are arguments of the @command{gnatmetric}
16441 call. Coupling metrics are program-wide (or project-wide) metrics, so to
16442 get a valid result, you should call @command{gnatmetric} for
16443 the whole set of sources that make up your program. It can be done
16444 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
16445 option (see @ref{The GNAT Driver and Project Files} for details).
16446
16447 By default, all the coupling metrics are disabled. You can use the following
16448 switches to specify the coupling metrics to be computed and reported:
16449
16450 @table @option
16451
16452 @ifclear vms
16453 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
16454 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
16455 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
16456 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
16457 @end ifclear
16458
16459 @ifset vms
16460 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
16461 @end ifset
16462
16463 @item ^--coupling-all^/COUPLING_METRICS=ALL^
16464 Report all the coupling metrics
16465
16466 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
16467 Report tagged (class) fan-out coupling
16468
16469 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
16470 Report tagged (class) fan-in coupling
16471
16472 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
16473 Report hierarchy (category) fan-out coupling
16474
16475 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
16476 Report hierarchy (category) fan-in coupling
16477
16478 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
16479 Report unit fan-out coupling
16480
16481 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
16482 Report unit fan-in coupling
16483
16484 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
16485 Report control fan-out coupling
16486
16487 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
16488 Report control fan-in coupling
16489 @end table
16490
16491 @node Other gnatmetric Switches
16492 @subsection Other @code{gnatmetric} Switches
16493
16494 @noindent
16495 Additional @command{gnatmetric} switches are as follows:
16496
16497 @table @option
16498 @item --version
16499 @cindex @option{--version} @command{gnatmetric}
16500 Display Copyright and version, then exit disregarding all other options.
16501
16502 @item --help
16503 @cindex @option{--help} @command{gnatmetric}
16504 Display usage, then exit disregarding all other options.
16505
16506 @item ^-files @var{filename}^/FILES=@var{filename}^
16507 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
16508 Take the argument source files from the specified file. This file should be an
16509 ordinary text file containing file names separated by spaces or
16510 line breaks. You can use this switch more than once in the same call to
16511 @command{gnatmetric}. You also can combine this switch with
16512 an explicit list of files.
16513
16514 @item ^-v^/VERBOSE^
16515 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
16516 Verbose mode;
16517 @command{gnatmetric} generates version information and then
16518 a trace of sources being processed.
16519
16520 @item ^-q^/QUIET^
16521 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
16522 Quiet mode.
16523 @end table
16524
16525 @node Generate project-wide metrics
16526 @subsection Generate project-wide metrics
16527
16528 In order to compute metrics on all units of a given project, you can use
16529 the @command{gnat} driver along with the @option{-P} option:
16530 @smallexample
16531 gnat metric -Pproj
16532 @end smallexample
16533
16534 @noindent
16535 If the project @code{proj} depends upon other projects, you can compute
16536 the metrics on the project closure using the @option{-U} option:
16537 @smallexample
16538 gnat metric -Pproj -U
16539 @end smallexample
16540
16541 @noindent
16542 Finally, if not all the units are relevant to a particular main
16543 program in the project closure, you can generate metrics for the set
16544 of units needed to create a given main program (unit closure) using
16545 the @option{-U} option followed by the name of the main unit:
16546 @smallexample
16547 gnat metric -Pproj -U main
16548 @end smallexample
16549
16550
16551 @c ***********************************
16552 @node File Name Krunching with gnatkr
16553 @chapter File Name Krunching with @code{gnatkr}
16554 @findex gnatkr
16555
16556 @noindent
16557 This chapter discusses the method used by the compiler to shorten
16558 the default file names chosen for Ada units so that they do not
16559 exceed the maximum length permitted. It also describes the
16560 @code{gnatkr} utility that can be used to determine the result of
16561 applying this shortening.
16562 @menu
16563 * About gnatkr::
16564 * Using gnatkr::
16565 * Krunching Method::
16566 * Examples of gnatkr Usage::
16567 @end menu
16568
16569 @node About gnatkr
16570 @section About @code{gnatkr}
16571
16572 @noindent
16573 The default file naming rule in GNAT
16574 is that the file name must be derived from
16575 the unit name. The exact default rule is as follows:
16576 @itemize @bullet
16577 @item
16578 Take the unit name and replace all dots by hyphens.
16579 @item
16580 If such a replacement occurs in the
16581 second character position of a name, and the first character is
16582 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
16583 then replace the dot by the character
16584 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
16585 instead of a minus.
16586 @end itemize
16587 The reason for this exception is to avoid clashes
16588 with the standard names for children of System, Ada, Interfaces,
16589 and GNAT, which use the prefixes
16590 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
16591 respectively.
16592
16593 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
16594 switch of the compiler activates a ``krunching''
16595 circuit that limits file names to nn characters (where nn is a decimal
16596 integer). For example, using OpenVMS,
16597 where the maximum file name length is
16598 39, the value of nn is usually set to 39, but if you want to generate
16599 a set of files that would be usable if ported to a system with some
16600 different maximum file length, then a different value can be specified.
16601 The default value of 39 for OpenVMS need not be specified.
16602
16603 The @code{gnatkr} utility can be used to determine the krunched name for
16604 a given file, when krunched to a specified maximum length.
16605
16606 @node Using gnatkr
16607 @section Using @code{gnatkr}
16608
16609 @noindent
16610 The @code{gnatkr} command has the form
16611
16612 @ifclear vms
16613 @smallexample
16614 @c $ gnatkr @var{name} @ovar{length}
16615 @c Expanding @ovar macro inline (explanation in macro def comments)
16616 $ gnatkr @var{name} @r{[}@var{length}@r{]}
16617 @end smallexample
16618 @end ifclear
16619
16620 @ifset vms
16621 @smallexample
16622 $ gnatkr @var{name} /COUNT=nn
16623 @end smallexample
16624 @end ifset
16625
16626 @noindent
16627 @var{name} is the uncrunched file name, derived from the name of the unit
16628 in the standard manner described in the previous section (i.e., in particular
16629 all dots are replaced by hyphens). The file name may or may not have an
16630 extension (defined as a suffix of the form period followed by arbitrary
16631 characters other than period). If an extension is present then it will
16632 be preserved in the output. For example, when krunching @file{hellofile.ads}
16633 to eight characters, the result will be hellofil.ads.
16634
16635 Note: for compatibility with previous versions of @code{gnatkr} dots may
16636 appear in the name instead of hyphens, but the last dot will always be
16637 taken as the start of an extension. So if @code{gnatkr} is given an argument
16638 such as @file{Hello.World.adb} it will be treated exactly as if the first
16639 period had been a hyphen, and for example krunching to eight characters
16640 gives the result @file{hellworl.adb}.
16641
16642 Note that the result is always all lower case (except on OpenVMS where it is
16643 all upper case). Characters of the other case are folded as required.
16644
16645 @var{length} represents the length of the krunched name. The default
16646 when no argument is given is ^8^39^ characters. A length of zero stands for
16647 unlimited, in other words do not chop except for system files where the
16648 implied crunching length is always eight characters.
16649
16650 @noindent
16651 The output is the krunched name. The output has an extension only if the
16652 original argument was a file name with an extension.
16653
16654 @node Krunching Method
16655 @section Krunching Method
16656
16657 @noindent
16658 The initial file name is determined by the name of the unit that the file
16659 contains. The name is formed by taking the full expanded name of the
16660 unit and replacing the separating dots with hyphens and
16661 using ^lowercase^uppercase^
16662 for all letters, except that a hyphen in the second character position is
16663 replaced by a ^tilde^dollar sign^ if the first character is
16664 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
16665 The extension is @code{.ads} for a
16666 spec and @code{.adb} for a body.
16667 Krunching does not affect the extension, but the file name is shortened to
16668 the specified length by following these rules:
16669
16670 @itemize @bullet
16671 @item
16672 The name is divided into segments separated by hyphens, tildes or
16673 underscores and all hyphens, tildes, and underscores are
16674 eliminated. If this leaves the name short enough, we are done.
16675
16676 @item
16677 If the name is too long, the longest segment is located (left-most
16678 if there are two of equal length), and shortened by dropping
16679 its last character. This is repeated until the name is short enough.
16680
16681 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16682 to fit the name into 8 characters as required by some operating systems.
16683
16684 @smallexample
16685 our-strings-wide_fixed 22
16686 our strings wide fixed 19
16687 our string wide fixed 18
16688 our strin wide fixed 17
16689 our stri wide fixed 16
16690 our stri wide fixe 15
16691 our str wide fixe 14
16692 our str wid fixe 13
16693 our str wid fix 12
16694 ou str wid fix 11
16695 ou st wid fix 10
16696 ou st wi fix 9
16697 ou st wi fi 8
16698 Final file name: oustwifi.adb
16699 @end smallexample
16700
16701 @item
16702 The file names for all predefined units are always krunched to eight
16703 characters. The krunching of these predefined units uses the following
16704 special prefix replacements:
16705
16706 @table @file
16707 @item ada-
16708 replaced by @file{^a^A^-}
16709
16710 @item gnat-
16711 replaced by @file{^g^G^-}
16712
16713 @item interfaces-
16714 replaced by @file{^i^I^-}
16715
16716 @item system-
16717 replaced by @file{^s^S^-}
16718 @end table
16719
16720 These system files have a hyphen in the second character position. That
16721 is why normal user files replace such a character with a
16722 ^tilde^dollar sign^, to
16723 avoid confusion with system file names.
16724
16725 As an example of this special rule, consider
16726 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16727
16728 @smallexample
16729 ada-strings-wide_fixed 22
16730 a- strings wide fixed 18
16731 a- string wide fixed 17
16732 a- strin wide fixed 16
16733 a- stri wide fixed 15
16734 a- stri wide fixe 14
16735 a- str wide fixe 13
16736 a- str wid fixe 12
16737 a- str wid fix 11
16738 a- st wid fix 10
16739 a- st wi fix 9
16740 a- st wi fi 8
16741 Final file name: a-stwifi.adb
16742 @end smallexample
16743 @end itemize
16744
16745 Of course no file shortening algorithm can guarantee uniqueness over all
16746 possible unit names, and if file name krunching is used then it is your
16747 responsibility to ensure that no name clashes occur. The utility
16748 program @code{gnatkr} is supplied for conveniently determining the
16749 krunched name of a file.
16750
16751 @node Examples of gnatkr Usage
16752 @section Examples of @code{gnatkr} Usage
16753
16754 @smallexample
16755 @iftex
16756 @leftskip=0cm
16757 @end iftex
16758 @ifclear vms
16759 $ gnatkr very_long_unit_name.ads --> velounna.ads
16760 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16761 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16762 $ gnatkr grandparent-parent-child --> grparchi
16763 @end ifclear
16764 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16765 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16766 @end smallexample
16767
16768 @node Preprocessing with gnatprep
16769 @chapter Preprocessing with @code{gnatprep}
16770 @findex gnatprep
16771
16772 @noindent
16773 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
16774 preprocessing.
16775 Although designed for use with GNAT, @code{gnatprep} does not depend on any
16776 special GNAT features.
16777 For further discussion of conditional compilation in general, see
16778 @ref{Conditional Compilation}.
16779
16780 @menu
16781 * Preprocessing Symbols::
16782 * Using gnatprep::
16783 * Switches for gnatprep::
16784 * Form of Definitions File::
16785 * Form of Input Text for gnatprep::
16786 @end menu
16787
16788 @node Preprocessing Symbols
16789 @section Preprocessing Symbols
16790
16791 @noindent
16792 Preprocessing symbols are defined in definition files and referred to in
16793 sources to be preprocessed. A Preprocessing symbol is an identifier, following
16794 normal Ada (case-insensitive) rules for its syntax, with the restriction that
16795 all characters need to be in the ASCII set (no accented letters).
16796
16797 @node Using gnatprep
16798 @section Using @code{gnatprep}
16799
16800 @noindent
16801 To call @code{gnatprep} use
16802
16803 @smallexample
16804 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
16805 @c Expanding @ovar macro inline (explanation in macro def comments)
16806 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
16807 @end smallexample
16808
16809 @noindent
16810 where
16811 @table @var
16812 @item switches
16813 is an optional sequence of switches as described in the next section.
16814
16815 @item infile
16816 is the full name of the input file, which is an Ada source
16817 file containing preprocessor directives.
16818
16819 @item outfile
16820 is the full name of the output file, which is an Ada source
16821 in standard Ada form. When used with GNAT, this file name will
16822 normally have an ads or adb suffix.
16823
16824 @item deffile
16825 is the full name of a text file containing definitions of
16826 preprocessing symbols to be referenced by the preprocessor. This argument is
16827 optional, and can be replaced by the use of the @option{-D} switch.
16828
16829 @end table
16830
16831 @node Switches for gnatprep
16832 @section Switches for @code{gnatprep}
16833
16834 @table @option
16835 @c !sort!
16836
16837 @item ^-b^/BLANK_LINES^
16838 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16839 Causes both preprocessor lines and the lines deleted by
16840 preprocessing to be replaced by blank lines in the output source file,
16841 preserving line numbers in the output file.
16842
16843 @item ^-c^/COMMENTS^
16844 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16845 Causes both preprocessor lines and the lines deleted
16846 by preprocessing to be retained in the output source as comments marked
16847 with the special string @code{"--! "}. This option will result in line numbers
16848 being preserved in the output file.
16849
16850 @item ^-C^/REPLACE_IN_COMMENTS^
16851 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
16852 Causes comments to be scanned. Normally comments are ignored by gnatprep.
16853 If this option is specified, then comments are scanned and any $symbol
16854 substitutions performed as in program text. This is particularly useful
16855 when structured comments are used (e.g., when writing programs in the
16856 SPARK dialect of Ada). Note that this switch is not available when
16857 doing integrated preprocessing (it would be useless in this context
16858 since comments are ignored by the compiler in any case).
16859
16860 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16861 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16862 Defines a new preprocessing symbol, associated with value. If no value is given
16863 on the command line, then symbol is considered to be @code{True}. This switch
16864 can be used in place of a definition file.
16865
16866 @ifset vms
16867 @item /REMOVE
16868 @cindex @option{/REMOVE} (@command{gnatprep})
16869 This is the default setting which causes lines deleted by preprocessing
16870 to be entirely removed from the output file.
16871 @end ifset
16872
16873 @item ^-r^/REFERENCE^
16874 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16875 Causes a @code{Source_Reference} pragma to be generated that
16876 references the original input file, so that error messages will use
16877 the file name of this original file. The use of this switch implies
16878 that preprocessor lines are not to be removed from the file, so its
16879 use will force @option{^-b^/BLANK_LINES^} mode if
16880 @option{^-c^/COMMENTS^}
16881 has not been specified explicitly.
16882
16883 Note that if the file to be preprocessed contains multiple units, then
16884 it will be necessary to @code{gnatchop} the output file from
16885 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16886 in the preprocessed file, it will be respected by
16887 @code{gnatchop ^-r^/REFERENCE^}
16888 so that the final chopped files will correctly refer to the original
16889 input source file for @code{gnatprep}.
16890
16891 @item ^-s^/SYMBOLS^
16892 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16893 Causes a sorted list of symbol names and values to be
16894 listed on the standard output file.
16895
16896 @item ^-u^/UNDEFINED^
16897 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16898 Causes undefined symbols to be treated as having the value FALSE in the context
16899 of a preprocessor test. In the absence of this option, an undefined symbol in
16900 a @code{#if} or @code{#elsif} test will be treated as an error.
16901
16902 @end table
16903
16904 @ifclear vms
16905 @noindent
16906 Note: if neither @option{-b} nor @option{-c} is present,
16907 then preprocessor lines and
16908 deleted lines are completely removed from the output, unless -r is
16909 specified, in which case -b is assumed.
16910 @end ifclear
16911
16912 @node Form of Definitions File
16913 @section Form of Definitions File
16914
16915 @noindent
16916 The definitions file contains lines of the form
16917
16918 @smallexample
16919 symbol := value
16920 @end smallexample
16921
16922 @noindent
16923 where symbol is a preprocessing symbol, and value is one of the following:
16924
16925 @itemize @bullet
16926 @item
16927 Empty, corresponding to a null substitution
16928 @item
16929 A string literal using normal Ada syntax
16930 @item
16931 Any sequence of characters from the set
16932 (letters, digits, period, underline).
16933 @end itemize
16934
16935 @noindent
16936 Comment lines may also appear in the definitions file, starting with
16937 the usual @code{--},
16938 and comments may be added to the definitions lines.
16939
16940 @node Form of Input Text for gnatprep
16941 @section Form of Input Text for @code{gnatprep}
16942
16943 @noindent
16944 The input text may contain preprocessor conditional inclusion lines,
16945 as well as general symbol substitution sequences.
16946
16947 The preprocessor conditional inclusion commands have the form
16948
16949 @smallexample
16950 @group
16951 @cartouche
16952 #if @i{expression} @r{[}then@r{]}
16953 lines
16954 #elsif @i{expression} @r{[}then@r{]}
16955 lines
16956 #elsif @i{expression} @r{[}then@r{]}
16957 lines
16958 @dots{}
16959 #else
16960 lines
16961 #end if;
16962 @end cartouche
16963 @end group
16964 @end smallexample
16965
16966 @noindent
16967 In this example, @i{expression} is defined by the following grammar:
16968 @smallexample
16969 @i{expression} ::= <symbol>
16970 @i{expression} ::= <symbol> = "<value>"
16971 @i{expression} ::= <symbol> = <symbol>
16972 @i{expression} ::= <symbol> = <integer>
16973 @i{expression} ::= <symbol> > <integer>
16974 @i{expression} ::= <symbol> >= <integer>
16975 @i{expression} ::= <symbol> < <integer>
16976 @i{expression} ::= <symbol> <= <integer>
16977 @i{expression} ::= <symbol> 'Defined
16978 @i{expression} ::= not @i{expression}
16979 @i{expression} ::= @i{expression} and @i{expression}
16980 @i{expression} ::= @i{expression} or @i{expression}
16981 @i{expression} ::= @i{expression} and then @i{expression}
16982 @i{expression} ::= @i{expression} or else @i{expression}
16983 @i{expression} ::= ( @i{expression} )
16984 @end smallexample
16985
16986 The following restriction exists: it is not allowed to have "and" or "or"
16987 following "not" in the same expression without parentheses. For example, this
16988 is not allowed:
16989
16990 @smallexample
16991 not X or Y
16992 @end smallexample
16993
16994 This should be one of the following:
16995
16996 @smallexample
16997 (not X) or Y
16998 not (X or Y)
16999 @end smallexample
17000
17001 @noindent
17002 For the first test (@i{expression} ::= <symbol>) the symbol must have
17003 either the value true or false, that is to say the right-hand of the
17004 symbol definition must be one of the (case-insensitive) literals
17005 @code{True} or @code{False}. If the value is true, then the
17006 corresponding lines are included, and if the value is false, they are
17007 excluded.
17008
17009 When comparing a symbol to an integer, the integer is any non negative
17010 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
17011 2#11#. The symbol value must also be a non negative integer. Integer values
17012 in the range 0 .. 2**31-1 are supported.
17013
17014 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
17015 the symbol has been defined in the definition file or by a @option{-D}
17016 switch on the command line. Otherwise, the test is false.
17017
17018 The equality tests are case insensitive, as are all the preprocessor lines.
17019
17020 If the symbol referenced is not defined in the symbol definitions file,
17021 then the effect depends on whether or not switch @option{-u}
17022 is specified. If so, then the symbol is treated as if it had the value
17023 false and the test fails. If this switch is not specified, then
17024 it is an error to reference an undefined symbol. It is also an error to
17025 reference a symbol that is defined with a value other than @code{True}
17026 or @code{False}.
17027
17028 The use of the @code{not} operator inverts the sense of this logical test.
17029 The @code{not} operator cannot be combined with the @code{or} or @code{and}
17030 operators, without parentheses. For example, "if not X or Y then" is not
17031 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
17032
17033 The @code{then} keyword is optional as shown
17034
17035 The @code{#} must be the first non-blank character on a line, but
17036 otherwise the format is free form. Spaces or tabs may appear between
17037 the @code{#} and the keyword. The keywords and the symbols are case
17038 insensitive as in normal Ada code. Comments may be used on a
17039 preprocessor line, but other than that, no other tokens may appear on a
17040 preprocessor line. Any number of @code{elsif} clauses can be present,
17041 including none at all. The @code{else} is optional, as in Ada.
17042
17043 The @code{#} marking the start of a preprocessor line must be the first
17044 non-blank character on the line, i.e., it must be preceded only by
17045 spaces or horizontal tabs.
17046
17047 Symbol substitution outside of preprocessor lines is obtained by using
17048 the sequence
17049
17050 @smallexample
17051 $symbol
17052 @end smallexample
17053
17054 @noindent
17055 anywhere within a source line, except in a comment or within a
17056 string literal. The identifier
17057 following the @code{$} must match one of the symbols defined in the symbol
17058 definition file, and the result is to substitute the value of the
17059 symbol in place of @code{$symbol} in the output file.
17060
17061 Note that although the substitution of strings within a string literal
17062 is not possible, it is possible to have a symbol whose defined value is
17063 a string literal. So instead of setting XYZ to @code{hello} and writing:
17064
17065 @smallexample
17066 Header : String := "$XYZ";
17067 @end smallexample
17068
17069 @noindent
17070 you should set XYZ to @code{"hello"} and write:
17071
17072 @smallexample
17073 Header : String := $XYZ;
17074 @end smallexample
17075
17076 @noindent
17077 and then the substitution will occur as desired.
17078
17079 @node The GNAT Library Browser gnatls
17080 @chapter The GNAT Library Browser @code{gnatls}
17081 @findex gnatls
17082 @cindex Library browser
17083
17084 @noindent
17085 @code{gnatls} is a tool that outputs information about compiled
17086 units. It gives the relationship between objects, unit names and source
17087 files. It can also be used to check the source dependencies of a unit
17088 as well as various characteristics.
17089
17090 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
17091 driver (see @ref{The GNAT Driver and Project Files}).
17092
17093 @menu
17094 * Running gnatls::
17095 * Switches for gnatls::
17096 * Examples of gnatls Usage::
17097 @end menu
17098
17099 @node Running gnatls
17100 @section Running @code{gnatls}
17101
17102 @noindent
17103 The @code{gnatls} command has the form
17104
17105 @smallexample
17106 $ gnatls switches @var{object_or_ali_file}
17107 @end smallexample
17108
17109 @noindent
17110 The main argument is the list of object or @file{ali} files
17111 (@pxref{The Ada Library Information Files})
17112 for which information is requested.
17113
17114 In normal mode, without additional option, @code{gnatls} produces a
17115 four-column listing. Each line represents information for a specific
17116 object. The first column gives the full path of the object, the second
17117 column gives the name of the principal unit in this object, the third
17118 column gives the status of the source and the fourth column gives the
17119 full path of the source representing this unit.
17120 Here is a simple example of use:
17121
17122 @smallexample
17123 $ gnatls *.o
17124 ^./^[]^demo1.o demo1 DIF demo1.adb
17125 ^./^[]^demo2.o demo2 OK demo2.adb
17126 ^./^[]^hello.o h1 OK hello.adb
17127 ^./^[]^instr-child.o instr.child MOK instr-child.adb
17128 ^./^[]^instr.o instr OK instr.adb
17129 ^./^[]^tef.o tef DIF tef.adb
17130 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
17131 ^./^[]^tgef.o tgef DIF tgef.adb
17132 @end smallexample
17133
17134 @noindent
17135 The first line can be interpreted as follows: the main unit which is
17136 contained in
17137 object file @file{demo1.o} is demo1, whose main source is in
17138 @file{demo1.adb}. Furthermore, the version of the source used for the
17139 compilation of demo1 has been modified (DIF). Each source file has a status
17140 qualifier which can be:
17141
17142 @table @code
17143 @item OK (unchanged)
17144 The version of the source file used for the compilation of the
17145 specified unit corresponds exactly to the actual source file.
17146
17147 @item MOK (slightly modified)
17148 The version of the source file used for the compilation of the
17149 specified unit differs from the actual source file but not enough to
17150 require recompilation. If you use gnatmake with the qualifier
17151 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
17152 MOK will not be recompiled.
17153
17154 @item DIF (modified)
17155 No version of the source found on the path corresponds to the source
17156 used to build this object.
17157
17158 @item ??? (file not found)
17159 No source file was found for this unit.
17160
17161 @item HID (hidden, unchanged version not first on PATH)
17162 The version of the source that corresponds exactly to the source used
17163 for compilation has been found on the path but it is hidden by another
17164 version of the same source that has been modified.
17165
17166 @end table
17167
17168 @node Switches for gnatls
17169 @section Switches for @code{gnatls}
17170
17171 @noindent
17172 @code{gnatls} recognizes the following switches:
17173
17174 @table @option
17175 @c !sort!
17176 @cindex @option{--version} @command{gnatls}
17177 Display Copyright and version, then exit disregarding all other options.
17178
17179 @item --help
17180 @cindex @option{--help} @command{gnatls}
17181 If @option{--version} was not used, display usage, then exit disregarding
17182 all other options.
17183
17184 @item ^-a^/ALL_UNITS^
17185 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
17186 Consider all units, including those of the predefined Ada library.
17187 Especially useful with @option{^-d^/DEPENDENCIES^}.
17188
17189 @item ^-d^/DEPENDENCIES^
17190 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
17191 List sources from which specified units depend on.
17192
17193 @item ^-h^/OUTPUT=OPTIONS^
17194 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
17195 Output the list of options.
17196
17197 @item ^-o^/OUTPUT=OBJECTS^
17198 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
17199 Only output information about object files.
17200
17201 @item ^-s^/OUTPUT=SOURCES^
17202 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
17203 Only output information about source files.
17204
17205 @item ^-u^/OUTPUT=UNITS^
17206 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
17207 Only output information about compilation units.
17208
17209 @item ^-files^/FILES^=@var{file}
17210 @cindex @option{^-files^/FILES^} (@code{gnatls})
17211 Take as arguments the files listed in text file @var{file}.
17212 Text file @var{file} may contain empty lines that are ignored.
17213 Each nonempty line should contain the name of an existing file.
17214 Several such switches may be specified simultaneously.
17215
17216 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17217 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
17218 @itemx ^-I^/SEARCH=^@var{dir}
17219 @itemx ^-I-^/NOCURRENT_DIRECTORY^
17220 @itemx -nostdinc
17221 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
17222 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
17223 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
17224 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
17225 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
17226 flags (@pxref{Switches for gnatmake}).
17227
17228 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^@var{dir}
17229 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (@code{gnatls})
17230 Add @var{dir} at the beginning of the project search dir.
17231
17232 @item --RTS=@var{rts-path}
17233 @cindex @option{--RTS} (@code{gnatls})
17234 Specifies the default location of the runtime library. Same meaning as the
17235 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
17236
17237 @item ^-v^/OUTPUT=VERBOSE^
17238 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
17239 Verbose mode. Output the complete source, object and project paths. Do not use
17240 the default column layout but instead use long format giving as much as
17241 information possible on each requested units, including special
17242 characteristics such as:
17243
17244 @table @code
17245 @item Preelaborable
17246 The unit is preelaborable in the Ada sense.
17247
17248 @item No_Elab_Code
17249 No elaboration code has been produced by the compiler for this unit.
17250
17251 @item Pure
17252 The unit is pure in the Ada sense.
17253
17254 @item Elaborate_Body
17255 The unit contains a pragma Elaborate_Body.
17256
17257 @item Remote_Types
17258 The unit contains a pragma Remote_Types.
17259
17260 @item Shared_Passive
17261 The unit contains a pragma Shared_Passive.
17262
17263 @item Predefined
17264 This unit is part of the predefined environment and cannot be modified
17265 by the user.
17266
17267 @item Remote_Call_Interface
17268 The unit contains a pragma Remote_Call_Interface.
17269
17270 @end table
17271
17272 @end table
17273
17274 @node Examples of gnatls Usage
17275 @section Example of @code{gnatls} Usage
17276 @ifclear vms
17277
17278 @noindent
17279 Example of using the verbose switch. Note how the source and
17280 object paths are affected by the -I switch.
17281
17282 @smallexample
17283 $ gnatls -v -I.. demo1.o
17284
17285 GNATLS 5.03w (20041123-34)
17286 Copyright 1997-2004 Free Software Foundation, Inc.
17287
17288 Source Search Path:
17289 <Current_Directory>
17290 ../
17291 /home/comar/local/adainclude/
17292
17293 Object Search Path:
17294 <Current_Directory>
17295 ../
17296 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17297
17298 Project Search Path:
17299 <Current_Directory>
17300 /home/comar/local/lib/gnat/
17301
17302 ./demo1.o
17303 Unit =>
17304 Name => demo1
17305 Kind => subprogram body
17306 Flags => No_Elab_Code
17307 Source => demo1.adb modified
17308 @end smallexample
17309
17310 @noindent
17311 The following is an example of use of the dependency list.
17312 Note the use of the -s switch
17313 which gives a straight list of source files. This can be useful for
17314 building specialized scripts.
17315
17316 @smallexample
17317 $ gnatls -d demo2.o
17318 ./demo2.o demo2 OK demo2.adb
17319 OK gen_list.ads
17320 OK gen_list.adb
17321 OK instr.ads
17322 OK instr-child.ads
17323
17324 $ gnatls -d -s -a demo1.o
17325 demo1.adb
17326 /home/comar/local/adainclude/ada.ads
17327 /home/comar/local/adainclude/a-finali.ads
17328 /home/comar/local/adainclude/a-filico.ads
17329 /home/comar/local/adainclude/a-stream.ads
17330 /home/comar/local/adainclude/a-tags.ads
17331 gen_list.ads
17332 gen_list.adb
17333 /home/comar/local/adainclude/gnat.ads
17334 /home/comar/local/adainclude/g-io.ads
17335 instr.ads
17336 /home/comar/local/adainclude/system.ads
17337 /home/comar/local/adainclude/s-exctab.ads
17338 /home/comar/local/adainclude/s-finimp.ads
17339 /home/comar/local/adainclude/s-finroo.ads
17340 /home/comar/local/adainclude/s-secsta.ads
17341 /home/comar/local/adainclude/s-stalib.ads
17342 /home/comar/local/adainclude/s-stoele.ads
17343 /home/comar/local/adainclude/s-stratt.ads
17344 /home/comar/local/adainclude/s-tasoli.ads
17345 /home/comar/local/adainclude/s-unstyp.ads
17346 /home/comar/local/adainclude/unchconv.ads
17347 @end smallexample
17348 @end ifclear
17349
17350 @ifset vms
17351 @smallexample
17352 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
17353
17354 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
17355 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
17356 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
17357 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
17358 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
17359 demo1.adb
17360 gen_list.ads
17361 gen_list.adb
17362 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
17363 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
17364 instr.ads
17365 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
17366 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
17367 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
17368 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
17369 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
17370 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
17371 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
17372 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
17373 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
17374 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
17375 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
17376 @end smallexample
17377 @end ifset
17378
17379 @node Cleaning Up with gnatclean
17380 @chapter Cleaning Up with @code{gnatclean}
17381 @findex gnatclean
17382 @cindex Cleaning tool
17383
17384 @noindent
17385 @code{gnatclean} is a tool that allows the deletion of files produced by the
17386 compiler, binder and linker, including ALI files, object files, tree files,
17387 expanded source files, library files, interface copy source files, binder
17388 generated files and executable files.
17389
17390 @menu
17391 * Running gnatclean::
17392 * Switches for gnatclean::
17393 @c * Examples of gnatclean Usage::
17394 @end menu
17395
17396 @node Running gnatclean
17397 @section Running @code{gnatclean}
17398
17399 @noindent
17400 The @code{gnatclean} command has the form:
17401
17402 @smallexample
17403 $ gnatclean switches @var{names}
17404 @end smallexample
17405
17406 @noindent
17407 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
17408 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
17409 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
17410
17411 @noindent
17412 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17413 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
17414 the linker. In informative-only mode, specified by switch
17415 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
17416 normal mode is listed, but no file is actually deleted.
17417
17418 @node Switches for gnatclean
17419 @section Switches for @code{gnatclean}
17420
17421 @noindent
17422 @code{gnatclean} recognizes the following switches:
17423
17424 @table @option
17425 @c !sort!
17426 @cindex @option{--version} @command{gnatclean}
17427 Display Copyright and version, then exit disregarding all other options.
17428
17429 @item --help
17430 @cindex @option{--help} @command{gnatclean}
17431 If @option{--version} was not used, display usage, then exit disregarding
17432 all other options.
17433
17434 @item ^--subdirs^/SUBDIRS^=subdir
17435 Actual object directory of each project file is the subdirectory subdir of the
17436 object directory specified or defaulted in the project file.
17437
17438 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
17439 By default, shared library projects are not allowed to import static library
17440 projects. When this switch is used on the command line, this restriction is
17441 relaxed.
17442
17443 @item ^-c^/COMPILER_FILES_ONLY^
17444 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
17445 Only attempt to delete the files produced by the compiler, not those produced
17446 by the binder or the linker. The files that are not to be deleted are library
17447 files, interface copy files, binder generated files and executable files.
17448
17449 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
17450 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17451 Indicate that ALI and object files should normally be found in directory
17452 @var{dir}.
17453
17454 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17455 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17456 When using project files, if some errors or warnings are detected during
17457 parsing and verbose mode is not in effect (no use of switch
17458 ^-v^/VERBOSE^), then error lines start with the full path name of the project
17459 file, rather than its simple file name.
17460
17461 @item ^-h^/HELP^
17462 @cindex @option{^-h^/HELP^} (@code{gnatclean})
17463 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17464
17465 @item ^-n^/NODELETE^
17466 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17467 Informative-only mode. Do not delete any files. Output the list of the files
17468 that would have been deleted if this switch was not specified.
17469
17470 @item ^-P^/PROJECT_FILE=^@var{project}
17471 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17472 Use project file @var{project}. Only one such switch can be used.
17473 When cleaning a project file, the files produced by the compilation of the
17474 immediate sources or inherited sources of the project files are to be
17475 deleted. This is not depending on the presence or not of executable names
17476 on the command line.
17477
17478 @item ^-q^/QUIET^
17479 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
17480 Quiet output. If there are no errors, do not output anything, except in
17481 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17482 (switch ^-n^/NODELETE^).
17483
17484 @item ^-r^/RECURSIVE^
17485 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17486 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17487 clean all imported and extended project files, recursively. If this switch
17488 is not specified, only the files related to the main project file are to be
17489 deleted. This switch has no effect if no project file is specified.
17490
17491 @item ^-v^/VERBOSE^
17492 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17493 Verbose mode.
17494
17495 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17496 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17497 Indicates the verbosity of the parsing of GNAT project files.
17498 @xref{Switches Related to Project Files}.
17499
17500 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17501 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17502 Indicates that external variable @var{name} has the value @var{value}.
17503 The Project Manager will use this value for occurrences of
17504 @code{external(name)} when parsing the project file.
17505 @xref{Switches Related to Project Files}.
17506
17507 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17508 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17509 When searching for ALI and object files, look in directory
17510 @var{dir}.
17511
17512 @item ^-I^/SEARCH=^@var{dir}
17513 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17514 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17515
17516 @item ^-I-^/NOCURRENT_DIRECTORY^
17517 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
17518 @cindex Source files, suppressing search
17519 Do not look for ALI or object files in the directory
17520 where @code{gnatclean} was invoked.
17521
17522 @end table
17523
17524 @c @node Examples of gnatclean Usage
17525 @c @section Examples of @code{gnatclean} Usage
17526
17527 @ifclear vms
17528 @node GNAT and Libraries
17529 @chapter GNAT and Libraries
17530 @cindex Library, building, installing, using
17531
17532 @noindent
17533 This chapter describes how to build and use libraries with GNAT, and also shows
17534 how to recompile the GNAT run-time library. You should be familiar with the
17535 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
17536 chapter.
17537
17538 @menu
17539 * Introduction to Libraries in GNAT::
17540 * General Ada Libraries::
17541 * Stand-alone Ada Libraries::
17542 * Rebuilding the GNAT Run-Time Library::
17543 @end menu
17544
17545 @node Introduction to Libraries in GNAT
17546 @section Introduction to Libraries in GNAT
17547
17548 @noindent
17549 A library is, conceptually, a collection of objects which does not have its
17550 own main thread of execution, but rather provides certain services to the
17551 applications that use it. A library can be either statically linked with the
17552 application, in which case its code is directly included in the application,
17553 or, on platforms that support it, be dynamically linked, in which case
17554 its code is shared by all applications making use of this library.
17555
17556 GNAT supports both types of libraries.
17557 In the static case, the compiled code can be provided in different ways. The
17558 simplest approach is to provide directly the set of objects resulting from
17559 compilation of the library source files. Alternatively, you can group the
17560 objects into an archive using whatever commands are provided by the operating
17561 system. For the latter case, the objects are grouped into a shared library.
17562
17563 In the GNAT environment, a library has three types of components:
17564 @itemize @bullet
17565 @item
17566 Source files.
17567 @item
17568 @file{ALI} files.
17569 @xref{The Ada Library Information Files}.
17570 @item
17571 Object files, an archive or a shared library.
17572 @end itemize
17573
17574 @noindent
17575 A GNAT library may expose all its source files, which is useful for
17576 documentation purposes. Alternatively, it may expose only the units needed by
17577 an external user to make use of the library. That is to say, the specs
17578 reflecting the library services along with all the units needed to compile
17579 those specs, which can include generic bodies or any body implementing an
17580 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17581 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17582
17583 All compilation units comprising an application, including those in a library,
17584 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17585 computes the elaboration order from the @file{ALI} files and this is why they
17586 constitute a mandatory part of GNAT libraries.
17587 @emph{Stand-alone libraries} are the exception to this rule because a specific
17588 library elaboration routine is produced independently of the application(s)
17589 using the library.
17590
17591 @node General Ada Libraries
17592 @section General Ada Libraries
17593
17594 @menu
17595 * Building a library::
17596 * Installing a library::
17597 * Using a library::
17598 @end menu
17599
17600 @node Building a library
17601 @subsection Building a library
17602
17603 @noindent
17604 The easiest way to build a library is to use the Project Manager,
17605 which supports a special type of project called a @emph{Library Project}
17606 (@pxref{Library Projects}).
17607
17608 A project is considered a library project, when two project-level attributes
17609 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17610 control different aspects of library configuration, additional optional
17611 project-level attributes can be specified:
17612 @table @code
17613 @item Library_Kind
17614 This attribute controls whether the library is to be static or dynamic
17615
17616 @item Library_Version
17617 This attribute specifies the library version; this value is used
17618 during dynamic linking of shared libraries to determine if the currently
17619 installed versions of the binaries are compatible.
17620
17621 @item Library_Options
17622 @item Library_GCC
17623 These attributes specify additional low-level options to be used during
17624 library generation, and redefine the actual application used to generate
17625 library.
17626 @end table
17627
17628 @noindent
17629 The GNAT Project Manager takes full care of the library maintenance task,
17630 including recompilation of the source files for which objects do not exist
17631 or are not up to date, assembly of the library archive, and installation of
17632 the library (i.e., copying associated source, object and @file{ALI} files
17633 to the specified location).
17634
17635 Here is a simple library project file:
17636 @smallexample @c ada
17637 project My_Lib is
17638 for Source_Dirs use ("src1", "src2");
17639 for Object_Dir use "obj";
17640 for Library_Name use "mylib";
17641 for Library_Dir use "lib";
17642 for Library_Kind use "dynamic";
17643 end My_lib;
17644 @end smallexample
17645
17646 @noindent
17647 and the compilation command to build and install the library:
17648
17649 @smallexample @c ada
17650 $ gnatmake -Pmy_lib
17651 @end smallexample
17652
17653 @noindent
17654 It is not entirely trivial to perform manually all the steps required to
17655 produce a library. We recommend that you use the GNAT Project Manager
17656 for this task. In special cases where this is not desired, the necessary
17657 steps are discussed below.
17658
17659 There are various possibilities for compiling the units that make up the
17660 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17661 with a conventional script. For simple libraries, it is also possible to create
17662 a dummy main program which depends upon all the packages that comprise the
17663 interface of the library. This dummy main program can then be given to
17664 @command{gnatmake}, which will ensure that all necessary objects are built.
17665
17666 After this task is accomplished, you should follow the standard procedure
17667 of the underlying operating system to produce the static or shared library.
17668
17669 Here is an example of such a dummy program:
17670 @smallexample @c ada
17671 @group
17672 with My_Lib.Service1;
17673 with My_Lib.Service2;
17674 with My_Lib.Service3;
17675 procedure My_Lib_Dummy is
17676 begin
17677 null;
17678 end;
17679 @end group
17680 @end smallexample
17681
17682 @noindent
17683 Here are the generic commands that will build an archive or a shared library.
17684
17685 @smallexample
17686 # compiling the library
17687 $ gnatmake -c my_lib_dummy.adb
17688
17689 # we don't need the dummy object itself
17690 $ rm my_lib_dummy.o my_lib_dummy.ali
17691
17692 # create an archive with the remaining objects
17693 $ ar rc libmy_lib.a *.o
17694 # some systems may require "ranlib" to be run as well
17695
17696 # or create a shared library
17697 $ gcc -shared -o libmy_lib.so *.o
17698 # some systems may require the code to have been compiled with -fPIC
17699
17700 # remove the object files that are now in the library
17701 $ rm *.o
17702
17703 # Make the ALI files read-only so that gnatmake will not try to
17704 # regenerate the objects that are in the library
17705 $ chmod -w *.ali
17706 @end smallexample
17707
17708 @noindent
17709 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
17710 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
17711 be accessed by the directive @option{-l@var{xxx}} at link time.
17712
17713 @node Installing a library
17714 @subsection Installing a library
17715 @cindex @code{ADA_PROJECT_PATH}
17716 @cindex @code{GPR_PROJECT_PATH}
17717
17718 @noindent
17719 If you use project files, library installation is part of the library build
17720 process (@pxref{Installing a library with project files}).
17721
17722 When project files are not an option, it is also possible, but not recommended,
17723 to install the library so that the sources needed to use the library are on the
17724 Ada source path and the ALI files & libraries be on the Ada Object path (see
17725 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17726 administrator can place general-purpose libraries in the default compiler
17727 paths, by specifying the libraries' location in the configuration files
17728 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17729 must be located in the GNAT installation tree at the same place as the gcc spec
17730 file. The location of the gcc spec file can be determined as follows:
17731 @smallexample
17732 $ gcc -v
17733 @end smallexample
17734
17735 @noindent
17736 The configuration files mentioned above have a simple format: each line
17737 must contain one unique directory name.
17738 Those names are added to the corresponding path
17739 in their order of appearance in the file. The names can be either absolute
17740 or relative; in the latter case, they are relative to where theses files
17741 are located.
17742
17743 The files @file{ada_source_path} and @file{ada_object_path} might not be
17744 present in a
17745 GNAT installation, in which case, GNAT will look for its run-time library in
17746 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17747 objects and @file{ALI} files). When the files exist, the compiler does not
17748 look in @file{adainclude} and @file{adalib}, and thus the
17749 @file{ada_source_path} file
17750 must contain the location for the GNAT run-time sources (which can simply
17751 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17752 contain the location for the GNAT run-time objects (which can simply
17753 be @file{adalib}).
17754
17755 You can also specify a new default path to the run-time library at compilation
17756 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17757 the run-time library you want your program to be compiled with. This switch is
17758 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17759 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17760
17761 It is possible to install a library before or after the standard GNAT
17762 library, by reordering the lines in the configuration files. In general, a
17763 library must be installed before the GNAT library if it redefines
17764 any part of it.
17765
17766 @node Using a library
17767 @subsection Using a library
17768
17769 @noindent Once again, the project facility greatly simplifies the use of
17770 libraries. In this context, using a library is just a matter of adding a
17771 @code{with} clause in the user project. For instance, to make use of the
17772 library @code{My_Lib} shown in examples in earlier sections, you can
17773 write:
17774
17775 @smallexample @c projectfile
17776 with "my_lib";
17777 project My_Proj is
17778 @dots{}
17779 end My_Proj;
17780 @end smallexample
17781
17782 Even if you have a third-party, non-Ada library, you can still use GNAT's
17783 Project Manager facility to provide a wrapper for it. For example, the
17784 following project, when @code{with}ed by your main project, will link with the
17785 third-party library @file{liba.a}:
17786
17787 @smallexample @c projectfile
17788 @group
17789 project Liba is
17790 for Externally_Built use "true";
17791 for Source_Files use ();
17792 for Library_Dir use "lib";
17793 for Library_Name use "a";
17794 for Library_Kind use "static";
17795 end Liba;
17796 @end group
17797 @end smallexample
17798 This is an alternative to the use of @code{pragma Linker_Options}. It is
17799 especially interesting in the context of systems with several interdependent
17800 static libraries where finding a proper linker order is not easy and best be
17801 left to the tools having visibility over project dependence information.
17802
17803 @noindent
17804 In order to use an Ada library manually, you need to make sure that this
17805 library is on both your source and object path
17806 (see @ref{Search Paths and the Run-Time Library (RTL)}
17807 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17808 in an archive or a shared library, you need to specify the desired
17809 library at link time.
17810
17811 For example, you can use the library @file{mylib} installed in
17812 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17813
17814 @smallexample
17815 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17816 -largs -lmy_lib
17817 @end smallexample
17818
17819 @noindent
17820 This can be expressed more simply:
17821 @smallexample
17822 $ gnatmake my_appl
17823 @end smallexample
17824 @noindent
17825 when the following conditions are met:
17826 @itemize @bullet
17827 @item
17828 @file{/dir/my_lib_src} has been added by the user to the environment
17829 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
17830 @file{ada_source_path}
17831 @item
17832 @file{/dir/my_lib_obj} has been added by the user to the environment
17833 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
17834 @file{ada_object_path}
17835 @item
17836 a pragma @code{Linker_Options} has been added to one of the sources.
17837 For example:
17838
17839 @smallexample @c ada
17840 pragma Linker_Options ("-lmy_lib");
17841 @end smallexample
17842 @end itemize
17843
17844 @node Stand-alone Ada Libraries
17845 @section Stand-alone Ada Libraries
17846 @cindex Stand-alone library, building, using
17847
17848 @menu
17849 * Introduction to Stand-alone Libraries::
17850 * Building a Stand-alone Library::
17851 * Creating a Stand-alone Library to be used in a non-Ada context::
17852 * Restrictions in Stand-alone Libraries::
17853 @end menu
17854
17855 @node Introduction to Stand-alone Libraries
17856 @subsection Introduction to Stand-alone Libraries
17857
17858 @noindent
17859 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17860 necessary code to
17861 elaborate the Ada units that are included in the library. In contrast with
17862 an ordinary library, which consists of all sources, objects and @file{ALI}
17863 files of the
17864 library, a SAL may specify a restricted subset of compilation units
17865 to serve as a library interface. In this case, the fully
17866 self-sufficient set of files will normally consist of an objects
17867 archive, the sources of interface units' specs, and the @file{ALI}
17868 files of interface units.
17869 If an interface spec contains a generic unit or an inlined subprogram,
17870 the body's
17871 source must also be provided; if the units that must be provided in the source
17872 form depend on other units, the source and @file{ALI} files of those must
17873 also be provided.
17874
17875 The main purpose of a SAL is to minimize the recompilation overhead of client
17876 applications when a new version of the library is installed. Specifically,
17877 if the interface sources have not changed, client applications do not need to
17878 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17879 version, controlled by @code{Library_Version} attribute, is not changed,
17880 then the clients do not need to be relinked.
17881
17882 SALs also allow the library providers to minimize the amount of library source
17883 text exposed to the clients. Such ``information hiding'' might be useful or
17884 necessary for various reasons.
17885
17886 Stand-alone libraries are also well suited to be used in an executable whose
17887 main routine is not written in Ada.
17888
17889 @node Building a Stand-alone Library
17890 @subsection Building a Stand-alone Library
17891
17892 @noindent
17893 GNAT's Project facility provides a simple way of building and installing
17894 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17895 To be a Stand-alone Library Project, in addition to the two attributes
17896 that make a project a Library Project (@code{Library_Name} and
17897 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17898 @code{Library_Interface} must be defined. For example:
17899
17900 @smallexample @c projectfile
17901 @group
17902 for Library_Dir use "lib_dir";
17903 for Library_Name use "dummy";
17904 for Library_Interface use ("int1", "int1.child");
17905 @end group
17906 @end smallexample
17907
17908 @noindent
17909 Attribute @code{Library_Interface} has a non-empty string list value,
17910 each string in the list designating a unit contained in an immediate source
17911 of the project file.
17912
17913 When a Stand-alone Library is built, first the binder is invoked to build
17914 a package whose name depends on the library name
17915 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
17916 This binder-generated package includes initialization and
17917 finalization procedures whose
17918 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17919 in the example
17920 above). The object corresponding to this package is included in the library.
17921
17922 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17923 calling of these procedures if a static SAL is built, or if a shared SAL
17924 is built
17925 with the project-level attribute @code{Library_Auto_Init} set to
17926 @code{"false"}.
17927
17928 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17929 (those that are listed in attribute @code{Library_Interface}) are copied to
17930 the Library Directory. As a consequence, only the Interface Units may be
17931 imported from Ada units outside of the library. If other units are imported,
17932 the binding phase will fail.
17933
17934 @noindent
17935 It is also possible to build an encapsulated library where not only
17936 the code to elaborate and finalize the library is embedded but also
17937 ensuring that the library is linked only against static
17938 libraries. So an encapsulated library only depends on system
17939 libraries, all other code, including the GNAT runtime, is embedded. To
17940 build an encapsulated library the attribute
17941 @code{Library_Standalone} must be set to @code{encapsulated}:
17942
17943 @smallexample @c projectfile
17944 @group
17945 for Library_Dir use "lib_dir";
17946 for Library_Name use "dummy";
17947 for Library_Kind use "dynamic";
17948 for Library_Interface use ("int1", "int1.child");
17949 for Library_Standalone use "encapsulated";
17950 @end group
17951 @end smallexample
17952
17953 @noindent
17954 The default value for this attribute is @code{standard} in which case
17955 a stand-alone library is built.
17956
17957 The attribute @code{Library_Src_Dir} may be specified for a
17958 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17959 single string value. Its value must be the path (absolute or relative to the
17960 project directory) of an existing directory. This directory cannot be the
17961 object directory or one of the source directories, but it can be the same as
17962 the library directory. The sources of the Interface
17963 Units of the library that are needed by an Ada client of the library will be
17964 copied to the designated directory, called the Interface Copy directory.
17965 These sources include the specs of the Interface Units, but they may also
17966 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17967 are used, or when there is a generic unit in the spec. Before the sources
17968 are copied to the Interface Copy directory, an attempt is made to delete all
17969 files in the Interface Copy directory.
17970
17971 Building stand-alone libraries by hand is somewhat tedious, but for those
17972 occasions when it is necessary here are the steps that you need to perform:
17973 @itemize @bullet
17974 @item
17975 Compile all library sources.
17976
17977 @item
17978 Invoke the binder with the switch @option{-n} (No Ada main program),
17979 with all the @file{ALI} files of the interfaces, and
17980 with the switch @option{-L} to give specific names to the @code{init}
17981 and @code{final} procedures. For example:
17982 @smallexample
17983 gnatbind -n int1.ali int2.ali -Lsal1
17984 @end smallexample
17985
17986 @item
17987 Compile the binder generated file:
17988 @smallexample
17989 gcc -c b~int2.adb
17990 @end smallexample
17991
17992 @item
17993 Link the dynamic library with all the necessary object files,
17994 indicating to the linker the names of the @code{init} (and possibly
17995 @code{final}) procedures for automatic initialization (and finalization).
17996 The built library should be placed in a directory different from
17997 the object directory.
17998
17999 @item
18000 Copy the @code{ALI} files of the interface to the library directory,
18001 add in this copy an indication that it is an interface to a SAL
18002 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
18003 with letter ``P'') and make the modified copy of the @file{ALI} file
18004 read-only.
18005 @end itemize
18006
18007 @noindent
18008 Using SALs is not different from using other libraries
18009 (see @ref{Using a library}).
18010
18011 @node Creating a Stand-alone Library to be used in a non-Ada context
18012 @subsection Creating a Stand-alone Library to be used in a non-Ada context
18013
18014 @noindent
18015 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
18016 a non-Ada context.
18017
18018 The only extra step required is to ensure that library interface subprograms
18019 are compatible with the main program, by means of @code{pragma Export}
18020 or @code{pragma Convention}.
18021
18022 Here is an example of simple library interface for use with C main program:
18023
18024 @smallexample @c ada
18025 package My_Package is
18026
18027 procedure Do_Something;
18028 pragma Export (C, Do_Something, "do_something");
18029
18030 procedure Do_Something_Else;
18031 pragma Export (C, Do_Something_Else, "do_something_else");
18032
18033 end My_Package;
18034 @end smallexample
18035
18036 @noindent
18037 On the foreign language side, you must provide a ``foreign'' view of the
18038 library interface; remember that it should contain elaboration routines in
18039 addition to interface subprograms.
18040
18041 The example below shows the content of @code{mylib_interface.h} (note
18042 that there is no rule for the naming of this file, any name can be used)
18043 @smallexample
18044 /* the library elaboration procedure */
18045 extern void mylibinit (void);
18046
18047 /* the library finalization procedure */
18048 extern void mylibfinal (void);
18049
18050 /* the interface exported by the library */
18051 extern void do_something (void);
18052 extern void do_something_else (void);
18053 @end smallexample
18054
18055 @noindent
18056 Libraries built as explained above can be used from any program, provided
18057 that the elaboration procedures (named @code{mylibinit} in the previous
18058 example) are called before the library services are used. Any number of
18059 libraries can be used simultaneously, as long as the elaboration
18060 procedure of each library is called.
18061
18062 Below is an example of a C program that uses the @code{mylib} library.
18063
18064 @smallexample
18065 #include "mylib_interface.h"
18066
18067 int
18068 main (void)
18069 @{
18070 /* First, elaborate the library before using it */
18071 mylibinit ();
18072
18073 /* Main program, using the library exported entities */
18074 do_something ();
18075 do_something_else ();
18076
18077 /* Library finalization at the end of the program */
18078 mylibfinal ();
18079 return 0;
18080 @}
18081 @end smallexample
18082
18083 @noindent
18084 Note that invoking any library finalization procedure generated by
18085 @code{gnatbind} shuts down the Ada run-time environment.
18086 Consequently, the
18087 finalization of all Ada libraries must be performed at the end of the program.
18088 No call to these libraries or to the Ada run-time library should be made
18089 after the finalization phase.
18090
18091 @node Restrictions in Stand-alone Libraries
18092 @subsection Restrictions in Stand-alone Libraries
18093
18094 @noindent
18095 The pragmas listed below should be used with caution inside libraries,
18096 as they can create incompatibilities with other Ada libraries:
18097 @itemize @bullet
18098 @item pragma @code{Locking_Policy}
18099 @item pragma @code{Partition_Elaboration_Policy}
18100 @item pragma @code{Queuing_Policy}
18101 @item pragma @code{Task_Dispatching_Policy}
18102 @item pragma @code{Unreserve_All_Interrupts}
18103 @end itemize
18104
18105 @noindent
18106 When using a library that contains such pragmas, the user must make sure
18107 that all libraries use the same pragmas with the same values. Otherwise,
18108 @code{Program_Error} will
18109 be raised during the elaboration of the conflicting
18110 libraries. The usage of these pragmas and its consequences for the user
18111 should therefore be well documented.
18112
18113 Similarly, the traceback in the exception occurrence mechanism should be
18114 enabled or disabled in a consistent manner across all libraries.
18115 Otherwise, Program_Error will be raised during the elaboration of the
18116 conflicting libraries.
18117
18118 If the @code{Version} or @code{Body_Version}
18119 attributes are used inside a library, then you need to
18120 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
18121 libraries, so that version identifiers can be properly computed.
18122 In practice these attributes are rarely used, so this is unlikely
18123 to be a consideration.
18124
18125 @node Rebuilding the GNAT Run-Time Library
18126 @section Rebuilding the GNAT Run-Time Library
18127 @cindex GNAT Run-Time Library, rebuilding
18128 @cindex Building the GNAT Run-Time Library
18129 @cindex Rebuilding the GNAT Run-Time Library
18130 @cindex Run-Time Library, rebuilding
18131
18132 @noindent
18133 It may be useful to recompile the GNAT library in various contexts, the
18134 most important one being the use of partition-wide configuration pragmas
18135 such as @code{Normalize_Scalars}. A special Makefile called
18136 @code{Makefile.adalib} is provided to that effect and can be found in
18137 the directory containing the GNAT library. The location of this
18138 directory depends on the way the GNAT environment has been installed and can
18139 be determined by means of the command:
18140
18141 @smallexample
18142 $ gnatls -v
18143 @end smallexample
18144
18145 @noindent
18146 The last entry in the object search path usually contains the
18147 gnat library. This Makefile contains its own documentation and in
18148 particular the set of instructions needed to rebuild a new library and
18149 to use it.
18150
18151 @node Using the GNU make Utility
18152 @chapter Using the GNU @code{make} Utility
18153 @findex make
18154
18155 @noindent
18156 This chapter offers some examples of makefiles that solve specific
18157 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
18158 make, make, GNU @code{make}}), nor does it try to replace the
18159 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
18160
18161 All the examples in this section are specific to the GNU version of
18162 make. Although @command{make} is a standard utility, and the basic language
18163 is the same, these examples use some advanced features found only in
18164 @code{GNU make}.
18165
18166 @menu
18167 * Using gnatmake in a Makefile::
18168 * Automatically Creating a List of Directories::
18169 * Generating the Command Line Switches::
18170 * Overcoming Command Line Length Limits::
18171 @end menu
18172
18173 @node Using gnatmake in a Makefile
18174 @section Using gnatmake in a Makefile
18175 @findex makefile
18176 @cindex GNU make
18177
18178 @noindent
18179 Complex project organizations can be handled in a very powerful way by
18180 using GNU make combined with gnatmake. For instance, here is a Makefile
18181 which allows you to build each subsystem of a big project into a separate
18182 shared library. Such a makefile allows you to significantly reduce the link
18183 time of very big applications while maintaining full coherence at
18184 each step of the build process.
18185
18186 The list of dependencies are handled automatically by
18187 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
18188 the appropriate directories.
18189
18190 Note that you should also read the example on how to automatically
18191 create the list of directories
18192 (@pxref{Automatically Creating a List of Directories})
18193 which might help you in case your project has a lot of subdirectories.
18194
18195 @smallexample
18196 @iftex
18197 @leftskip=0cm
18198 @font@heightrm=cmr8
18199 @heightrm
18200 @end iftex
18201 ## This Makefile is intended to be used with the following directory
18202 ## configuration:
18203 ## - The sources are split into a series of csc (computer software components)
18204 ## Each of these csc is put in its own directory.
18205 ## Their name are referenced by the directory names.
18206 ## They will be compiled into shared library (although this would also work
18207 ## with static libraries
18208 ## - The main program (and possibly other packages that do not belong to any
18209 ## csc is put in the top level directory (where the Makefile is).
18210 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
18211 ## \_ second_csc (sources) __ lib (will contain the library)
18212 ## \_ @dots{}
18213 ## Although this Makefile is build for shared library, it is easy to modify
18214 ## to build partial link objects instead (modify the lines with -shared and
18215 ## gnatlink below)
18216 ##
18217 ## With this makefile, you can change any file in the system or add any new
18218 ## file, and everything will be recompiled correctly (only the relevant shared
18219 ## objects will be recompiled, and the main program will be re-linked).
18220
18221 # The list of computer software component for your project. This might be
18222 # generated automatically.
18223 CSC_LIST=aa bb cc
18224
18225 # Name of the main program (no extension)
18226 MAIN=main
18227
18228 # If we need to build objects with -fPIC, uncomment the following line
18229 #NEED_FPIC=-fPIC
18230
18231 # The following variable should give the directory containing libgnat.so
18232 # You can get this directory through 'gnatls -v'. This is usually the last
18233 # directory in the Object_Path.
18234 GLIB=@dots{}
18235
18236 # The directories for the libraries
18237 # (This macro expands the list of CSC to the list of shared libraries, you
18238 # could simply use the expanded form:
18239 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
18240 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
18241
18242 $@{MAIN@}: objects $@{LIB_DIR@}
18243 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
18244 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
18245
18246 objects::
18247 # recompile the sources
18248 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
18249
18250 # Note: In a future version of GNAT, the following commands will be simplified
18251 # by a new tool, gnatmlib
18252 $@{LIB_DIR@}:
18253 mkdir -p $@{dir $@@ @}
18254 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
18255 cd $@{dir $@@ @} && cp -f ../*.ali .
18256
18257 # The dependencies for the modules
18258 # Note that we have to force the expansion of *.o, since in some cases
18259 # make won't be able to do it itself.
18260 aa/lib/libaa.so: $@{wildcard aa/*.o@}
18261 bb/lib/libbb.so: $@{wildcard bb/*.o@}
18262 cc/lib/libcc.so: $@{wildcard cc/*.o@}
18263
18264 # Make sure all of the shared libraries are in the path before starting the
18265 # program
18266 run::
18267 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
18268
18269 clean::
18270 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
18271 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
18272 $@{RM@} $@{CSC_LIST:%=%/*.o@}
18273 $@{RM@} *.o *.ali $@{MAIN@}
18274 @end smallexample
18275
18276 @node Automatically Creating a List of Directories
18277 @section Automatically Creating a List of Directories
18278
18279 @noindent
18280 In most makefiles, you will have to specify a list of directories, and
18281 store it in a variable. For small projects, it is often easier to
18282 specify each of them by hand, since you then have full control over what
18283 is the proper order for these directories, which ones should be
18284 included.
18285
18286 However, in larger projects, which might involve hundreds of
18287 subdirectories, it might be more convenient to generate this list
18288 automatically.
18289
18290 The example below presents two methods. The first one, although less
18291 general, gives you more control over the list. It involves wildcard
18292 characters, that are automatically expanded by @command{make}. Its
18293 shortcoming is that you need to explicitly specify some of the
18294 organization of your project, such as for instance the directory tree
18295 depth, whether some directories are found in a separate tree, @enddots{}
18296
18297 The second method is the most general one. It requires an external
18298 program, called @command{find}, which is standard on all Unix systems. All
18299 the directories found under a given root directory will be added to the
18300 list.
18301
18302 @smallexample
18303 @iftex
18304 @leftskip=0cm
18305 @font@heightrm=cmr8
18306 @heightrm
18307 @end iftex
18308 # The examples below are based on the following directory hierarchy:
18309 # All the directories can contain any number of files
18310 # ROOT_DIRECTORY -> a -> aa -> aaa
18311 # -> ab
18312 # -> ac
18313 # -> b -> ba -> baa
18314 # -> bb
18315 # -> bc
18316 # This Makefile creates a variable called DIRS, that can be reused any time
18317 # you need this list (see the other examples in this section)
18318
18319 # The root of your project's directory hierarchy
18320 ROOT_DIRECTORY=.
18321
18322 ####
18323 # First method: specify explicitly the list of directories
18324 # This allows you to specify any subset of all the directories you need.
18325 ####
18326
18327 DIRS := a/aa/ a/ab/ b/ba/
18328
18329 ####
18330 # Second method: use wildcards
18331 # Note that the argument(s) to wildcard below should end with a '/'.
18332 # Since wildcards also return file names, we have to filter them out
18333 # to avoid duplicate directory names.
18334 # We thus use make's @code{dir} and @code{sort} functions.
18335 # It sets DIRs to the following value (note that the directories aaa and baa
18336 # are not given, unless you change the arguments to wildcard).
18337 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
18338 ####
18339
18340 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
18341 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
18342
18343 ####
18344 # Third method: use an external program
18345 # This command is much faster if run on local disks, avoiding NFS slowdowns.
18346 # This is the most complete command: it sets DIRs to the following value:
18347 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
18348 ####
18349
18350 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
18351
18352 @end smallexample
18353
18354 @node Generating the Command Line Switches
18355 @section Generating the Command Line Switches
18356
18357 @noindent
18358 Once you have created the list of directories as explained in the
18359 previous section (@pxref{Automatically Creating a List of Directories}),
18360 you can easily generate the command line arguments to pass to gnatmake.
18361
18362 For the sake of completeness, this example assumes that the source path
18363 is not the same as the object path, and that you have two separate lists
18364 of directories.
18365
18366 @smallexample
18367 # see "Automatically creating a list of directories" to create
18368 # these variables
18369 SOURCE_DIRS=
18370 OBJECT_DIRS=
18371
18372 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
18373 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
18374
18375 all:
18376 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
18377 @end smallexample
18378
18379 @node Overcoming Command Line Length Limits
18380 @section Overcoming Command Line Length Limits
18381
18382 @noindent
18383 One problem that might be encountered on big projects is that many
18384 operating systems limit the length of the command line. It is thus hard to give
18385 gnatmake the list of source and object directories.
18386
18387 This example shows how you can set up environment variables, which will
18388 make @command{gnatmake} behave exactly as if the directories had been
18389 specified on the command line, but have a much higher length limit (or
18390 even none on most systems).
18391
18392 It assumes that you have created a list of directories in your Makefile,
18393 using one of the methods presented in
18394 @ref{Automatically Creating a List of Directories}.
18395 For the sake of completeness, we assume that the object
18396 path (where the ALI files are found) is different from the sources patch.
18397
18398 Note a small trick in the Makefile below: for efficiency reasons, we
18399 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
18400 expanded immediately by @code{make}. This way we overcome the standard
18401 make behavior which is to expand the variables only when they are
18402 actually used.
18403
18404 On Windows, if you are using the standard Windows command shell, you must
18405 replace colons with semicolons in the assignments to these variables.
18406
18407 @smallexample
18408 @iftex
18409 @leftskip=0cm
18410 @font@heightrm=cmr8
18411 @heightrm
18412 @end iftex
18413 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
18414 # This is the same thing as putting the -I arguments on the command line.
18415 # (the equivalent of using -aI on the command line would be to define
18416 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
18417 # You can of course have different values for these variables.
18418 #
18419 # Note also that we need to keep the previous values of these variables, since
18420 # they might have been set before running 'make' to specify where the GNAT
18421 # library is installed.
18422
18423 # see "Automatically creating a list of directories" to create these
18424 # variables
18425 SOURCE_DIRS=
18426 OBJECT_DIRS=
18427
18428 empty:=
18429 space:=$@{empty@} $@{empty@}
18430 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
18431 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
18432 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
18433 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
18434 export ADA_INCLUDE_PATH
18435 export ADA_OBJECTS_PATH
18436
18437 all:
18438 gnatmake main_unit
18439 @end smallexample
18440 @end ifclear
18441
18442 @node Memory Management Issues
18443 @chapter Memory Management Issues
18444
18445 @noindent
18446 This chapter describes some useful memory pools provided in the GNAT library
18447 and in particular the GNAT Debug Pool facility, which can be used to detect
18448 incorrect uses of access values (including ``dangling references'').
18449 @ifclear vms
18450 It also describes the @command{gnatmem} tool, which can be used to track down
18451 ``memory leaks''.
18452 @end ifclear
18453
18454 @menu
18455 * Some Useful Memory Pools::
18456 * The GNAT Debug Pool Facility::
18457 @ifclear vms
18458 * The gnatmem Tool::
18459 @end ifclear
18460 @end menu
18461
18462 @node Some Useful Memory Pools
18463 @section Some Useful Memory Pools
18464 @findex Memory Pool
18465 @cindex storage, pool
18466
18467 @noindent
18468 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18469 storage pool. Allocations use the standard system call @code{malloc} while
18470 deallocations use the standard system call @code{free}. No reclamation is
18471 performed when the pool goes out of scope. For performance reasons, the
18472 standard default Ada allocators/deallocators do not use any explicit storage
18473 pools but if they did, they could use this storage pool without any change in
18474 behavior. That is why this storage pool is used when the user
18475 manages to make the default implicit allocator explicit as in this example:
18476 @smallexample @c ada
18477 type T1 is access Something;
18478 -- no Storage pool is defined for T2
18479 type T2 is access Something_Else;
18480 for T2'Storage_Pool use T1'Storage_Pool;
18481 -- the above is equivalent to
18482 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18483 @end smallexample
18484
18485 @noindent
18486 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18487 pool. The allocation strategy is similar to @code{Pool_Local}'s
18488 except that the all
18489 storage allocated with this pool is reclaimed when the pool object goes out of
18490 scope. This pool provides a explicit mechanism similar to the implicit one
18491 provided by several Ada 83 compilers for allocations performed through a local
18492 access type and whose purpose was to reclaim memory when exiting the
18493 scope of a given local access. As an example, the following program does not
18494 leak memory even though it does not perform explicit deallocation:
18495
18496 @smallexample @c ada
18497 with System.Pool_Local;
18498 procedure Pooloc1 is
18499 procedure Internal is
18500 type A is access Integer;
18501 X : System.Pool_Local.Unbounded_Reclaim_Pool;
18502 for A'Storage_Pool use X;
18503 v : A;
18504 begin
18505 for I in 1 .. 50 loop
18506 v := new Integer;
18507 end loop;
18508 end Internal;
18509 begin
18510 for I in 1 .. 100 loop
18511 Internal;
18512 end loop;
18513 end Pooloc1;
18514 @end smallexample
18515
18516 @noindent
18517 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
18518 @code{Storage_Size} is specified for an access type.
18519 The whole storage for the pool is
18520 allocated at once, usually on the stack at the point where the access type is
18521 elaborated. It is automatically reclaimed when exiting the scope where the
18522 access type is defined. This package is not intended to be used directly by the
18523 user and it is implicitly used for each such declaration:
18524
18525 @smallexample @c ada
18526 type T1 is access Something;
18527 for T1'Storage_Size use 10_000;
18528 @end smallexample
18529
18530 @node The GNAT Debug Pool Facility
18531 @section The GNAT Debug Pool Facility
18532 @findex Debug Pool
18533 @cindex storage, pool, memory corruption
18534
18535 @noindent
18536 The use of unchecked deallocation and unchecked conversion can easily
18537 lead to incorrect memory references. The problems generated by such
18538 references are usually difficult to tackle because the symptoms can be
18539 very remote from the origin of the problem. In such cases, it is
18540 very helpful to detect the problem as early as possible. This is the
18541 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
18542
18543 In order to use the GNAT specific debugging pool, the user must
18544 associate a debug pool object with each of the access types that may be
18545 related to suspected memory problems. See Ada Reference Manual 13.11.
18546 @smallexample @c ada
18547 type Ptr is access Some_Type;
18548 Pool : GNAT.Debug_Pools.Debug_Pool;
18549 for Ptr'Storage_Pool use Pool;
18550 @end smallexample
18551
18552 @noindent
18553 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18554 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18555 allow the user to redefine allocation and deallocation strategies. They
18556 also provide a checkpoint for each dereference, through the use of
18557 the primitive operation @code{Dereference} which is implicitly called at
18558 each dereference of an access value.
18559
18560 Once an access type has been associated with a debug pool, operations on
18561 values of the type may raise four distinct exceptions,
18562 which correspond to four potential kinds of memory corruption:
18563 @itemize @bullet
18564 @item
18565 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18566 @item
18567 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18568 @item
18569 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18570 @item
18571 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18572 @end itemize
18573
18574 @noindent
18575 For types associated with a Debug_Pool, dynamic allocation is performed using
18576 the standard GNAT allocation routine. References to all allocated chunks of
18577 memory are kept in an internal dictionary. Several deallocation strategies are
18578 provided, whereupon the user can choose to release the memory to the system,
18579 keep it allocated for further invalid access checks, or fill it with an easily
18580 recognizable pattern for debug sessions. The memory pattern is the old IBM
18581 hexadecimal convention: @code{16#DEADBEEF#}.
18582
18583 See the documentation in the file g-debpoo.ads for more information on the
18584 various strategies.
18585
18586 Upon each dereference, a check is made that the access value denotes a
18587 properly allocated memory location. Here is a complete example of use of
18588 @code{Debug_Pools}, that includes typical instances of memory corruption:
18589 @smallexample @c ada
18590 @iftex
18591 @leftskip=0cm
18592 @end iftex
18593 with Gnat.Io; use Gnat.Io;
18594 with Unchecked_Deallocation;
18595 with Unchecked_Conversion;
18596 with GNAT.Debug_Pools;
18597 with System.Storage_Elements;
18598 with Ada.Exceptions; use Ada.Exceptions;
18599 procedure Debug_Pool_Test is
18600
18601 type T is access Integer;
18602 type U is access all T;
18603
18604 P : GNAT.Debug_Pools.Debug_Pool;
18605 for T'Storage_Pool use P;
18606
18607 procedure Free is new Unchecked_Deallocation (Integer, T);
18608 function UC is new Unchecked_Conversion (U, T);
18609 A, B : aliased T;
18610
18611 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
18612
18613 begin
18614 Info (P);
18615 A := new Integer;
18616 B := new Integer;
18617 B := A;
18618 Info (P);
18619 Free (A);
18620 begin
18621 Put_Line (Integer'Image(B.all));
18622 exception
18623 when E : others => Put_Line ("raised: " & Exception_Name (E));
18624 end;
18625 begin
18626 Free (B);
18627 exception
18628 when E : others => Put_Line ("raised: " & Exception_Name (E));
18629 end;
18630 B := UC(A'Access);
18631 begin
18632 Put_Line (Integer'Image(B.all));
18633 exception
18634 when E : others => Put_Line ("raised: " & Exception_Name (E));
18635 end;
18636 begin
18637 Free (B);
18638 exception
18639 when E : others => Put_Line ("raised: " & Exception_Name (E));
18640 end;
18641 Info (P);
18642 end Debug_Pool_Test;
18643 @end smallexample
18644
18645 @noindent
18646 The debug pool mechanism provides the following precise diagnostics on the
18647 execution of this erroneous program:
18648 @smallexample
18649 Debug Pool info:
18650 Total allocated bytes : 0
18651 Total deallocated bytes : 0
18652 Current Water Mark: 0
18653 High Water Mark: 0
18654
18655 Debug Pool info:
18656 Total allocated bytes : 8
18657 Total deallocated bytes : 0
18658 Current Water Mark: 8
18659 High Water Mark: 8
18660
18661 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18662 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18663 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18664 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18665 Debug Pool info:
18666 Total allocated bytes : 8
18667 Total deallocated bytes : 4
18668 Current Water Mark: 4
18669 High Water Mark: 8
18670 @end smallexample
18671
18672 @ifclear vms
18673 @node The gnatmem Tool
18674 @section The @command{gnatmem} Tool
18675 @findex gnatmem
18676
18677 @noindent
18678 The @code{gnatmem} utility monitors dynamic allocation and
18679 deallocation activity in a program, and displays information about
18680 incorrect deallocations and possible sources of memory leaks.
18681 It is designed to work in association with a static runtime library
18682 only and in this context provides three types of information:
18683 @itemize @bullet
18684 @item
18685 General information concerning memory management, such as the total
18686 number of allocations and deallocations, the amount of allocated
18687 memory and the high water mark, i.e.@: the largest amount of allocated
18688 memory in the course of program execution.
18689
18690 @item
18691 Backtraces for all incorrect deallocations, that is to say deallocations
18692 which do not correspond to a valid allocation.
18693
18694 @item
18695 Information on each allocation that is potentially the origin of a memory
18696 leak.
18697 @end itemize
18698
18699 @menu
18700 * Running gnatmem::
18701 * Switches for gnatmem::
18702 * Example of gnatmem Usage::
18703 @end menu
18704
18705 @node Running gnatmem
18706 @subsection Running @code{gnatmem}
18707
18708 @noindent
18709 @code{gnatmem} makes use of the output created by the special version of
18710 allocation and deallocation routines that record call information. This
18711 allows to obtain accurate dynamic memory usage history at a minimal cost to
18712 the execution speed. Note however, that @code{gnatmem} is not supported on
18713 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
18714 Solaris and Windows NT/2000/XP (x86).
18715
18716 @noindent
18717 The @code{gnatmem} command has the form
18718
18719 @smallexample
18720 @c $ gnatmem @ovar{switches} user_program
18721 @c Expanding @ovar macro inline (explanation in macro def comments)
18722 $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
18723 @end smallexample
18724
18725 @noindent
18726 The program must have been linked with the instrumented version of the
18727 allocation and deallocation routines. This is done by linking with the
18728 @file{libgmem.a} library. For correct symbolic backtrace information,
18729 the user program should be compiled with debugging options
18730 (see @ref{Switches for gcc}). For example to build @file{my_program}:
18731
18732 @smallexample
18733 $ gnatmake -g my_program -largs -lgmem
18734 @end smallexample
18735
18736 @noindent
18737 As library @file{libgmem.a} contains an alternate body for package
18738 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
18739 when an executable is linked with library @file{libgmem.a}. It is then not
18740 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
18741
18742 @noindent
18743 When @file{my_program} is executed, the file @file{gmem.out} is produced.
18744 This file contains information about all allocations and deallocations
18745 performed by the program. It is produced by the instrumented allocations and
18746 deallocations routines and will be used by @code{gnatmem}.
18747
18748 In order to produce symbolic backtrace information for allocations and
18749 deallocations performed by the GNAT run-time library, you need to use a
18750 version of that library that has been compiled with the @option{-g} switch
18751 (see @ref{Rebuilding the GNAT Run-Time Library}).
18752
18753 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18754 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18755 @option{-i} switch, gnatmem will assume that this file can be found in the
18756 current directory. For example, after you have executed @file{my_program},
18757 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18758
18759 @smallexample
18760 $ gnatmem my_program
18761 @end smallexample
18762
18763 @noindent
18764 This will produce the output with the following format:
18765
18766 *************** debut cc
18767 @smallexample
18768 $ gnatmem my_program
18769
18770 Global information
18771 ------------------
18772 Total number of allocations : 45
18773 Total number of deallocations : 6
18774 Final Water Mark (non freed mem) : 11.29 Kilobytes
18775 High Water Mark : 11.40 Kilobytes
18776
18777 .
18778 .
18779 .
18780 Allocation Root # 2
18781 -------------------
18782 Number of non freed allocations : 11
18783 Final Water Mark (non freed mem) : 1.16 Kilobytes
18784 High Water Mark : 1.27 Kilobytes
18785 Backtrace :
18786 my_program.adb:23 my_program.alloc
18787 .
18788 .
18789 .
18790 @end smallexample
18791
18792 The first block of output gives general information. In this case, the
18793 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18794 Unchecked_Deallocation routine occurred.
18795
18796 @noindent
18797 Subsequent paragraphs display information on all allocation roots.
18798 An allocation root is a specific point in the execution of the program
18799 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18800 construct. This root is represented by an execution backtrace (or subprogram
18801 call stack). By default the backtrace depth for allocations roots is 1, so
18802 that a root corresponds exactly to a source location. The backtrace can
18803 be made deeper, to make the root more specific.
18804
18805 @node Switches for gnatmem
18806 @subsection Switches for @code{gnatmem}
18807
18808 @noindent
18809 @code{gnatmem} recognizes the following switches:
18810
18811 @table @option
18812
18813 @item -q
18814 @cindex @option{-q} (@code{gnatmem})
18815 Quiet. Gives the minimum output needed to identify the origin of the
18816 memory leaks. Omits statistical information.
18817
18818 @item @var{N}
18819 @cindex @var{N} (@code{gnatmem})
18820 N is an integer literal (usually between 1 and 10) which controls the
18821 depth of the backtraces defining allocation root. The default value for
18822 N is 1. The deeper the backtrace, the more precise the localization of
18823 the root. Note that the total number of roots can depend on this
18824 parameter. This parameter must be specified @emph{before} the name of the
18825 executable to be analyzed, to avoid ambiguity.
18826
18827 @item -b n
18828 @cindex @option{-b} (@code{gnatmem})
18829 This switch has the same effect as just depth parameter.
18830
18831 @item -i @var{file}
18832 @cindex @option{-i} (@code{gnatmem})
18833 Do the @code{gnatmem} processing starting from @file{file}, rather than
18834 @file{gmem.out} in the current directory.
18835
18836 @item -m n
18837 @cindex @option{-m} (@code{gnatmem})
18838 This switch causes @code{gnatmem} to mask the allocation roots that have less
18839 than n leaks. The default value is 1. Specifying the value of 0 will allow to
18840 examine even the roots that didn't result in leaks.
18841
18842 @item -s order
18843 @cindex @option{-s} (@code{gnatmem})
18844 This switch causes @code{gnatmem} to sort the allocation roots according to the
18845 specified order of sort criteria, each identified by a single letter. The
18846 currently supported criteria are @code{n, h, w} standing respectively for
18847 number of unfreed allocations, high watermark, and final watermark
18848 corresponding to a specific root. The default order is @code{nwh}.
18849
18850 @end table
18851
18852 @node Example of gnatmem Usage
18853 @subsection Example of @code{gnatmem} Usage
18854
18855 @noindent
18856 The following example shows the use of @code{gnatmem}
18857 on a simple memory-leaking program.
18858 Suppose that we have the following Ada program:
18859
18860 @smallexample @c ada
18861 @group
18862 @cartouche
18863 with Unchecked_Deallocation;
18864 procedure Test_Gm is
18865
18866 type T is array (1..1000) of Integer;
18867 type Ptr is access T;
18868 procedure Free is new Unchecked_Deallocation (T, Ptr);
18869 A : Ptr;
18870
18871 procedure My_Alloc is
18872 begin
18873 A := new T;
18874 end My_Alloc;
18875
18876 procedure My_DeAlloc is
18877 B : Ptr := A;
18878 begin
18879 Free (B);
18880 end My_DeAlloc;
18881
18882 begin
18883 My_Alloc;
18884 for I in 1 .. 5 loop
18885 for J in I .. 5 loop
18886 My_Alloc;
18887 end loop;
18888 My_Dealloc;
18889 end loop;
18890 end;
18891 @end cartouche
18892 @end group
18893 @end smallexample
18894
18895 @noindent
18896 The program needs to be compiled with debugging option and linked with
18897 @code{gmem} library:
18898
18899 @smallexample
18900 $ gnatmake -g test_gm -largs -lgmem
18901 @end smallexample
18902
18903 @noindent
18904 Then we execute the program as usual:
18905
18906 @smallexample
18907 $ test_gm
18908 @end smallexample
18909
18910 @noindent
18911 Then @code{gnatmem} is invoked simply with
18912 @smallexample
18913 $ gnatmem test_gm
18914 @end smallexample
18915
18916 @noindent
18917 which produces the following output (result may vary on different platforms):
18918
18919 @smallexample
18920 Global information
18921 ------------------
18922 Total number of allocations : 18
18923 Total number of deallocations : 5
18924 Final Water Mark (non freed mem) : 53.00 Kilobytes
18925 High Water Mark : 56.90 Kilobytes
18926
18927 Allocation Root # 1
18928 -------------------
18929 Number of non freed allocations : 11
18930 Final Water Mark (non freed mem) : 42.97 Kilobytes
18931 High Water Mark : 46.88 Kilobytes
18932 Backtrace :
18933 test_gm.adb:11 test_gm.my_alloc
18934
18935 Allocation Root # 2
18936 -------------------
18937 Number of non freed allocations : 1
18938 Final Water Mark (non freed mem) : 10.02 Kilobytes
18939 High Water Mark : 10.02 Kilobytes
18940 Backtrace :
18941 s-secsta.adb:81 system.secondary_stack.ss_init
18942
18943 Allocation Root # 3
18944 -------------------
18945 Number of non freed allocations : 1
18946 Final Water Mark (non freed mem) : 12 Bytes
18947 High Water Mark : 12 Bytes
18948 Backtrace :
18949 s-secsta.adb:181 system.secondary_stack.ss_init
18950 @end smallexample
18951
18952 @noindent
18953 Note that the GNAT run time contains itself a certain number of
18954 allocations that have no corresponding deallocation,
18955 as shown here for root #2 and root
18956 #3. This is a normal behavior when the number of non-freed allocations
18957 is one, it allocates dynamic data structures that the run time needs for
18958 the complete lifetime of the program. Note also that there is only one
18959 allocation root in the user program with a single line back trace:
18960 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18961 program shows that 'My_Alloc' is called at 2 different points in the
18962 source (line 21 and line 24). If those two allocation roots need to be
18963 distinguished, the backtrace depth parameter can be used:
18964
18965 @smallexample
18966 $ gnatmem 3 test_gm
18967 @end smallexample
18968
18969 @noindent
18970 which will give the following output:
18971
18972 @smallexample
18973 Global information
18974 ------------------
18975 Total number of allocations : 18
18976 Total number of deallocations : 5
18977 Final Water Mark (non freed mem) : 53.00 Kilobytes
18978 High Water Mark : 56.90 Kilobytes
18979
18980 Allocation Root # 1
18981 -------------------
18982 Number of non freed allocations : 10
18983 Final Water Mark (non freed mem) : 39.06 Kilobytes
18984 High Water Mark : 42.97 Kilobytes
18985 Backtrace :
18986 test_gm.adb:11 test_gm.my_alloc
18987 test_gm.adb:24 test_gm
18988 b_test_gm.c:52 main
18989
18990 Allocation Root # 2
18991 -------------------
18992 Number of non freed allocations : 1
18993 Final Water Mark (non freed mem) : 10.02 Kilobytes
18994 High Water Mark : 10.02 Kilobytes
18995 Backtrace :
18996 s-secsta.adb:81 system.secondary_stack.ss_init
18997 s-secsta.adb:283 <system__secondary_stack___elabb>
18998 b_test_gm.c:33 adainit
18999
19000 Allocation Root # 3
19001 -------------------
19002 Number of non freed allocations : 1
19003 Final Water Mark (non freed mem) : 3.91 Kilobytes
19004 High Water Mark : 3.91 Kilobytes
19005 Backtrace :
19006 test_gm.adb:11 test_gm.my_alloc
19007 test_gm.adb:21 test_gm
19008 b_test_gm.c:52 main
19009
19010 Allocation Root # 4
19011 -------------------
19012 Number of non freed allocations : 1
19013 Final Water Mark (non freed mem) : 12 Bytes
19014 High Water Mark : 12 Bytes
19015 Backtrace :
19016 s-secsta.adb:181 system.secondary_stack.ss_init
19017 s-secsta.adb:283 <system__secondary_stack___elabb>
19018 b_test_gm.c:33 adainit
19019 @end smallexample
19020
19021 @noindent
19022 The allocation root #1 of the first example has been split in 2 roots #1
19023 and #3 thanks to the more precise associated backtrace.
19024
19025 @end ifclear
19026
19027 @node Stack Related Facilities
19028 @chapter Stack Related Facilities
19029
19030 @noindent
19031 This chapter describes some useful tools associated with stack
19032 checking and analysis. In
19033 particular, it deals with dynamic and static stack usage measurements.
19034
19035 @menu
19036 * Stack Overflow Checking::
19037 * Static Stack Usage Analysis::
19038 * Dynamic Stack Usage Analysis::
19039 @end menu
19040
19041 @node Stack Overflow Checking
19042 @section Stack Overflow Checking
19043 @cindex Stack Overflow Checking
19044 @cindex -fstack-check
19045
19046 @noindent
19047 For most operating systems, @command{gcc} does not perform stack overflow
19048 checking by default. This means that if the main environment task or
19049 some other task exceeds the available stack space, then unpredictable
19050 behavior will occur. Most native systems offer some level of protection by
19051 adding a guard page at the end of each task stack. This mechanism is usually
19052 not enough for dealing properly with stack overflow situations because
19053 a large local variable could ``jump'' above the guard page.
19054 Furthermore, when the
19055 guard page is hit, there may not be any space left on the stack for executing
19056 the exception propagation code. Enabling stack checking avoids
19057 such situations.
19058
19059 To activate stack checking, compile all units with the gcc option
19060 @option{-fstack-check}. For example:
19061
19062 @smallexample
19063 gcc -c -fstack-check package1.adb
19064 @end smallexample
19065
19066 @noindent
19067 Units compiled with this option will generate extra instructions to check
19068 that any use of the stack (for procedure calls or for declaring local
19069 variables in declare blocks) does not exceed the available stack space.
19070 If the space is exceeded, then a @code{Storage_Error} exception is raised.
19071
19072 For declared tasks, the stack size is controlled by the size
19073 given in an applicable @code{Storage_Size} pragma or by the value specified
19074 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
19075 the default size as defined in the GNAT runtime otherwise.
19076
19077 For the environment task, the stack size depends on
19078 system defaults and is unknown to the compiler. Stack checking
19079 may still work correctly if a fixed
19080 size stack is allocated, but this cannot be guaranteed.
19081 @ifclear vms
19082 To ensure that a clean exception is signalled for stack
19083 overflow, set the environment variable
19084 @env{GNAT_STACK_LIMIT} to indicate the maximum
19085 stack area that can be used, as in:
19086 @cindex GNAT_STACK_LIMIT
19087
19088 @smallexample
19089 SET GNAT_STACK_LIMIT 1600
19090 @end smallexample
19091
19092 @noindent
19093 The limit is given in kilobytes, so the above declaration would
19094 set the stack limit of the environment task to 1.6 megabytes.
19095 Note that the only purpose of this usage is to limit the amount
19096 of stack used by the environment task. If it is necessary to
19097 increase the amount of stack for the environment task, then this
19098 is an operating systems issue, and must be addressed with the
19099 appropriate operating systems commands.
19100 @end ifclear
19101 @ifset vms
19102 To have a fixed size stack in the environment task, the stack must be put
19103 in the P0 address space and its size specified. Use these switches to
19104 create a p0 image:
19105
19106 @smallexample
19107 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
19108 @end smallexample
19109
19110 @noindent
19111 The quotes are required to keep case. The number after @samp{STACK=} is the
19112 size of the environmental task stack in pagelets (512 bytes). In this example
19113 the stack size is about 2 megabytes.
19114
19115 @noindent
19116 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
19117 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
19118 more details about the @option{/p0image} qualifier and the @option{stack}
19119 option.
19120
19121 @noindent
19122 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
19123 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
19124 stack in kilobytes. For example:
19125
19126 @smallexample
19127 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
19128 @end smallexample
19129 @end ifset
19130
19131 @node Static Stack Usage Analysis
19132 @section Static Stack Usage Analysis
19133 @cindex Static Stack Usage Analysis
19134 @cindex -fstack-usage
19135
19136 @noindent
19137 A unit compiled with @option{-fstack-usage} will generate an extra file
19138 that specifies
19139 the maximum amount of stack used, on a per-function basis.
19140 The file has the same
19141 basename as the target object file with a @file{.su} extension.
19142 Each line of this file is made up of three fields:
19143
19144 @itemize
19145 @item
19146 The name of the function.
19147 @item
19148 A number of bytes.
19149 @item
19150 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
19151 @end itemize
19152
19153 The second field corresponds to the size of the known part of the function
19154 frame.
19155
19156 The qualifier @code{static} means that the function frame size
19157 is purely static.
19158 It usually means that all local variables have a static size.
19159 In this case, the second field is a reliable measure of the function stack
19160 utilization.
19161
19162 The qualifier @code{dynamic} means that the function frame size is not static.
19163 It happens mainly when some local variables have a dynamic size. When this
19164 qualifier appears alone, the second field is not a reliable measure
19165 of the function stack analysis. When it is qualified with @code{bounded}, it
19166 means that the second field is a reliable maximum of the function stack
19167 utilization.
19168
19169 A unit compiled with @option{-Wstack-usage} will issue a warning for each
19170 subprogram whose stack usage might be larger than the specified amount of
19171 bytes. The wording is in keeping with the qualifier documented above.
19172
19173 @node Dynamic Stack Usage Analysis
19174 @section Dynamic Stack Usage Analysis
19175
19176 @noindent
19177 It is possible to measure the maximum amount of stack used by a task, by
19178 adding a switch to @command{gnatbind}, as:
19179
19180 @smallexample
19181 $ gnatbind -u0 file
19182 @end smallexample
19183
19184 @noindent
19185 With this option, at each task termination, its stack usage is output on
19186 @file{stderr}.
19187 It is not always convenient to output the stack usage when the program
19188 is still running. Hence, it is possible to delay this output until program
19189 termination. for a given number of tasks specified as the argument of the
19190 @option{-u} option. For instance:
19191
19192 @smallexample
19193 $ gnatbind -u100 file
19194 @end smallexample
19195
19196 @noindent
19197 will buffer the stack usage information of the first 100 tasks to terminate and
19198 output this info at program termination. Results are displayed in four
19199 columns:
19200
19201 @noindent
19202 Index | Task Name | Stack Size | Stack Usage
19203
19204 @noindent
19205 where:
19206
19207 @table @emph
19208 @item Index
19209 is a number associated with each task.
19210
19211 @item Task Name
19212 is the name of the task analyzed.
19213
19214 @item Stack Size
19215 is the maximum size for the stack.
19216
19217 @item Stack Usage
19218 is the measure done by the stack analyzer. In order to prevent overflow, the stack
19219 is not entirely analyzed, and it's not possible to know exactly how
19220 much has actually been used.
19221
19222 @end table
19223
19224 @noindent
19225 The environment task stack, e.g., the stack that contains the main unit, is
19226 only processed when the environment variable GNAT_STACK_LIMIT is set.
19227
19228 @noindent
19229 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
19230 stack usage reports at run-time. See its body for the details.
19231
19232 @c *********************************
19233 @c * GNATCHECK *
19234 @c *********************************
19235 @node Verifying Properties with gnatcheck
19236 @chapter Verifying Properties with @command{gnatcheck}
19237 @findex gnatcheck
19238 @cindex @command{gnatcheck}
19239
19240 @noindent
19241 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
19242 of Ada source files according to a given set of semantic rules.
19243 @cindex ASIS
19244
19245 In order to check compliance with a given rule, @command{gnatcheck} has to
19246 semantically analyze the Ada sources.
19247 Therefore, checks can only be performed on
19248 legal Ada units. Moreover, when a unit depends semantically upon units located
19249 outside the current directory, the source search path has to be provided when
19250 calling @command{gnatcheck}, either through a specified project file or
19251 through @command{gnatcheck} switches.
19252
19253 For full details, refer to @cite{GNATcheck Reference Manual} document.
19254
19255
19256 @c *********************************
19257 @node Creating Sample Bodies with gnatstub
19258 @chapter Creating Sample Bodies with @command{gnatstub}
19259 @findex gnatstub
19260
19261 @noindent
19262 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
19263 for library unit declarations.
19264
19265 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
19266 driver (see @ref{The GNAT Driver and Project Files}).
19267
19268 To create a body stub, @command{gnatstub} has to compile the library
19269 unit declaration. Therefore, bodies can be created only for legal
19270 library units. Moreover, if a library unit depends semantically upon
19271 units located outside the current directory, you have to provide
19272 the source search path when calling @command{gnatstub}, see the description
19273 of @command{gnatstub} switches below.
19274
19275 By default, all the program unit body stubs generated by @code{gnatstub}
19276 raise the predefined @code{Program_Error} exception, which will catch
19277 accidental calls of generated stubs. This behavior can be changed with
19278 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
19279
19280 @menu
19281 * Running gnatstub::
19282 * Switches for gnatstub::
19283 @end menu
19284
19285 @node Running gnatstub
19286 @section Running @command{gnatstub}
19287
19288 @noindent
19289 @command{gnatstub} has a command-line interface of the form:
19290
19291 @smallexample
19292 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
19293 @c Expanding @ovar macro inline (explanation in macro def comments)
19294 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19295 @end smallexample
19296
19297 @noindent
19298 where
19299 @table @var
19300 @item filename
19301 is the name of the source file that contains a library unit declaration
19302 for which a body must be created. The file name may contain the path
19303 information.
19304 The file name does not have to follow the GNAT file name conventions. If the
19305 name
19306 does not follow GNAT file naming conventions, the name of the body file must
19307 be provided
19308 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
19309 If the file name follows the GNAT file naming
19310 conventions and the name of the body file is not provided,
19311 @command{gnatstub}
19312 creates the name
19313 of the body file from the argument file name by replacing the @file{.ads}
19314 suffix
19315 with the @file{.adb} suffix.
19316
19317 @item directory
19318 indicates the directory in which the body stub is to be placed (the default
19319 is the
19320 current directory)
19321
19322 @item @samp{@var{gcc_switches}} is a list of switches for
19323 @command{gcc}. They will be passed on to all compiler invocations made by
19324 @command{gnatstub} to generate the ASIS trees. Here you can provide
19325 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19326 use the @option{-gnatec} switch to set the configuration file,
19327 use the @option{-gnat05} switch if sources should be compiled in
19328 Ada 2005 mode etc.
19329
19330 @item switches
19331 is an optional sequence of switches as described in the next section
19332 @end table
19333
19334 @node Switches for gnatstub
19335 @section Switches for @command{gnatstub}
19336
19337 @table @option
19338 @c !sort!
19339
19340 @item --version
19341 @cindex @option{--version} @command{gnatstub}
19342 Display Copyright and version, then exit disregarding all other options.
19343
19344 @item --help
19345 @cindex @option{--help} @command{gnatstub}
19346 Display usage, then exit disregarding all other options.
19347
19348 @item ^-f^/FULL^
19349 @cindex @option{^-f^/FULL^} (@command{gnatstub})
19350 If the destination directory already contains a file with the name of the
19351 body file
19352 for the argument spec file, replace it with the generated body stub.
19353
19354 @item ^-hs^/HEADER=SPEC^
19355 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
19356 Put the comment header (i.e., all the comments preceding the
19357 compilation unit) from the source of the library unit declaration
19358 into the body stub.
19359
19360 @item ^-hg^/HEADER=GENERAL^
19361 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
19362 Put a sample comment header into the body stub.
19363
19364 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
19365 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
19366 Use the content of the file as the comment header for a generated body stub.
19367
19368 @ifclear vms
19369 @item -IDIR
19370 @cindex @option{-IDIR} (@command{gnatstub})
19371 @itemx -I-
19372 @cindex @option{-I-} (@command{gnatstub})
19373 @end ifclear
19374 @ifset vms
19375 @item /NOCURRENT_DIRECTORY
19376 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
19377 @end ifset
19378 ^These switches have ^This switch has^ the same meaning as in calls to
19379 @command{gcc}.
19380 ^They define ^It defines ^ the source search path in the call to
19381 @command{gcc} issued
19382 by @command{gnatstub} to compile an argument source file.
19383
19384 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
19385 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
19386 This switch has the same meaning as in calls to @command{gcc}.
19387 It defines the additional configuration file to be passed to the call to
19388 @command{gcc} issued
19389 by @command{gnatstub} to compile an argument source file.
19390
19391 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
19392 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
19393 (@var{n} is a non-negative integer). Set the maximum line length that is
19394 allowed in a source file. The default is 79. The maximum value that can be
19395 specified is 32767. Note that in the special case of configuration
19396 pragma files, the maximum is always 32767 regardless of whether or
19397 not this switch appears.
19398
19399 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
19400 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
19401 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
19402 the generated body sample to @var{n}.
19403 The default indentation is 3.
19404
19405 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
19406 @cindex @option{^-gnatyo^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
19407 Order local bodies alphabetically. (By default local bodies are ordered
19408 in the same way as the corresponding local specs in the argument spec file.)
19409
19410 @item ^-i^/INDENTATION=^@var{n}
19411 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
19412 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
19413
19414 @item ^-k^/TREE_FILE=SAVE^
19415 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
19416 Do not remove the tree file (i.e., the snapshot of the compiler internal
19417 structures used by @command{gnatstub}) after creating the body stub.
19418
19419 @item ^-l^/LINE_LENGTH=^@var{n}
19420 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
19421 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
19422
19423 @item ^--no-exception^/NO_EXCEPTION^
19424 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
19425 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
19426 This is not always possible for function stubs.
19427
19428 @item ^--no-local-header^/NO_LOCAL_HEADER^
19429 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
19430 Do not place local comment header with unit name before body stub for a
19431 unit.
19432
19433 @item ^-o ^/BODY=^@var{body-name}
19434 @cindex @option{^-o^/BODY^} (@command{gnatstub})
19435 Body file name. This should be set if the argument file name does not
19436 follow
19437 the GNAT file naming
19438 conventions. If this switch is omitted the default name for the body will be
19439 obtained
19440 from the argument file name according to the GNAT file naming conventions.
19441
19442 @item ^-q^/QUIET^
19443 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
19444 Quiet mode: do not generate a confirmation when a body is
19445 successfully created, and do not generate a message when a body is not
19446 required for an
19447 argument unit.
19448
19449 @item ^-r^/TREE_FILE=REUSE^
19450 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
19451 Reuse the tree file (if it exists) instead of creating it. Instead of
19452 creating the tree file for the library unit declaration, @command{gnatstub}
19453 tries to find it in the current directory and use it for creating
19454 a body. If the tree file is not found, no body is created. This option
19455 also implies @option{^-k^/SAVE^}, whether or not
19456 the latter is set explicitly.
19457
19458 @item ^-t^/TREE_FILE=OVERWRITE^
19459 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
19460 Overwrite the existing tree file. If the current directory already
19461 contains the file which, according to the GNAT file naming rules should
19462 be considered as a tree file for the argument source file,
19463 @command{gnatstub}
19464 will refuse to create the tree file needed to create a sample body
19465 unless this option is set.
19466
19467 @item ^-v^/VERBOSE^
19468 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
19469 Verbose mode: generate version information.
19470
19471 @end table
19472
19473 @c *********************************
19474 @node Creating Unit Tests with gnattest
19475 @chapter Creating Unit Tests with @command{gnattest}
19476 @findex gnattest
19477
19478 @noindent
19479 @command{gnattest} is an ASIS-based utility that creates unit-test skeletons
19480 as well as a test driver infrastructure (harness). @command{gnattest} creates
19481 a skeleton for each visible subprogram in the packages under consideration when
19482 they do not exist already.
19483
19484 In order to process source files from a project, @command{gnattest} has to
19485 semantically analyze the sources. Therefore, test skeletons can only be
19486 generated for legal Ada units. If a unit is dependent on other units,
19487 those units should be among the source files of the project or of other projects
19488 imported by this one.
19489
19490 Generated skeletons and harnesses are based on the AUnit testing framework.
19491 AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit
19492 for Java or CppUnit for C++. While it is advised that gnattest users read
19493 the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest.
19494 For correct operation of @command{gnattest}, AUnit should be installed and
19495 aunit.gpr must be on the project path. This happens automatically when Aunit
19496 is installed at its default location.
19497 @menu
19498 * Running gnattest::
19499 * Switches for gnattest::
19500 * Project Attributes for gnattest::
19501 * Simple Example::
19502 * Setting Up and Tearing Down the Testing Environment::
19503 * Regenerating Tests::
19504 * Default Test Behavior::
19505 * Testing Primitive Operations of Tagged Types::
19506 * Testing Inheritance::
19507 * Tagged Types Substitutability Testing::
19508 * Testing with Contracts::
19509 * Additional Tests::
19510 @ifclear vms
19511 * Support for other platforms/run-times::
19512 @end ifclear
19513 * Current Limitations::
19514 @end menu
19515
19516 @node Running gnattest
19517 @section Running @command{gnattest}
19518
19519 @noindent
19520 @command{gnattest} has a command-line interface of the form
19521
19522 @smallexample
19523 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
19524 @c Expanding @ovar macro inline (explanation in macro def comments)
19525 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19526 @end smallexample
19527
19528 @noindent
19529 where
19530 @table @var
19531
19532 @item -Pprojname
19533 specifies the project defining the location of source files. When no
19534 file names are provided on the command line, all sources in the project
19535 are used as input. This switch is required.
19536
19537 @item filename
19538 is the name of the source file containing the library unit package declaration
19539 for which a test package will be created. The file name may be given with a
19540 path.
19541
19542 @item @samp{@var{gcc_switches}}
19543 is a list of switches for
19544 @command{gcc}. These switches will be passed on to all compiler invocations
19545 made by @command{gnattest} to generate a set of ASIS trees. Here you can provide
19546 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19547 use the @option{-gnatec} switch to set the configuration file,
19548 use the @option{-gnat05} switch if sources should be compiled in
19549 Ada 2005 mode, etc.
19550
19551 @item switches
19552 is an optional sequence of switches as described in the next section.
19553
19554 @end table
19555
19556 @command{gnattest} results can be found in two different places.
19557
19558 @itemize @bullet
19559 @item automatic harness:
19560 the harness code, which is located by default in "gnattest/harness" directory
19561 that is created in the object directory of corresponding project file. All of
19562 this code is generated completely automatically and can be destroyed and
19563 regenerated at will. It is not recommended to modify this code manually, since
19564 it could easily be overridden by mistake. The entry point in the harness code is
19565 the project file named @command{test_driver.gpr}. Tests can be compiled and run
19566 using a command such as:
19567
19568 @smallexample
19569 gnatmake -P<harness-dir>/test_driver
19570 test_runner
19571 @end smallexample
19572
19573 Note that you might need to specify the necessary values of scenario variables
19574 when you are not using the AUnit defaults.
19575
19576 @item actual unit test skeletons:
19577 a test skeleton for each visible subprogram is created in a separate file, if it
19578 doesn't exist already. By default, those separate test files are located in a
19579 "gnattest/tests" directory that is created in the object directory of
19580 corresponding project file. For example, if a source file my_unit.ads in
19581 directory src contains a visible subprogram Proc, then the corresponding unit
19582 test will be found in file src/tests/my_unit-test_data-tests-proc_<code>.adb.
19583 <code> is a signature encoding used to differentiate test names in case of
19584 overloading.
19585
19586 Note that if the project already has both my_unit.ads and my_unit-test_data.ads,
19587 this will cause a name conflict with the generated test package.
19588 @end itemize
19589
19590 @node Switches for gnattest
19591 @section Switches for @command{gnattest}
19592
19593 @table @option
19594 @c !sort!
19595
19596 @item --harness-only
19597 @cindex @option{--harness-only} (@command{gnattest})
19598 When this option is given, @command{gnattest} creates a harness for all
19599 sources, treating them as test packages.
19600
19601 @item --additional-tests=@var{projname}
19602 @cindex @option{--additional-tests} (@command{gnattest})
19603 Sources described in @var{projname} are considered potential additional
19604 manual tests to be added to the test suite.
19605
19606 @item -r
19607 @cindex @option{-r} (@command{gnattest})
19608 Recursively consider all sources from all projects.
19609
19610 @item -X@var{name=value}
19611 @cindex @option{-X} (@command{gnattest})
19612 Indicate that external variable @var{name} has the value @var{value}.
19613
19614 @item -q
19615 @cindex @option{-q} (@command{gnattest})
19616 Suppresses noncritical output messages.
19617
19618 @item -v
19619 @cindex @option{-v} (@command{gnattest})
19620 Verbose mode: generates version information.
19621
19622 @item --validate-type-extensions
19623 @cindex @option{--validate-type-extensions} (@command{gnattest})
19624 Enables substitution check: run all tests from all parents in order
19625 to check substitutability.
19626
19627 @item --skeleton-default=@var{val}
19628 @cindex @option{--skeleton-default} (@command{gnattest})
19629 Specifies the default behavior of generated skeletons. @var{val} can be either
19630 "fail" or "pass", "fail" being the default.
19631
19632 @item --passed-tests=@var{val}
19633 @cindex @option{--skeleton-default} (@command{gnattest})
19634 Specifies whether or not passed tests should be shown. @var{val} can be either
19635 "show" or "hide", "show" being the default.
19636
19637
19638 @item --tests-root=@var{dirname}
19639 @cindex @option{--tests-root} (@command{gnattest})
19640 The directory hierarchy of tested sources is recreated in the @var{dirname}
19641 directory, and test packages are placed in corresponding directories.
19642 If the @var{dirname} is a relative path, it is considered relative to the object
19643 directory of the project file. When all sources from all projects are taken
19644 recursively from all projects, directory hierarchies of tested sources are
19645 recreated for each project in their object directories and test packages are
19646 placed accordingly.
19647
19648 @item --subdir=@var{dirname}
19649 @cindex @option{--subdir} (@command{gnattest})
19650 Test packages are placed in subdirectories.
19651
19652 @item --tests-dir=@var{dirname}
19653 @cindex @option{--tests-dir} (@command{gnattest})
19654 All test packages are placed in the @var{dirname} directory.
19655 If the @var{dirname} is a relative path, it is considered relative to the object
19656 directory of the project file. When all sources from all projects are taken
19657 recursively from all projects, @var{dirname} directories are created for each
19658 project in their object directories and test packages are placed accordingly.
19659
19660 @item --harness-dir=@var{dirname}
19661 @cindex @option{--harness-dir} (@command{gnattest})
19662 specifies the directory that will hold the harness packages and project file
19663 for the test driver. If the @var{dirname} is a relative path, it is considered
19664 relative to the object directory of the project file.
19665
19666 @item --separates
19667 @cindex @option{--separates} (@command{gnattest})
19668 Bodies of all test routines are generated as separates. Note that this mode is
19669 kept for compatibility reasons only and it is not advised to use it due to
19670 possible problems with hash in names of test skeletons when using an
19671 inconsistent casing. Separate test skeletons can be incorporated to monolith
19672 test package with improved hash being used by using @option{--transition}
19673 switch.
19674
19675
19676 @item --transition
19677 @cindex @option{--transition} (@command{gnattest})
19678 This allows transition from separate test routines to monolith test packages.
19679 All matching test routines are overwritten with contents of corresponding
19680 separates. Note that if separate test routines had any manually added with
19681 clauses they will be moved to the test package body as is and have to be moved
19682 by hand.
19683
19684 @end table
19685
19686 @option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are
19687 mutually exclusive.
19688
19689 @node Project Attributes for gnattest
19690 @section Project Attributes for @command{gnattest}
19691
19692 @noindent
19693
19694 Most of the command-line options can also be passed to the tool by adding
19695 special attributes to the project file. Those attributes should be put in
19696 package gnattest. Here is the list of attributes:
19697
19698 @itemize @bullet
19699
19700 @item Tests_Root
19701 is used to select the same output mode as with the --tests-root option.
19702 This attribute cannot be used together with Subdir or Tests_Dir.
19703
19704 @item Subdir
19705 is used to select the same output mode as with the --subdir option.
19706 This attribute cannot be used together with Tests_Root or Tests_Dir.
19707
19708 @item Tests_Dir
19709 is used to select the same output mode as with the --tests-dir option.
19710 This attribute cannot be used together with Subdir or Tests_Root.
19711
19712 @item Harness_Dir
19713 is used to specify the directory in which to place harness packages and project
19714 file for the test driver, otherwise specified by --harness-dir.
19715
19716 @item Additional_Tests
19717 is used to specify the project file, otherwise given by
19718 --additional-tests switch.
19719
19720 @item Skeletons_Default
19721 is used to specify the default behaviour of test skeletons, otherwise
19722 specified by --skeleton-default option. The value of this attribute
19723 should be either "pass" or "fail".
19724
19725 @end itemize
19726
19727 Each of those attributes can be overridden from the command line if needed.
19728 Other @command{gnattest} switches can also be passed via the project
19729 file as an attribute list called GNATtest_Switches.
19730
19731 @node Simple Example
19732 @section Simple Example
19733
19734 @noindent
19735
19736 Let's take a very simple example using the first @command{gnattest} example
19737 located in:
19738
19739 @smallexample
19740 <install_prefix>/share/examples/gnattest/simple
19741 @end smallexample
19742
19743 This project contains a simple package containing one subprogram. By running gnattest:
19744
19745 @smallexample
19746 $ gnattest --harness-dir=driver -Psimple.gpr
19747 @end smallexample
19748
19749 a test driver is created in directory "driver". It can be compiled and run:
19750
19751 @smallexample
19752 $ cd obj/driver
19753 $ gnatmake -Ptest_driver
19754 $ test_runner
19755 @end smallexample
19756
19757 One failed test with diagnosis "test not implemented" is reported.
19758 Since no special output option was specified, the test package Simple.Tests
19759 is located in:
19760
19761 @smallexample
19762 <install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
19763 @end smallexample
19764
19765 For each package containing visible subprograms, a child test package is
19766 generated. It contains one test routine per tested subprogram. Each
19767 declaration of a test subprogram has a comment specifying which tested
19768 subprogram it corresponds to. Bodies of test routines are placed in test package
19769 bodies and are surrounded by special comment sections. Those comment sections
19770 should not be removed or modified in order for gnattest to be able to regenerate
19771 test packages and keep already written tests in place.
19772 The test routine Test_Inc_5eaee3 located at simple-test_data-tests.adb contains
19773 a single statement: a call to procedure Assert. It has two arguments:
19774 the Boolean expression we want to check and the diagnosis message to display if
19775 the condition is false.
19776
19777 That is where actual testing code should be written after a proper setup.
19778 An actual check can be performed by replacing the Assert call with:
19779
19780 @smallexample @c ada
19781 Assert (Inc (1) = 2, "wrong incrementation");
19782 @end smallexample
19783
19784 After recompiling and running the test driver, one successfully passed test
19785 is reported.
19786
19787 @node Setting Up and Tearing Down the Testing Environment
19788 @section Setting Up and Tearing Down the Testing Environment
19789
19790 @noindent
19791
19792 Besides test routines themselves, each test package has a parent package
19793 Test_Data that has two procedures: Set_Up and Tear_Down. This package is never
19794 overwritten by the tool. Set_Up is called before each test routine of the
19795 package and Tear_Down is called after each test routine. Those two procedures
19796 can be used to perform necessary initialization and finalization,
19797 memory allocation, etc. Test type declared in Test_Data package is parent type
19798 for the test type of test package and can have user-defined components whose
19799 values can be set by Set_Up routine and used in test routines afterwards.
19800
19801 @node Regenerating Tests
19802 @section Regenerating Tests
19803
19804 @noindent
19805
19806 Bodies of test routines and test_data packages are never overridden after they
19807 have been created once. As long as the name of the subprogram, full expanded Ada
19808 names, and the order of its parameters is the same, and comment sections are
19809 intact the old test routine will fit in its place and no test skeleton will be
19810 generated for the subprogram.
19811
19812 This can be demonstrated with the previous example. By uncommenting declaration
19813 and body of function Dec in simple.ads and simple.adb, running
19814 @command{gnattest} on the project, and then running the test driver:
19815
19816 @smallexample
19817 gnattest --harness-dir=driver -Psimple.gpr
19818 cd obj/driver
19819 gnatmake -Ptest_driver
19820 test_runner
19821 @end smallexample
19822
19823 the old test is not replaced with a stub, nor is it lost, but a new test
19824 skeleton is created for function Dec.
19825
19826 The only way of regenerating tests skeletons is to remove the previously created
19827 tests together with corresponding comment sections.
19828
19829 @node Default Test Behavior
19830 @section Default Test Behavior
19831
19832 @noindent
19833
19834 The generated test driver can treat unimplemented tests in two ways:
19835 either count them all as failed (this is useful to see which tests are still
19836 left to implement) or as passed (to sort out unimplemented ones from those
19837 actually failing).
19838
19839 The test driver accepts a switch to specify this behavior:
19840 --skeleton-default=val, where val is either "pass" or "fail" (exactly as for
19841 @command{gnattest}).
19842
19843 The default behavior of the test driver is set with the same switch
19844 as passed to gnattest when generating the test driver.
19845
19846 Passing it to the driver generated on the first example:
19847
19848 @smallexample
19849 test_runner --skeleton-default=pass
19850 @end smallexample
19851
19852 makes both tests pass, even the unimplemented one.
19853
19854 @node Testing Primitive Operations of Tagged Types
19855 @section Testing Primitive Operations of Tagged Types
19856
19857 @noindent
19858
19859 Creation of test skeletons for primitive operations of tagged types entails
19860 a number of features. Test routines for all primitives of a given tagged type
19861 are placed in a separate child package named according to the tagged type. For
19862 example, if you have tagged type T in package P, all tests for primitives
19863 of T will be in P.T_Test_Data.T_Tests.
19864
19865 Consider running gnattest on the second example (note: actual tests for this
19866 example already exist, so there's no need to worry if the tool reports that
19867 no new stubs were generated):
19868
19869 @smallexample
19870 cd <install_prefix>/share/examples/gnattest/tagged_rec
19871 gnattest --harness-dir=driver -Ptagged_rec.gpr
19872 @end smallexample
19873
19874 Taking a closer look at the test type declared in the test package
19875 Speed1.Controller_Test_Data is necessary. It is declared in:
19876
19877 @smallexample
19878 <install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
19879 @end smallexample
19880
19881 Test types are direct or indirect descendants of
19882 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
19883 subprograms, the user doesn't need to be concerned with them. However,
19884 when generating test packages for primitive operations, there are some things
19885 the user needs to know.
19886
19887 Type Test_Controller has components that allow assignment of various
19888 derivations of type Controller. And if you look at the specification of
19889 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
19890 actually derives from Test_Controller rather than AUnit type Test_Fixture.
19891 Thus, test types mirror the hierarchy of tested types.
19892
19893 The Set_Up procedure of Test_Data package corresponding to a test package
19894 of primitive operations of type T assigns to Fixture a reference to an
19895 object of that exact type T. Notice, however, that if the tagged type has
19896 discriminants, the Set_Up only has a commented template for setting
19897 up the fixture, since filling the discriminant with actual value is up
19898 to the user.
19899
19900 The knowledge of the structure of test types allows additional testing
19901 without additional effort. Those possibilities are described below.
19902
19903 @node Testing Inheritance
19904 @section Testing Inheritance
19905
19906 @noindent
19907
19908 Since the test type hierarchy mimics the hierarchy of tested types, the
19909 inheritance of tests takes place. An example of such inheritance can be
19910 seen by running the test driver generated for the second example. As previously
19911 mentioned, actual tests are already written for this example.
19912
19913 @smallexample
19914 cd obj/driver
19915 gnatmake -Ptest_driver
19916 test_runner
19917 @end smallexample
19918
19919 There are 6 passed tests while there are only 5 testable subprograms. The test
19920 routine for function Speed has been inherited and run against objects of the
19921 derived type.
19922
19923 @node Tagged Types Substitutability Testing
19924 @section Tagged Types Substitutability Testing
19925
19926 @noindent
19927
19928 Tagged Types Substitutability Testing is a way of verifying the global type
19929 consistency by testing. Global type consistency is a principle stating that if
19930 S is a subtype of T (in Ada, S is a derived type of tagged type T),
19931 then objects of type T may be replaced with objects of type S (that is,
19932 objects of type S may be substituted for objects of type T), without
19933 altering any of the desirable properties of the program. When the properties
19934 of the program are expressed in the form of subprogram preconditions and
19935 postconditions (let's call them pre and post), the principle is formulated as
19936 relations between the pre and post of primitive operations and the pre and post
19937 of their derived operations. The pre of a derived operation should not be
19938 stronger than the original pre, and the post of the derived operation should
19939 not be weaker than the original post. Those relations ensure that verifying if
19940 a dispatching call is safe can be done just by using the pre and post of the
19941 root operation.
19942
19943 Verifying global type consistency by testing consists of running all the unit
19944 tests associated with the primitives of a given tagged type with objects of its
19945 derived types.
19946
19947 In the example used in the previous section, there was clearly a violation of
19948 type consistency. The overriding primitive Adjust_Speed in package Speed2
19949 removes the functionality of the overridden primitive and thus doesn't respect
19950 the consistency principle.
19951 Gnattest has a special option to run overridden parent tests against objects
19952 of the type which have overriding primitives:
19953
19954 @smallexample
19955 gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr
19956 cd obj/driver
19957 gnatmake -Ptest_driver
19958 test_runner
19959 @end smallexample
19960
19961 While all the tests pass by themselves, the parent test for Adjust_Speed fails
19962 against objects of the derived type.
19963
19964 Non-overridden tests are already inherited for derived test types, so the
19965 --validate-type-extensions enables the application of overriden tests to objects
19966 of derived types.
19967
19968 @node Testing with Contracts
19969 @section Testing with Contracts
19970
19971 @noindent
19972
19973 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case,
19974 as well as corresponding aspects.
19975 Test routines are generated, one per each Test_Case associated with a tested
19976 subprogram. Those test routines have special wrappers for tested functions
19977 that have composition of pre- and postcondition of the subprogram with
19978 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
19979 either count for Nominal mode or do not count for Robustness mode).
19980
19981 The third example demonstrates how this works:
19982
19983 @smallexample
19984 cd <install_prefix>/share/examples/gnattest/contracts
19985 gnattest --harness-dir=driver -Pcontracts.gpr
19986 @end smallexample
19987
19988 Putting actual checks within the range of the contract does not cause any
19989 error reports. For example, for the test routine which corresponds to
19990 test case 1:
19991
19992 @smallexample @c ada
19993 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
19994 @end smallexample
19995
19996 and for the test routine corresponding to test case 2:
19997
19998 @smallexample @c ada
19999 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
20000 @end smallexample
20001
20002 are acceptable:
20003
20004 @smallexample
20005 cd obj/driver
20006 gnatmake -Ptest_driver
20007 test_runner
20008 @end smallexample
20009
20010 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
20011 a precondition violation for test case one. Also, by using any otherwise
20012 correct but positive pair of numbers in the second test routine, you can also
20013 get a precondition violation. Postconditions are checked and reported
20014 the same way.
20015
20016 @node Additional Tests
20017 @section Additional Tests
20018
20019 @noindent
20020 @command{gnattest} can add user-written tests to the main suite of the test
20021 driver. @command{gnattest} traverses the given packages and searches for test
20022 routines. All procedures with a single in out parameter of a type which is
20023 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
20024 specifications are added to the suites and are then executed by the test driver.
20025 (Set_Up and Tear_Down are filtered out.)
20026
20027 An example illustrates two ways of creating test harnesses for user-written
20028 tests. Directory additional_tests contains an AUnit-based test driver written
20029 by hand.
20030
20031 @smallexample
20032 <install_prefix>/share/examples/gnattest/additional_tests/
20033 @end smallexample
20034
20035 To create a test driver for already-written tests, use the --harness-only
20036 option:
20037
20038 @smallexample
20039 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
20040 --harness-only
20041 gnatmake -Pharness_only/test_driver.gpr
20042 harness_only/test_runner
20043 @end smallexample
20044
20045 Additional tests can also be executed together with generated tests:
20046
20047 @smallexample
20048 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
20049 --harness-dir=mixing
20050 gnatmake -Pmixing/test_driver.gpr
20051 mixing/test_runner
20052 @end smallexample
20053
20054 @ifclear vms
20055 @node Support for other platforms/run-times
20056 @section Support for other platforms/run-times
20057
20058 @noindent
20059 @command{gnattest} can be used to generate the test harness for platforms
20060 and run-time libraries others than the default native target with the
20061 default full run-time. For example, when using a limited run-time library
20062 such as Zero FootPrint (ZFP), a simplified harness is generated.
20063
20064 Two variables are used to tell the underlying AUnit framework how to generate
20065 the test harness: @code{PLATFORM}, which identifies the target, and
20066 @code{RUNTIME}, used to determine the run-time library for which the harness
20067 is generated. Corresponding prefix should also be used when calling
20068 @command{gnattest} for non-native targets. For example, the following options
20069 are used to generate the AUnit test harness for a PowerPC ELF target using
20070 the ZFP run-time library:
20071
20072 @smallexample
20073 powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
20074 @end smallexample
20075 @end ifclear
20076
20077 @node Current Limitations
20078 @section Current Limitations
20079
20080 @noindent
20081
20082 The tool currently does not support following features:
20083
20084 @itemize @bullet
20085 @item generic tests for generic packages and package instantiations
20086 @item tests for protected subprograms and entries
20087
20088 @end itemize
20089
20090 @c *********************************
20091 @node Performing Dimensionality Analysis in GNAT
20092 @chapter Performing Dimensionality Analysis in GNAT
20093 @noindent
20094 The GNAT compiler now supports dimensionality checking. The user can
20095 specify physical units for objects, and the compiler will verify that uses
20096 of these objects are compatible with their dimensions, in a fashion that is
20097 familiar to engineering practice. The dimensions of algebraic expressions
20098 (including powers with static exponents) are computed from their consistuents.
20099
20100 This feature depends on Ada 2012 aspect specifications, and is available from
20101 version 7.0.1 of GNAT onwards. The GNAT-specific aspect Dimension_System allows
20102 you to define a system of units; the aspect Dimension then allows the user
20103 to declare dimensioned quantities within a given system.
20104
20105 The major advantage of this model is that it does not require the declaration of
20106 multiple operators for all possible combinations of types: it is only necessary
20107 to use the proper subtypes in object declarations.
20108
20109 The simplest way to impose dimensionality checking on a computation is to make
20110 use of the package System.Dim.Mks, which is part of the GNAT library. This
20111 package defines a floating-point type MKS_Type, for which a sequence of
20112 dimension names are specified, together with their conventional abbreviations.
20113 The following should be read together with the full specification of the
20114 package, in file s-dimmks.ads.
20115
20116 @smallexample @c ada
20117 type Mks_Type is new Long_Long_Float
20118 with
20119 Dimension_System => (
20120 (Unit_Name => Meter, Unit_Symbol => 'm', Dim_Symbol => 'L'),
20121 (Unit_Name => Kilogram, Unit_Symbol => "kg", Dim_Symbol => 'M'),
20122 (Unit_Name => Second, Unit_Symbol => 's', Dim_Symbol => 'T'),
20123 (Unit_Name => Ampere, Unit_Symbol => 'A', Dim_Symbol => 'I'),
20124 (Unit_Name => Kelvin, Unit_Symbol => 'K', Dim_Symbol => "Theta"),
20125 (Unit_Name => Mole, Unit_Symbol => "mol", Dim_Symbol => 'N'),
20126 (Unit_Name => Candela, Unit_Symbol => "cd", Dim_Symbol => 'J'));
20127 @end smallexample
20128
20129 @noindent
20130 The package then defines a series of subtypes that correspond to these
20131 conventional units. For example:
20132 @smallexample @c ada
20133 subtype Length is Mks_Type
20134 with
20135 Dimension => (Symbol => 'm', Meter => 1, others => 0);
20136 @end smallexample
20137 @noindent
20138 and similarly for Mass, Time, Electric_Current, Thermodynamic_Temperature,
20139 Amount_Of_Substance, and Luminous_Intensity (the standard set of units of
20140 the SI system).
20141
20142 The package also defines conventional names for values of each unit, for
20143 example:
20144
20145 @smallexample @c ada
20146 m : constant Length := 1.0;
20147 kg : constant Mass := 1.0;
20148 s : constant Time := 1.0;
20149 A : constant Electric_Current := 1.0;
20150 @end smallexample
20151
20152 @noindent
20153 as well as useful multiples of these units:
20154
20155 @smallexample @c ada
20156 cm : constant Length := 1.0E-02;
20157 g : constant Mass := 1.0E-03;
20158 min : constant Time := 60.0;
20159 day : constant TIme := 60.0 * 24.0 * min;
20160 ...
20161 @end smallexample
20162
20163 @noindent
20164 Using this package, you can then define a derived unit by
20165 providing the aspect that
20166 specifies its dimensions within the MKS system, as well as the string to
20167 be used for output of a value of that unit:
20168
20169 @smallexample @c ada
20170 subtype Acceleration is Mks_Type
20171 with Dimension => ("m/sec^^^2",
20172 Meter => 1,
20173 Second => -2,
20174 others => 0);
20175 @end smallexample
20176
20177 @noindent
20178 Here is a complete example of use:
20179
20180 @smallexample @c ada
20181 with System.Dim.MKS; use System.Dim.Mks;
20182 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
20183 with Text_IO; use Text_IO;
20184 procedure Free_Fall is
20185 subtype Acceleration is Mks_Type
20186 with Dimension => ("m/sec^^^2", 1, 0, -2, others => 0);
20187 G : constant acceleration := 9.81 * m / (s ** 2);
20188 T : Time := 10.0*s;
20189 Distance : Length;
20190 begin
20191 Put ("Gravitational constant: ");
20192 Put (G, Aft => 2, Exp => 0); Put_Line ("");
20193 Distance := 0.5 * G * T ** 2;
20194 Put ("distance travelled in 10 seconds of free fall ");
20195 Put (Distance, Aft => 2, Exp => 0);
20196 Put_Line ("");
20197 end Free_Fall;
20198 @end smallexample
20199
20200 @noindent
20201 Execution of this program yields:
20202 @smallexample
20203 Gravitational constant: 9.81 m/sec^^^2
20204 distance travelled in 10 seconds of free fall 490.50 m
20205 @end smallexample
20206
20207 @noindent
20208 However, incorrect assignments such as:
20209
20210 @smallexample @c ada
20211 Distance := 5.0;
20212 Distance := 5.0 * kg:
20213 @end smallexample
20214
20215 @noindent
20216 are rejected with the following diagnoses:
20217
20218 @smallexample
20219 Distance := 5.0;
20220 >>> dimensions mismatch in assignment
20221 >>> left-hand side has dimension [L]
20222 >>> right-hand side is dimensionless
20223
20224 Distance := 5.0 * kg:
20225 >>> dimensions mismatch in assignment
20226 >>> left-hand side has dimension [L]
20227 >>> right-hand side has dimension [M]
20228 @end smallexample
20229
20230 @noindent
20231 The dimensions of an expression are properly displayed, even if there is
20232 no explicit subtype for it. If we add to the program:
20233
20234 @smallexample @c ada
20235 Put ("Final velocity: ");
20236 Put (G * T, Aft =>2, Exp =>0);
20237 Put_Line ("");
20238 @end smallexample
20239
20240 @noindent
20241 then the output includes:
20242 @smallexample
20243 Final velocity: 98.10 m.s**(-1)
20244 @end smallexample
20245
20246 @c *********************************
20247 @node Generating Ada Bindings for C and C++ headers
20248 @chapter Generating Ada Bindings for C and C++ headers
20249 @findex binding
20250
20251 @noindent
20252 GNAT now comes with a binding generator for C and C++ headers which is
20253 intended to do 95% of the tedious work of generating Ada specs from C
20254 or C++ header files.
20255
20256 Note that this capability is not intended to generate 100% correct Ada specs,
20257 and will is some cases require manual adjustments, although it can often
20258 be used out of the box in practice.
20259
20260 Some of the known limitations include:
20261
20262 @itemize @bullet
20263 @item only very simple character constant macros are translated into Ada
20264 constants. Function macros (macros with arguments) are partially translated
20265 as comments, to be completed manually if needed.
20266 @item some extensions (e.g. vector types) are not supported
20267 @item pointers to pointers or complex structures are mapped to System.Address
20268 @item identifiers with identical name (except casing) will generate compilation
20269 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
20270 @end itemize
20271
20272 The code generated is using the Ada 2005 syntax, which makes it
20273 easier to interface with other languages than previous versions of Ada.
20274
20275 @menu
20276 * Running the binding generator::
20277 * Generating bindings for C++ headers::
20278 * Switches::
20279 @end menu
20280
20281 @node Running the binding generator
20282 @section Running the binding generator
20283
20284 @noindent
20285 The binding generator is part of the @command{gcc} compiler and can be
20286 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
20287 spec files for the header files specified on the command line, and all
20288 header files needed by these files transitively. For example:
20289
20290 @smallexample
20291 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
20292 $ gcc -c -gnat05 *.ads
20293 @end smallexample
20294
20295 will generate, under GNU/Linux, the following files: @file{time_h.ads},
20296 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
20297 correspond to the files @file{/usr/include/time.h},
20298 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
20299 mode these Ada specs.
20300
20301 The @code{-C} switch tells @command{gcc} to extract comments from headers,
20302 and will attempt to generate corresponding Ada comments.
20303
20304 If you want to generate a single Ada file and not the transitive closure, you
20305 can use instead the @option{-fdump-ada-spec-slim} switch.
20306
20307 You can optionally specify a parent unit, of which all generated units will
20308 be children, using @code{-fada-spec-parent=}@var{unit}.
20309
20310 Note that we recommend when possible to use the @command{g++} driver to
20311 generate bindings, even for most C headers, since this will in general
20312 generate better Ada specs. For generating bindings for C++ headers, it is
20313 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
20314 is equivalent in this case. If @command{g++} cannot work on your C headers
20315 because of incompatibilities between C and C++, then you can fallback to
20316 @command{gcc} instead.
20317
20318 For an example of better bindings generated from the C++ front-end,
20319 the name of the parameters (when available) are actually ignored by the C
20320 front-end. Consider the following C header:
20321
20322 @smallexample
20323 extern void foo (int variable);
20324 @end smallexample
20325
20326 with the C front-end, @code{variable} is ignored, and the above is handled as:
20327
20328 @smallexample
20329 extern void foo (int);
20330 @end smallexample
20331
20332 generating a generic:
20333
20334 @smallexample
20335 procedure foo (param1 : int);
20336 @end smallexample
20337
20338 with the C++ front-end, the name is available, and we generate:
20339
20340 @smallexample
20341 procedure foo (variable : int);
20342 @end smallexample
20343
20344 In some cases, the generated bindings will be more complete or more meaningful
20345 when defining some macros, which you can do via the @option{-D} switch. This
20346 is for example the case with @file{Xlib.h} under GNU/Linux:
20347
20348 @smallexample
20349 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
20350 @end smallexample
20351
20352 The above will generate more complete bindings than a straight call without
20353 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
20354
20355 In other cases, it is not possible to parse a header file in a stand-alone
20356 manner, because other include files need to be included first. In this
20357 case, the solution is to create a small header file including the needed
20358 @code{#include} and possible @code{#define} directives. For example, to
20359 generate Ada bindings for @file{readline/readline.h}, you need to first
20360 include @file{stdio.h}, so you can create a file with the following two
20361 lines in e.g. @file{readline1.h}:
20362
20363 @smallexample
20364 #include <stdio.h>
20365 #include <readline/readline.h>
20366 @end smallexample
20367
20368 and then generate Ada bindings from this file:
20369
20370 @smallexample
20371 $ g++ -c -fdump-ada-spec readline1.h
20372 @end smallexample
20373
20374 @node Generating bindings for C++ headers
20375 @section Generating bindings for C++ headers
20376
20377 @noindent
20378 Generating bindings for C++ headers is done using the same options, always
20379 with the @command{g++} compiler.
20380
20381 In this mode, C++ classes will be mapped to Ada tagged types, constructors
20382 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
20383 multiple inheritance of abstract classes will be mapped to Ada interfaces
20384 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
20385 information on interfacing to C++).
20386
20387 For example, given the following C++ header file:
20388
20389 @smallexample
20390 @group
20391 @cartouche
20392 class Carnivore @{
20393 public:
20394 virtual int Number_Of_Teeth () = 0;
20395 @};
20396
20397 class Domestic @{
20398 public:
20399 virtual void Set_Owner (char* Name) = 0;
20400 @};
20401
20402 class Animal @{
20403 public:
20404 int Age_Count;
20405 virtual void Set_Age (int New_Age);
20406 @};
20407
20408 class Dog : Animal, Carnivore, Domestic @{
20409 public:
20410 int Tooth_Count;
20411 char *Owner;
20412
20413 virtual int Number_Of_Teeth ();
20414 virtual void Set_Owner (char* Name);
20415
20416 Dog();
20417 @};
20418 @end cartouche
20419 @end group
20420 @end smallexample
20421
20422 The corresponding Ada code is generated:
20423
20424 @smallexample @c ada
20425 @group
20426 @cartouche
20427 package Class_Carnivore is
20428 type Carnivore is limited interface;
20429 pragma Import (CPP, Carnivore);
20430
20431 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
20432 end;
20433 use Class_Carnivore;
20434
20435 package Class_Domestic is
20436 type Domestic is limited interface;
20437 pragma Import (CPP, Domestic);
20438
20439 procedure Set_Owner
20440 (this : access Domestic;
20441 Name : Interfaces.C.Strings.chars_ptr) is abstract;
20442 end;
20443 use Class_Domestic;
20444
20445 package Class_Animal is
20446 type Animal is tagged limited record
20447 Age_Count : aliased int;
20448 end record;
20449 pragma Import (CPP, Animal);
20450
20451 procedure Set_Age (this : access Animal; New_Age : int);
20452 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
20453 end;
20454 use Class_Animal;
20455
20456 package Class_Dog is
20457 type Dog is new Animal and Carnivore and Domestic with record
20458 Tooth_Count : aliased int;
20459 Owner : Interfaces.C.Strings.chars_ptr;
20460 end record;
20461 pragma Import (CPP, Dog);
20462
20463 function Number_Of_Teeth (this : access Dog) return int;
20464 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
20465
20466 procedure Set_Owner
20467 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
20468 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
20469
20470 function New_Dog return Dog;
20471 pragma CPP_Constructor (New_Dog);
20472 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
20473 end;
20474 use Class_Dog;
20475 @end cartouche
20476 @end group
20477 @end smallexample
20478
20479 @node Switches
20480 @section Switches
20481
20482 @table @option
20483 @item -fdump-ada-spec
20484 @cindex @option{-fdump-ada-spec} (@command{gcc})
20485 Generate Ada spec files for the given header files transitively (including
20486 all header files that these headers depend upon).
20487
20488 @item -fdump-ada-spec-slim
20489 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
20490 Generate Ada spec files for the header files specified on the command line
20491 only.
20492
20493 @item -fada-spec-parent=@var{unit}
20494 @cindex -fada-spec-parent (@command{gcc})
20495 Specifies that all files generated by @option{-fdump-ada-spec*} are
20496 to be child units of the specified parent unit.
20497
20498 @item -C
20499 @cindex @option{-C} (@command{gcc})
20500 Extract comments from headers and generate Ada comments in the Ada spec files.
20501 @end table
20502
20503 @node Other Utility Programs
20504 @chapter Other Utility Programs
20505
20506 @noindent
20507 This chapter discusses some other utility programs available in the Ada
20508 environment.
20509
20510 @menu
20511 * Using Other Utility Programs with GNAT::
20512 * The External Symbol Naming Scheme of GNAT::
20513 * Converting Ada Files to html with gnathtml::
20514 * Installing gnathtml::
20515 @ifset vms
20516 * LSE::
20517 * Profiling::
20518 @end ifset
20519 @end menu
20520
20521 @node Using Other Utility Programs with GNAT
20522 @section Using Other Utility Programs with GNAT
20523
20524 @noindent
20525 The object files generated by GNAT are in standard system format and in
20526 particular the debugging information uses this format. This means
20527 programs generated by GNAT can be used with existing utilities that
20528 depend on these formats.
20529
20530 @ifclear vms
20531 In general, any utility program that works with C will also often work with
20532 Ada programs generated by GNAT. This includes software utilities such as
20533 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
20534 as Purify.
20535 @end ifclear
20536
20537 @node The External Symbol Naming Scheme of GNAT
20538 @section The External Symbol Naming Scheme of GNAT
20539
20540 @noindent
20541 In order to interpret the output from GNAT, when using tools that are
20542 originally intended for use with other languages, it is useful to
20543 understand the conventions used to generate link names from the Ada
20544 entity names.
20545
20546 All link names are in all lowercase letters. With the exception of library
20547 procedure names, the mechanism used is simply to use the full expanded
20548 Ada name with dots replaced by double underscores. For example, suppose
20549 we have the following package spec:
20550
20551 @smallexample @c ada
20552 @group
20553 @cartouche
20554 package QRS is
20555 MN : Integer;
20556 end QRS;
20557 @end cartouche
20558 @end group
20559 @end smallexample
20560
20561 @noindent
20562 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
20563 the corresponding link name is @code{qrs__mn}.
20564 @findex Export
20565 Of course if a @code{pragma Export} is used this may be overridden:
20566
20567 @smallexample @c ada
20568 @group
20569 @cartouche
20570 package Exports is
20571 Var1 : Integer;
20572 pragma Export (Var1, C, External_Name => "var1_name");
20573 Var2 : Integer;
20574 pragma Export (Var2, C, Link_Name => "var2_link_name");
20575 end Exports;
20576 @end cartouche
20577 @end group
20578 @end smallexample
20579
20580 @noindent
20581 In this case, the link name for @var{Var1} is whatever link name the
20582 C compiler would assign for the C function @var{var1_name}. This typically
20583 would be either @var{var1_name} or @var{_var1_name}, depending on operating
20584 system conventions, but other possibilities exist. The link name for
20585 @var{Var2} is @var{var2_link_name}, and this is not operating system
20586 dependent.
20587
20588 @findex _main
20589 One exception occurs for library level procedures. A potential ambiguity
20590 arises between the required name @code{_main} for the C main program,
20591 and the name we would otherwise assign to an Ada library level procedure
20592 called @code{Main} (which might well not be the main program).
20593
20594 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
20595 names. So if we have a library level procedure such as
20596
20597 @smallexample @c ada
20598 @group
20599 @cartouche
20600 procedure Hello (S : String);
20601 @end cartouche
20602 @end group
20603 @end smallexample
20604
20605 @noindent
20606 the external name of this procedure will be @var{_ada_hello}.
20607
20608
20609 @node Converting Ada Files to html with gnathtml
20610 @section Converting Ada Files to HTML with @code{gnathtml}
20611
20612 @noindent
20613 This @code{Perl} script allows Ada source files to be browsed using
20614 standard Web browsers. For installation procedure, see the section
20615 @xref{Installing gnathtml}.
20616
20617 Ada reserved keywords are highlighted in a bold font and Ada comments in
20618 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
20619 switch to suppress the generation of cross-referencing information, user
20620 defined variables and types will appear in a different color; you will
20621 be able to click on any identifier and go to its declaration.
20622
20623 The command line is as follow:
20624 @smallexample
20625 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
20626 @c Expanding @ovar macro inline (explanation in macro def comments)
20627 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
20628 @end smallexample
20629
20630 @noindent
20631 You can pass it as many Ada files as you want. @code{gnathtml} will generate
20632 an html file for every ada file, and a global file called @file{index.htm}.
20633 This file is an index of every identifier defined in the files.
20634
20635 The available ^switches^options^ are the following ones:
20636
20637 @table @option
20638 @item -83
20639 @cindex @option{-83} (@code{gnathtml})
20640 Only the Ada 83 subset of keywords will be highlighted.
20641
20642 @item -cc @var{color}
20643 @cindex @option{-cc} (@code{gnathtml})
20644 This option allows you to change the color used for comments. The default
20645 value is green. The color argument can be any name accepted by html.
20646
20647 @item -d
20648 @cindex @option{-d} (@code{gnathtml})
20649 If the Ada files depend on some other files (for instance through
20650 @code{with} clauses, the latter files will also be converted to html.
20651 Only the files in the user project will be converted to html, not the files
20652 in the run-time library itself.
20653
20654 @item -D
20655 @cindex @option{-D} (@code{gnathtml})
20656 This command is the same as @option{-d} above, but @command{gnathtml} will
20657 also look for files in the run-time library, and generate html files for them.
20658
20659 @item -ext @var{extension}
20660 @cindex @option{-ext} (@code{gnathtml})
20661 This option allows you to change the extension of the generated HTML files.
20662 If you do not specify an extension, it will default to @file{htm}.
20663
20664 @item -f
20665 @cindex @option{-f} (@code{gnathtml})
20666 By default, gnathtml will generate html links only for global entities
20667 ('with'ed units, global variables and types,@dots{}). If you specify
20668 @option{-f} on the command line, then links will be generated for local
20669 entities too.
20670
20671 @item -l @var{number}
20672 @cindex @option{-l} (@code{gnathtml})
20673 If this ^switch^option^ is provided and @var{number} is not 0, then
20674 @code{gnathtml} will number the html files every @var{number} line.
20675
20676 @item -I @var{dir}
20677 @cindex @option{-I} (@code{gnathtml})
20678 Specify a directory to search for library files (@file{.ALI} files) and
20679 source files. You can provide several -I switches on the command line,
20680 and the directories will be parsed in the order of the command line.
20681
20682 @item -o @var{dir}
20683 @cindex @option{-o} (@code{gnathtml})
20684 Specify the output directory for html files. By default, gnathtml will
20685 saved the generated html files in a subdirectory named @file{html/}.
20686
20687 @item -p @var{file}
20688 @cindex @option{-p} (@code{gnathtml})
20689 If you are using Emacs and the most recent Emacs Ada mode, which provides
20690 a full Integrated Development Environment for compiling, checking,
20691 running and debugging applications, you may use @file{.gpr} files
20692 to give the directories where Emacs can find sources and object files.
20693
20694 Using this ^switch^option^, you can tell gnathtml to use these files.
20695 This allows you to get an html version of your application, even if it
20696 is spread over multiple directories.
20697
20698 @item -sc @var{color}
20699 @cindex @option{-sc} (@code{gnathtml})
20700 This ^switch^option^ allows you to change the color used for symbol
20701 definitions.
20702 The default value is red. The color argument can be any name accepted by html.
20703
20704 @item -t @var{file}
20705 @cindex @option{-t} (@code{gnathtml})
20706 This ^switch^option^ provides the name of a file. This file contains a list of
20707 file names to be converted, and the effect is exactly as though they had
20708 appeared explicitly on the command line. This
20709 is the recommended way to work around the command line length limit on some
20710 systems.
20711
20712 @end table
20713
20714 @node Installing gnathtml
20715 @section Installing @code{gnathtml}
20716
20717 @noindent
20718 @code{Perl} needs to be installed on your machine to run this script.
20719 @code{Perl} is freely available for almost every architecture and
20720 Operating System via the Internet.
20721
20722 On Unix systems, you may want to modify the first line of the script
20723 @code{gnathtml}, to explicitly tell the Operating system where Perl
20724 is. The syntax of this line is:
20725 @smallexample
20726 #!full_path_name_to_perl
20727 @end smallexample
20728
20729 @noindent
20730 Alternatively, you may run the script using the following command line:
20731
20732 @smallexample
20733 @c $ perl gnathtml.pl @ovar{switches} @var{files}
20734 @c Expanding @ovar macro inline (explanation in macro def comments)
20735 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
20736 @end smallexample
20737
20738 @ifset vms
20739 @node LSE
20740 @section LSE
20741 @findex LSE
20742
20743 @noindent
20744 The GNAT distribution provides an Ada 95 template for the HP Language
20745 Sensitive Editor (LSE), a component of DECset. In order to
20746 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
20747
20748 @node Profiling
20749 @section Profiling
20750 @findex PCA
20751
20752 @noindent
20753 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
20754 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
20755 the collection phase with the /DEBUG qualifier.
20756
20757 @smallexample
20758 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
20759 $ DEFINE LIB$DEBUG PCA$COLLECTOR
20760 $ RUN/DEBUG <PROGRAM_NAME>
20761 @end smallexample
20762 @noindent
20763 @end ifset
20764
20765 @ifclear vms
20766 @c ******************************
20767 @node Code Coverage and Profiling
20768 @chapter Code Coverage and Profiling
20769 @cindex Code Coverage
20770 @cindex Profiling
20771
20772 @noindent
20773 This chapter describes how to use @code{gcov} - coverage testing tool - and
20774 @code{gprof} - profiler tool - on your Ada programs.
20775
20776 @menu
20777 * Code Coverage of Ada Programs with gcov::
20778 * Profiling an Ada Program with gprof::
20779 @end menu
20780
20781 @node Code Coverage of Ada Programs with gcov
20782 @section Code Coverage of Ada Programs with gcov
20783 @cindex gcov
20784 @cindex -fprofile-arcs
20785 @cindex -ftest-coverage
20786 @cindex -coverage
20787 @cindex Code Coverage
20788
20789 @noindent
20790 @code{gcov} is a test coverage program: it analyzes the execution of a given
20791 program on selected tests, to help you determine the portions of the program
20792 that are still untested.
20793
20794 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
20795 User's Guide. You can refer to this documentation for a more complete
20796 description.
20797
20798 This chapter provides a quick startup guide, and
20799 details some Gnat-specific features.
20800
20801 @menu
20802 * Quick startup guide::
20803 * Gnat specifics::
20804 @end menu
20805
20806 @node Quick startup guide
20807 @subsection Quick startup guide
20808
20809 In order to perform coverage analysis of a program using @code{gcov}, 3
20810 steps are needed:
20811
20812 @itemize @bullet
20813 @item
20814 Code instrumentation during the compilation process
20815 @item
20816 Execution of the instrumented program
20817 @item
20818 Execution of the @code{gcov} tool to generate the result.
20819 @end itemize
20820
20821 The code instrumentation needed by gcov is created at the object level:
20822 The source code is not modified in any way, because the instrumentation code is
20823 inserted by gcc during the compilation process. To compile your code with code
20824 coverage activated, you need to recompile your whole project using the
20825 switches
20826 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
20827 @code{-fprofile-arcs}.
20828
20829 @smallexample
20830 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
20831 -largs -fprofile-arcs
20832 @end smallexample
20833
20834 This compilation process will create @file{.gcno} files together with
20835 the usual object files.
20836
20837 Once the program is compiled with coverage instrumentation, you can
20838 run it as many times as needed - on portions of a test suite for
20839 example. The first execution will produce @file{.gcda} files at the
20840 same location as the @file{.gcno} files. The following executions
20841 will update those files, so that a cumulative result of the covered
20842 portions of the program is generated.
20843
20844 Finally, you need to call the @code{gcov} tool. The different options of
20845 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
20846
20847 This will create annotated source files with a @file{.gcov} extension:
20848 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
20849
20850 @node Gnat specifics
20851 @subsection Gnat specifics
20852
20853 Because Ada semantics, portions of the source code may be shared among
20854 several object files. This is the case for example when generics are
20855 involved, when inlining is active or when declarations generate initialisation
20856 calls. In order to take
20857 into account this shared code, you need to call @code{gcov} on all
20858 source files of the tested program at once.
20859
20860 The list of source files might exceed the system's maximum command line
20861 length. In order to bypass this limitation, a new mechanism has been
20862 implemented in @code{gcov}: you can now list all your project's files into a
20863 text file, and provide this file to gcov as a parameter, preceded by a @@
20864 (e.g. @samp{gcov @@mysrclist.txt}).
20865
20866 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
20867 not supported as there can be unresolved symbols during the final link.
20868
20869 @node Profiling an Ada Program with gprof
20870 @section Profiling an Ada Program with gprof
20871 @cindex gprof
20872 @cindex -pg
20873 @cindex Profiling
20874
20875 @noindent
20876 This section is not meant to be an exhaustive documentation of @code{gprof}.
20877 Full documentation for it can be found in the GNU Profiler User's Guide
20878 documentation that is part of this GNAT distribution.
20879
20880 Profiling a program helps determine the parts of a program that are executed
20881 most often, and are therefore the most time-consuming.
20882
20883 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
20884 better handle Ada programs and multitasking.
20885 It is currently supported on the following platforms
20886 @itemize @bullet
20887 @item
20888 linux x86/x86_64
20889 @item
20890 solaris sparc/sparc64/x86
20891 @item
20892 windows x86
20893 @end itemize
20894
20895 @noindent
20896 In order to profile a program using @code{gprof}, 3 steps are needed:
20897
20898 @itemize @bullet
20899 @item
20900 Code instrumentation, requiring a full recompilation of the project with the
20901 proper switches.
20902 @item
20903 Execution of the program under the analysis conditions, i.e. with the desired
20904 input.
20905 @item
20906 Analysis of the results using the @code{gprof} tool.
20907 @end itemize
20908
20909 @noindent
20910 The following sections detail the different steps, and indicate how
20911 to interpret the results:
20912 @menu
20913 * Compilation for profiling::
20914 * Program execution::
20915 * Running gprof::
20916 * Interpretation of profiling results::
20917 @end menu
20918
20919 @node Compilation for profiling
20920 @subsection Compilation for profiling
20921 @cindex -pg
20922 @cindex Profiling
20923
20924 In order to profile a program the first step is to tell the compiler
20925 to generate the necessary profiling information. The compiler switch to be used
20926 is @code{-pg}, which must be added to other compilation switches. This
20927 switch needs to be specified both during compilation and link stages, and can
20928 be specified once when using gnatmake:
20929
20930 @smallexample
20931 gnatmake -f -pg -P my_project
20932 @end smallexample
20933
20934 @noindent
20935 Note that only the objects that were compiled with the @samp{-pg} switch will
20936 be profiled; if you need to profile your whole project, use the @samp{-f}
20937 gnatmake switch to force full recompilation.
20938
20939 @node Program execution
20940 @subsection Program execution
20941
20942 @noindent
20943 Once the program has been compiled for profiling, you can run it as usual.
20944
20945 The only constraint imposed by profiling is that the program must terminate
20946 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20947 properly analyzed.
20948
20949 Once the program completes execution, a data file called @file{gmon.out} is
20950 generated in the directory where the program was launched from. If this file
20951 already exists, it will be overwritten.
20952
20953 @node Running gprof
20954 @subsection Running gprof
20955
20956 @noindent
20957 The @code{gprof} tool is called as follow:
20958
20959 @smallexample
20960 gprof my_prog gmon.out
20961 @end smallexample
20962
20963 @noindent
20964 or simpler:
20965
20966 @smallexample
20967 gprof my_prog
20968 @end smallexample
20969
20970 @noindent
20971 The complete form of the gprof command line is the following:
20972
20973 @smallexample
20974 gprof [^switches^options^] [executable [data-file]]
20975 @end smallexample
20976
20977 @noindent
20978 @code{gprof} supports numerous ^switch^options^. The order of these
20979 ^switch^options^ does not matter. The full list of options can be found in
20980 the GNU Profiler User's Guide documentation that comes with this documentation.
20981
20982 The following is the subset of those switches that is most relevant:
20983
20984 @table @option
20985
20986 @item --demangle[=@var{style}]
20987 @itemx --no-demangle
20988 @cindex @option{--demangle} (@code{gprof})
20989 These options control whether symbol names should be demangled when
20990 printing output. The default is to demangle C++ symbols. The
20991 @code{--no-demangle} option may be used to turn off demangling. Different
20992 compilers have different mangling styles. The optional demangling style
20993 argument can be used to choose an appropriate demangling style for your
20994 compiler, in particular Ada symbols generated by GNAT can be demangled using
20995 @code{--demangle=gnat}.
20996
20997 @item -e @var{function_name}
20998 @cindex @option{-e} (@code{gprof})
20999 The @samp{-e @var{function}} option tells @code{gprof} not to print
21000 information about the function @var{function_name} (and its
21001 children@dots{}) in the call graph. The function will still be listed
21002 as a child of any functions that call it, but its index number will be
21003 shown as @samp{[not printed]}. More than one @samp{-e} option may be
21004 given; only one @var{function_name} may be indicated with each @samp{-e}
21005 option.
21006
21007 @item -E @var{function_name}
21008 @cindex @option{-E} (@code{gprof})
21009 The @code{-E @var{function}} option works like the @code{-e} option, but
21010 execution time spent in the function (and children who were not called from
21011 anywhere else), will not be used to compute the percentages-of-time for
21012 the call graph. More than one @samp{-E} option may be given; only one
21013 @var{function_name} may be indicated with each @samp{-E} option.
21014
21015 @item -f @var{function_name}
21016 @cindex @option{-f} (@code{gprof})
21017 The @samp{-f @var{function}} option causes @code{gprof} to limit the
21018 call graph to the function @var{function_name} and its children (and
21019 their children@dots{}). More than one @samp{-f} option may be given;
21020 only one @var{function_name} may be indicated with each @samp{-f}
21021 option.
21022
21023 @item -F @var{function_name}
21024 @cindex @option{-F} (@code{gprof})
21025 The @samp{-F @var{function}} option works like the @code{-f} option, but
21026 only time spent in the function and its children (and their
21027 children@dots{}) will be used to determine total-time and
21028 percentages-of-time for the call graph. More than one @samp{-F} option
21029 may be given; only one @var{function_name} may be indicated with each
21030 @samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.
21031
21032 @end table
21033
21034 @node Interpretation of profiling results
21035 @subsection Interpretation of profiling results
21036
21037 @noindent
21038
21039 The results of the profiling analysis are represented by two arrays: the
21040 'flat profile' and the 'call graph'. Full documentation of those outputs
21041 can be found in the GNU Profiler User's Guide.
21042
21043 The flat profile shows the time spent in each function of the program, and how
21044 many time it has been called. This allows you to locate easily the most
21045 time-consuming functions.
21046
21047 The call graph shows, for each subprogram, the subprograms that call it,
21048 and the subprograms that it calls. It also provides an estimate of the time
21049 spent in each of those callers/called subprograms.
21050 @end ifclear
21051
21052 @c ******************************
21053 @node Running and Debugging Ada Programs
21054 @chapter Running and Debugging Ada Programs
21055 @cindex Debugging
21056
21057 @noindent
21058 This chapter discusses how to debug Ada programs.
21059 @ifset vms
21060 It applies to GNAT on the Alpha OpenVMS platform;
21061 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
21062 since HP has implemented Ada support in the OpenVMS debugger on I64.
21063 @end ifset
21064
21065 An incorrect Ada program may be handled in three ways by the GNAT compiler:
21066
21067 @enumerate
21068 @item
21069 The illegality may be a violation of the static semantics of Ada. In
21070 that case GNAT diagnoses the constructs in the program that are illegal.
21071 It is then a straightforward matter for the user to modify those parts of
21072 the program.
21073
21074 @item
21075 The illegality may be a violation of the dynamic semantics of Ada. In
21076 that case the program compiles and executes, but may generate incorrect
21077 results, or may terminate abnormally with some exception.
21078
21079 @item
21080 When presented with a program that contains convoluted errors, GNAT
21081 itself may terminate abnormally without providing full diagnostics on
21082 the incorrect user program.
21083 @end enumerate
21084
21085 @menu
21086 * The GNAT Debugger GDB::
21087 * Running GDB::
21088 * Introduction to GDB Commands::
21089 * Using Ada Expressions::
21090 * Calling User-Defined Subprograms::
21091 * Using the Next Command in a Function::
21092 * Ada Exceptions::
21093 * Ada Tasks::
21094 * Debugging Generic Units::
21095 * Remote Debugging with gdbserver::
21096 * GNAT Abnormal Termination or Failure to Terminate::
21097 * Naming Conventions for GNAT Source Files::
21098 * Getting Internal Debugging Information::
21099 * Stack Traceback::
21100 @end menu
21101
21102 @cindex Debugger
21103 @findex gdb
21104
21105 @node The GNAT Debugger GDB
21106 @section The GNAT Debugger GDB
21107
21108 @noindent
21109 @code{GDB} is a general purpose, platform-independent debugger that
21110 can be used to debug mixed-language programs compiled with @command{gcc},
21111 and in particular is capable of debugging Ada programs compiled with
21112 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
21113 complex Ada data structures.
21114
21115 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
21116 @ifset vms
21117 located in the GNU:[DOCS] directory,
21118 @end ifset
21119 for full details on the usage of @code{GDB}, including a section on
21120 its usage on programs. This manual should be consulted for full
21121 details. The section that follows is a brief introduction to the
21122 philosophy and use of @code{GDB}.
21123
21124 When GNAT programs are compiled, the compiler optionally writes debugging
21125 information into the generated object file, including information on
21126 line numbers, and on declared types and variables. This information is
21127 separate from the generated code. It makes the object files considerably
21128 larger, but it does not add to the size of the actual executable that
21129 will be loaded into memory, and has no impact on run-time performance. The
21130 generation of debug information is triggered by the use of the
21131 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
21132 used to carry out the compilations. It is important to emphasize that
21133 the use of these options does not change the generated code.
21134
21135 The debugging information is written in standard system formats that
21136 are used by many tools, including debuggers and profilers. The format
21137 of the information is typically designed to describe C types and
21138 semantics, but GNAT implements a translation scheme which allows full
21139 details about Ada types and variables to be encoded into these
21140 standard C formats. Details of this encoding scheme may be found in
21141 the file exp_dbug.ads in the GNAT source distribution. However, the
21142 details of this encoding are, in general, of no interest to a user,
21143 since @code{GDB} automatically performs the necessary decoding.
21144
21145 When a program is bound and linked, the debugging information is
21146 collected from the object files, and stored in the executable image of
21147 the program. Again, this process significantly increases the size of
21148 the generated executable file, but it does not increase the size of
21149 the executable program itself. Furthermore, if this program is run in
21150 the normal manner, it runs exactly as if the debug information were
21151 not present, and takes no more actual memory.
21152
21153 However, if the program is run under control of @code{GDB}, the
21154 debugger is activated. The image of the program is loaded, at which
21155 point it is ready to run. If a run command is given, then the program
21156 will run exactly as it would have if @code{GDB} were not present. This
21157 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
21158 entirely non-intrusive until a breakpoint is encountered. If no
21159 breakpoint is ever hit, the program will run exactly as it would if no
21160 debugger were present. When a breakpoint is hit, @code{GDB} accesses
21161 the debugging information and can respond to user commands to inspect
21162 variables, and more generally to report on the state of execution.
21163
21164 @c **************
21165 @node Running GDB
21166 @section Running GDB
21167
21168 @noindent
21169 This section describes how to initiate the debugger.
21170 @c The above sentence is really just filler, but it was otherwise
21171 @c clumsy to get the first paragraph nonindented given the conditional
21172 @c nature of the description
21173
21174 @ifclear vms
21175 The debugger can be launched from a @code{GPS} menu or
21176 directly from the command line. The description below covers the latter use.
21177 All the commands shown can be used in the @code{GPS} debug console window,
21178 but there are usually more GUI-based ways to achieve the same effect.
21179 @end ifclear
21180
21181 The command to run @code{GDB} is
21182
21183 @smallexample
21184 $ ^gdb program^GDB PROGRAM^
21185 @end smallexample
21186
21187 @noindent
21188 where @code{^program^PROGRAM^} is the name of the executable file. This
21189 activates the debugger and results in a prompt for debugger commands.
21190 The simplest command is simply @code{run}, which causes the program to run
21191 exactly as if the debugger were not present. The following section
21192 describes some of the additional commands that can be given to @code{GDB}.
21193
21194 @c *******************************
21195 @node Introduction to GDB Commands
21196 @section Introduction to GDB Commands
21197
21198 @noindent
21199 @code{GDB} contains a large repertoire of commands. @xref{Top,,
21200 Debugging with GDB, gdb, Debugging with GDB},
21201 @ifset vms
21202 located in the GNU:[DOCS] directory,
21203 @end ifset
21204 for extensive documentation on the use
21205 of these commands, together with examples of their use. Furthermore,
21206 the command @command{help} invoked from within GDB activates a simple help
21207 facility which summarizes the available commands and their options.
21208 In this section we summarize a few of the most commonly
21209 used commands to give an idea of what @code{GDB} is about. You should create
21210 a simple program with debugging information and experiment with the use of
21211 these @code{GDB} commands on the program as you read through the
21212 following section.
21213
21214 @table @code
21215 @item set args @var{arguments}
21216 The @var{arguments} list above is a list of arguments to be passed to
21217 the program on a subsequent run command, just as though the arguments
21218 had been entered on a normal invocation of the program. The @code{set args}
21219 command is not needed if the program does not require arguments.
21220
21221 @item run
21222 The @code{run} command causes execution of the program to start from
21223 the beginning. If the program is already running, that is to say if
21224 you are currently positioned at a breakpoint, then a prompt will ask
21225 for confirmation that you want to abandon the current execution and
21226 restart.
21227
21228 @item breakpoint @var{location}
21229 The breakpoint command sets a breakpoint, that is to say a point at which
21230 execution will halt and @code{GDB} will await further
21231 commands. @var{location} is
21232 either a line number within a file, given in the format @code{file:linenumber},
21233 or it is the name of a subprogram. If you request that a breakpoint be set on
21234 a subprogram that is overloaded, a prompt will ask you to specify on which of
21235 those subprograms you want to breakpoint. You can also
21236 specify that all of them should be breakpointed. If the program is run
21237 and execution encounters the breakpoint, then the program
21238 stops and @code{GDB} signals that the breakpoint was encountered by
21239 printing the line of code before which the program is halted.
21240
21241 @item catch exception @var{name}
21242 This command causes the program execution to stop whenever exception
21243 @var{name} is raised. If @var{name} is omitted, then the execution is
21244 suspended when any exception is raised.
21245
21246 @item print @var{expression}
21247 This will print the value of the given expression. Most simple
21248 Ada expression formats are properly handled by @code{GDB}, so the expression
21249 can contain function calls, variables, operators, and attribute references.
21250
21251 @item continue
21252 Continues execution following a breakpoint, until the next breakpoint or the
21253 termination of the program.
21254
21255 @item step
21256 Executes a single line after a breakpoint. If the next statement
21257 is a subprogram call, execution continues into (the first statement of)
21258 the called subprogram.
21259
21260 @item next
21261 Executes a single line. If this line is a subprogram call, executes and
21262 returns from the call.
21263
21264 @item list
21265 Lists a few lines around the current source location. In practice, it
21266 is usually more convenient to have a separate edit window open with the
21267 relevant source file displayed. Successive applications of this command
21268 print subsequent lines. The command can be given an argument which is a
21269 line number, in which case it displays a few lines around the specified one.
21270
21271 @item backtrace
21272 Displays a backtrace of the call chain. This command is typically
21273 used after a breakpoint has occurred, to examine the sequence of calls that
21274 leads to the current breakpoint. The display includes one line for each
21275 activation record (frame) corresponding to an active subprogram.
21276
21277 @item up
21278 At a breakpoint, @code{GDB} can display the values of variables local
21279 to the current frame. The command @code{up} can be used to
21280 examine the contents of other active frames, by moving the focus up
21281 the stack, that is to say from callee to caller, one frame at a time.
21282
21283 @item down
21284 Moves the focus of @code{GDB} down from the frame currently being
21285 examined to the frame of its callee (the reverse of the previous command),
21286
21287 @item frame @var{n}
21288 Inspect the frame with the given number. The value 0 denotes the frame
21289 of the current breakpoint, that is to say the top of the call stack.
21290
21291 @end table
21292
21293 @noindent
21294 The above list is a very short introduction to the commands that
21295 @code{GDB} provides. Important additional capabilities, including conditional
21296 breakpoints, the ability to execute command sequences on a breakpoint,
21297 the ability to debug at the machine instruction level and many other
21298 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
21299 Debugging with GDB}. Note that most commands can be abbreviated
21300 (for example, c for continue, bt for backtrace).
21301
21302 @node Using Ada Expressions
21303 @section Using Ada Expressions
21304 @cindex Ada expressions
21305
21306 @noindent
21307 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
21308 extensions. The philosophy behind the design of this subset is
21309
21310 @itemize @bullet
21311 @item
21312 That @code{GDB} should provide basic literals and access to operations for
21313 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
21314 leaving more sophisticated computations to subprograms written into the
21315 program (which therefore may be called from @code{GDB}).
21316
21317 @item
21318 That type safety and strict adherence to Ada language restrictions
21319 are not particularly important to the @code{GDB} user.
21320
21321 @item
21322 That brevity is important to the @code{GDB} user.
21323 @end itemize
21324
21325 @noindent
21326 Thus, for brevity, the debugger acts as if there were
21327 implicit @code{with} and @code{use} clauses in effect for all user-written
21328 packages, thus making it unnecessary to fully qualify most names with
21329 their packages, regardless of context. Where this causes ambiguity,
21330 @code{GDB} asks the user's intent.
21331
21332 For details on the supported Ada syntax, see @ref{Top,, Debugging with
21333 GDB, gdb, Debugging with GDB}.
21334
21335 @node Calling User-Defined Subprograms
21336 @section Calling User-Defined Subprograms
21337
21338 @noindent
21339 An important capability of @code{GDB} is the ability to call user-defined
21340 subprograms while debugging. This is achieved simply by entering
21341 a subprogram call statement in the form:
21342
21343 @smallexample
21344 call subprogram-name (parameters)
21345 @end smallexample
21346
21347 @noindent
21348 The keyword @code{call} can be omitted in the normal case where the
21349 @code{subprogram-name} does not coincide with any of the predefined
21350 @code{GDB} commands.
21351
21352 The effect is to invoke the given subprogram, passing it the
21353 list of parameters that is supplied. The parameters can be expressions and
21354 can include variables from the program being debugged. The
21355 subprogram must be defined
21356 at the library level within your program, and @code{GDB} will call the
21357 subprogram within the environment of your program execution (which
21358 means that the subprogram is free to access or even modify variables
21359 within your program).
21360
21361 The most important use of this facility is in allowing the inclusion of
21362 debugging routines that are tailored to particular data structures
21363 in your program. Such debugging routines can be written to provide a suitably
21364 high-level description of an abstract type, rather than a low-level dump
21365 of its physical layout. After all, the standard
21366 @code{GDB print} command only knows the physical layout of your
21367 types, not their abstract meaning. Debugging routines can provide information
21368 at the desired semantic level and are thus enormously useful.
21369
21370 For example, when debugging GNAT itself, it is crucial to have access to
21371 the contents of the tree nodes used to represent the program internally.
21372 But tree nodes are represented simply by an integer value (which in turn
21373 is an index into a table of nodes).
21374 Using the @code{print} command on a tree node would simply print this integer
21375 value, which is not very useful. But the PN routine (defined in file
21376 treepr.adb in the GNAT sources) takes a tree node as input, and displays
21377 a useful high level representation of the tree node, which includes the
21378 syntactic category of the node, its position in the source, the integers
21379 that denote descendant nodes and parent node, as well as varied
21380 semantic information. To study this example in more detail, you might want to
21381 look at the body of the PN procedure in the stated file.
21382
21383 @node Using the Next Command in a Function
21384 @section Using the Next Command in a Function
21385
21386 @noindent
21387 When you use the @code{next} command in a function, the current source
21388 location will advance to the next statement as usual. A special case
21389 arises in the case of a @code{return} statement.
21390
21391 Part of the code for a return statement is the ``epilog'' of the function.
21392 This is the code that returns to the caller. There is only one copy of
21393 this epilog code, and it is typically associated with the last return
21394 statement in the function if there is more than one return. In some
21395 implementations, this epilog is associated with the first statement
21396 of the function.
21397
21398 The result is that if you use the @code{next} command from a return
21399 statement that is not the last return statement of the function you
21400 may see a strange apparent jump to the last return statement or to
21401 the start of the function. You should simply ignore this odd jump.
21402 The value returned is always that from the first return statement
21403 that was stepped through.
21404
21405 @node Ada Exceptions
21406 @section Stopping when Ada Exceptions are Raised
21407 @cindex Exceptions
21408
21409 @noindent
21410 You can set catchpoints that stop the program execution when your program
21411 raises selected exceptions.
21412
21413 @table @code
21414 @item catch exception
21415 Set a catchpoint that stops execution whenever (any task in the) program
21416 raises any exception.
21417
21418 @item catch exception @var{name}
21419 Set a catchpoint that stops execution whenever (any task in the) program
21420 raises the exception @var{name}.
21421
21422 @item catch exception unhandled
21423 Set a catchpoint that stops executing whenever (any task in the) program
21424 raises an exception for which there is no handler.
21425
21426 @item info exceptions
21427 @itemx info exceptions @var{regexp}
21428 The @code{info exceptions} command permits the user to examine all defined
21429 exceptions within Ada programs. With a regular expression, @var{regexp}, as
21430 argument, prints out only those exceptions whose name matches @var{regexp}.
21431 @end table
21432
21433 @node Ada Tasks
21434 @section Ada Tasks
21435 @cindex Tasks
21436
21437 @noindent
21438 @code{GDB} allows the following task-related commands:
21439
21440 @table @code
21441 @item info tasks
21442 This command shows a list of current Ada tasks, as in the following example:
21443
21444 @smallexample
21445 @iftex
21446 @leftskip=0cm
21447 @end iftex
21448 (gdb) info tasks
21449 ID TID P-ID Thread Pri State Name
21450 1 8088000 0 807e000 15 Child Activation Wait main_task
21451 2 80a4000 1 80ae000 15 Accept/Select Wait b
21452 3 809a800 1 80a4800 15 Child Activation Wait a
21453 * 4 80ae800 3 80b8000 15 Running c
21454 @end smallexample
21455
21456 @noindent
21457 In this listing, the asterisk before the first task indicates it to be the
21458 currently running task. The first column lists the task ID that is used
21459 to refer to tasks in the following commands.
21460
21461 @item break @var{linespec} task @var{taskid}
21462 @itemx break @var{linespec} task @var{taskid} if @dots{}
21463 @cindex Breakpoints and tasks
21464 These commands are like the @code{break @dots{} thread @dots{}}.
21465 @var{linespec} specifies source lines.
21466
21467 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
21468 to specify that you only want @code{GDB} to stop the program when a
21469 particular Ada task reaches this breakpoint. @var{taskid} is one of the
21470 numeric task identifiers assigned by @code{GDB}, shown in the first
21471 column of the @samp{info tasks} display.
21472
21473 If you do not specify @samp{task @var{taskid}} when you set a
21474 breakpoint, the breakpoint applies to @emph{all} tasks of your
21475 program.
21476
21477 You can use the @code{task} qualifier on conditional breakpoints as
21478 well; in this case, place @samp{task @var{taskid}} before the
21479 breakpoint condition (before the @code{if}).
21480
21481 @item task @var{taskno}
21482 @cindex Task switching
21483
21484 This command allows to switch to the task referred by @var{taskno}. In
21485 particular, This allows to browse the backtrace of the specified
21486 task. It is advised to switch back to the original task before
21487 continuing execution otherwise the scheduling of the program may be
21488 perturbed.
21489 @end table
21490
21491 @noindent
21492 For more detailed information on the tasking support,
21493 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
21494
21495 @node Debugging Generic Units
21496 @section Debugging Generic Units
21497 @cindex Debugging Generic Units
21498 @cindex Generics
21499
21500 @noindent
21501 GNAT always uses code expansion for generic instantiation. This means that
21502 each time an instantiation occurs, a complete copy of the original code is
21503 made, with appropriate substitutions of formals by actuals.
21504
21505 It is not possible to refer to the original generic entities in
21506 @code{GDB}, but it is always possible to debug a particular instance of
21507 a generic, by using the appropriate expanded names. For example, if we have
21508
21509 @smallexample @c ada
21510 @group
21511 @cartouche
21512 procedure g is
21513
21514 generic package k is
21515 procedure kp (v1 : in out integer);
21516 end k;
21517
21518 package body k is
21519 procedure kp (v1 : in out integer) is
21520 begin
21521 v1 := v1 + 1;
21522 end kp;
21523 end k;
21524
21525 package k1 is new k;
21526 package k2 is new k;
21527
21528 var : integer := 1;
21529
21530 begin
21531 k1.kp (var);
21532 k2.kp (var);
21533 k1.kp (var);
21534 k2.kp (var);
21535 end;
21536 @end cartouche
21537 @end group
21538 @end smallexample
21539
21540 @noindent
21541 Then to break on a call to procedure kp in the k2 instance, simply
21542 use the command:
21543
21544 @smallexample
21545 (gdb) break g.k2.kp
21546 @end smallexample
21547
21548 @noindent
21549 When the breakpoint occurs, you can step through the code of the
21550 instance in the normal manner and examine the values of local variables, as for
21551 other units.
21552
21553 @node Remote Debugging with gdbserver
21554 @section Remote Debugging with gdbserver
21555 @cindex Remote Debugging with gdbserver
21556
21557 @noindent
21558 On platforms where gdbserver is supported, it is possible to use this tool
21559 to debug your application remotely. This can be useful in situations
21560 where the program needs to be run on a target host that is different
21561 from the host used for development, particularly when the target has
21562 a limited amount of resources (either CPU and/or memory).
21563
21564 To do so, start your program using gdbserver on the target machine.
21565 gdbserver then automatically suspends the execution of your program
21566 at its entry point, waiting for a debugger to connect to it. The
21567 following commands starts an application and tells gdbserver to
21568 wait for a connection with the debugger on localhost port 4444.
21569
21570 @smallexample
21571 $ gdbserver localhost:4444 program
21572 Process program created; pid = 5685
21573 Listening on port 4444
21574 @end smallexample
21575
21576 Once gdbserver has started listening, we can tell the debugger to establish
21577 a connection with this gdbserver, and then start the same debugging session
21578 as if the program was being debugged on the same host, directly under
21579 the control of GDB.
21580
21581 @smallexample
21582 $ gdb program
21583 (gdb) target remote targethost:4444
21584 Remote debugging using targethost:4444
21585 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
21586 (gdb) b foo.adb:3
21587 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
21588 (gdb) continue
21589 Continuing.
21590
21591 Breakpoint 1, foo () at foo.adb:4
21592 4 end foo;
21593 @end smallexample
21594
21595 It is also possible to use gdbserver to attach to an already running
21596 program, in which case the execution of that program is simply suspended
21597 until the connection between the debugger and gdbserver is established.
21598
21599 For more information on how to use gdbserver, @ref{Top, Server, Using
21600 the gdbserver Program, gdb, Debugging with GDB}. @value{EDITION} provides support
21601 for gdbserver on x86-linux, x86-windows and x86_64-linux.
21602
21603 @node GNAT Abnormal Termination or Failure to Terminate
21604 @section GNAT Abnormal Termination or Failure to Terminate
21605 @cindex GNAT Abnormal Termination or Failure to Terminate
21606
21607 @noindent
21608 When presented with programs that contain serious errors in syntax
21609 or semantics,
21610 GNAT may on rare occasions experience problems in operation, such
21611 as aborting with a
21612 segmentation fault or illegal memory access, raising an internal
21613 exception, terminating abnormally, or failing to terminate at all.
21614 In such cases, you can activate
21615 various features of GNAT that can help you pinpoint the construct in your
21616 program that is the likely source of the problem.
21617
21618 The following strategies are presented in increasing order of
21619 difficulty, corresponding to your experience in using GNAT and your
21620 familiarity with compiler internals.
21621
21622 @enumerate
21623 @item
21624 Run @command{gcc} with the @option{-gnatf}. This first
21625 switch causes all errors on a given line to be reported. In its absence,
21626 only the first error on a line is displayed.
21627
21628 The @option{-gnatdO} switch causes errors to be displayed as soon as they
21629 are encountered, rather than after compilation is terminated. If GNAT
21630 terminates prematurely or goes into an infinite loop, the last error
21631 message displayed may help to pinpoint the culprit.
21632
21633 @item
21634 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
21635 mode, @command{gcc} produces ongoing information about the progress of the
21636 compilation and provides the name of each procedure as code is
21637 generated. This switch allows you to find which Ada procedure was being
21638 compiled when it encountered a code generation problem.
21639
21640 @item
21641 @cindex @option{-gnatdc} switch
21642 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
21643 switch that does for the front-end what @option{^-v^VERBOSE^} does
21644 for the back end. The system prints the name of each unit,
21645 either a compilation unit or nested unit, as it is being analyzed.
21646 @item
21647 Finally, you can start
21648 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
21649 front-end of GNAT, and can be run independently (normally it is just
21650 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
21651 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
21652 @code{where} command is the first line of attack; the variable
21653 @code{lineno} (seen by @code{print lineno}), used by the second phase of
21654 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
21655 which the execution stopped, and @code{input_file name} indicates the name of
21656 the source file.
21657 @end enumerate
21658
21659 @node Naming Conventions for GNAT Source Files
21660 @section Naming Conventions for GNAT Source Files
21661
21662 @noindent
21663 In order to examine the workings of the GNAT system, the following
21664 brief description of its organization may be helpful:
21665
21666 @itemize @bullet
21667 @item
21668 Files with prefix @file{^sc^SC^} contain the lexical scanner.
21669
21670 @item
21671 All files prefixed with @file{^par^PAR^} are components of the parser. The
21672 numbers correspond to chapters of the Ada Reference Manual. For example,
21673 parsing of select statements can be found in @file{par-ch9.adb}.
21674
21675 @item
21676 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
21677 numbers correspond to chapters of the Ada standard. For example, all
21678 issues involving context clauses can be found in @file{sem_ch10.adb}. In
21679 addition, some features of the language require sufficient special processing
21680 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
21681 dynamic dispatching, etc.
21682
21683 @item
21684 All files prefixed with @file{^exp^EXP^} perform normalization and
21685 expansion of the intermediate representation (abstract syntax tree, or AST).
21686 these files use the same numbering scheme as the parser and semantics files.
21687 For example, the construction of record initialization procedures is done in
21688 @file{exp_ch3.adb}.
21689
21690 @item
21691 The files prefixed with @file{^bind^BIND^} implement the binder, which
21692 verifies the consistency of the compilation, determines an order of
21693 elaboration, and generates the bind file.
21694
21695 @item
21696 The files @file{atree.ads} and @file{atree.adb} detail the low-level
21697 data structures used by the front-end.
21698
21699 @item
21700 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
21701 the abstract syntax tree as produced by the parser.
21702
21703 @item
21704 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
21705 all entities, computed during semantic analysis.
21706
21707 @item
21708 Library management issues are dealt with in files with prefix
21709 @file{^lib^LIB^}.
21710
21711 @item
21712 @findex Ada
21713 @cindex Annex A
21714 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
21715 defined in Annex A.
21716
21717 @item
21718 @findex Interfaces
21719 @cindex Annex B
21720 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
21721 defined in Annex B.
21722
21723 @item
21724 @findex System
21725 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
21726 both language-defined children and GNAT run-time routines.
21727
21728 @item
21729 @findex GNAT
21730 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
21731 general-purpose packages, fully documented in their specs. All
21732 the other @file{.c} files are modifications of common @command{gcc} files.
21733 @end itemize
21734
21735 @node Getting Internal Debugging Information
21736 @section Getting Internal Debugging Information
21737
21738 @noindent
21739 Most compilers have internal debugging switches and modes. GNAT
21740 does also, except GNAT internal debugging switches and modes are not
21741 secret. A summary and full description of all the compiler and binder
21742 debug flags are in the file @file{debug.adb}. You must obtain the
21743 sources of the compiler to see the full detailed effects of these flags.
21744
21745 The switches that print the source of the program (reconstructed from
21746 the internal tree) are of general interest for user programs, as are the
21747 options to print
21748 the full internal tree, and the entity table (the symbol table
21749 information). The reconstructed source provides a readable version of the
21750 program after the front-end has completed analysis and expansion,
21751 and is useful when studying the performance of specific constructs.
21752 For example, constraint checks are indicated, complex aggregates
21753 are replaced with loops and assignments, and tasking primitives
21754 are replaced with run-time calls.
21755
21756 @node Stack Traceback
21757 @section Stack Traceback
21758 @cindex traceback
21759 @cindex stack traceback
21760 @cindex stack unwinding
21761
21762 @noindent
21763 Traceback is a mechanism to display the sequence of subprogram calls that
21764 leads to a specified execution point in a program. Often (but not always)
21765 the execution point is an instruction at which an exception has been raised.
21766 This mechanism is also known as @i{stack unwinding} because it obtains
21767 its information by scanning the run-time stack and recovering the activation
21768 records of all active subprograms. Stack unwinding is one of the most
21769 important tools for program debugging.
21770
21771 The first entry stored in traceback corresponds to the deepest calling level,
21772 that is to say the subprogram currently executing the instruction
21773 from which we want to obtain the traceback.
21774
21775 Note that there is no runtime performance penalty when stack traceback
21776 is enabled, and no exception is raised during program execution.
21777
21778 @menu
21779 * Non-Symbolic Traceback::
21780 * Symbolic Traceback::
21781 @end menu
21782
21783 @node Non-Symbolic Traceback
21784 @subsection Non-Symbolic Traceback
21785 @cindex traceback, non-symbolic
21786
21787 @noindent
21788 Note: this feature is not supported on all platforms. See
21789 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
21790 platforms.
21791
21792 @menu
21793 * Tracebacks From an Unhandled Exception::
21794 * Tracebacks From Exception Occurrences (non-symbolic)::
21795 * Tracebacks From Anywhere in a Program (non-symbolic)::
21796 @end menu
21797
21798 @node Tracebacks From an Unhandled Exception
21799 @subsubsection Tracebacks From an Unhandled Exception
21800
21801 @noindent
21802 A runtime non-symbolic traceback is a list of addresses of call instructions.
21803 To enable this feature you must use the @option{-E}
21804 @code{gnatbind}'s option. With this option a stack traceback is stored as part
21805 of exception information. You can retrieve this information using the
21806 @code{addr2line} tool.
21807
21808 Here is a simple example:
21809
21810 @smallexample @c ada
21811 @cartouche
21812 procedure STB is
21813
21814 procedure P1 is
21815 begin
21816 raise Constraint_Error;
21817 end P1;
21818
21819 procedure P2 is
21820 begin
21821 P1;
21822 end P2;
21823
21824 begin
21825 P2;
21826 end STB;
21827 @end cartouche
21828 @end smallexample
21829
21830 @smallexample
21831 $ gnatmake stb -bargs -E
21832 $ stb
21833
21834 Execution terminated by unhandled exception
21835 Exception name: CONSTRAINT_ERROR
21836 Message: stb.adb:5
21837 Call stack traceback locations:
21838 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21839 @end smallexample
21840
21841 @noindent
21842 As we see the traceback lists a sequence of addresses for the unhandled
21843 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
21844 guess that this exception come from procedure P1. To translate these
21845 addresses into the source lines where the calls appear, the
21846 @code{addr2line} tool, described below, is invaluable. The use of this tool
21847 requires the program to be compiled with debug information.
21848
21849 @smallexample
21850 $ gnatmake -g stb -bargs -E
21851 $ stb
21852
21853 Execution terminated by unhandled exception
21854 Exception name: CONSTRAINT_ERROR
21855 Message: stb.adb:5
21856 Call stack traceback locations:
21857 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21858
21859 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
21860 0x4011f1 0x77e892a4
21861
21862 00401373 at d:/stb/stb.adb:5
21863 0040138B at d:/stb/stb.adb:10
21864 0040139C at d:/stb/stb.adb:14
21865 00401335 at d:/stb/b~stb.adb:104
21866 004011C4 at /build/@dots{}/crt1.c:200
21867 004011F1 at /build/@dots{}/crt1.c:222
21868 77E892A4 in ?? at ??:0
21869 @end smallexample
21870
21871 @noindent
21872 The @code{addr2line} tool has several other useful options:
21873
21874 @table @code
21875 @item --functions
21876 to get the function name corresponding to any location
21877
21878 @item --demangle=gnat
21879 to use the gnat decoding mode for the function names. Note that
21880 for binutils version 2.9.x the option is simply @option{--demangle}.
21881 @end table
21882
21883 @smallexample
21884 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
21885 0x40139c 0x401335 0x4011c4 0x4011f1
21886
21887 00401373 in stb.p1 at d:/stb/stb.adb:5
21888 0040138B in stb.p2 at d:/stb/stb.adb:10
21889 0040139C in stb at d:/stb/stb.adb:14
21890 00401335 in main at d:/stb/b~stb.adb:104
21891 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
21892 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
21893 @end smallexample
21894
21895 @noindent
21896 From this traceback we can see that the exception was raised in
21897 @file{stb.adb} at line 5, which was reached from a procedure call in
21898 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
21899 which contains the call to the main program.
21900 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
21901 and the output will vary from platform to platform.
21902
21903 It is also possible to use @code{GDB} with these traceback addresses to debug
21904 the program. For example, we can break at a given code location, as reported
21905 in the stack traceback:
21906
21907 @smallexample
21908 $ gdb -nw stb
21909 @ifclear vms
21910 @noindent
21911 Furthermore, this feature is not implemented inside Windows DLL. Only
21912 the non-symbolic traceback is reported in this case.
21913 @end ifclear
21914
21915 (gdb) break *0x401373
21916 Breakpoint 1 at 0x401373: file stb.adb, line 5.
21917 @end smallexample
21918
21919 @noindent
21920 It is important to note that the stack traceback addresses
21921 do not change when debug information is included. This is particularly useful
21922 because it makes it possible to release software without debug information (to
21923 minimize object size), get a field report that includes a stack traceback
21924 whenever an internal bug occurs, and then be able to retrieve the sequence
21925 of calls with the same program compiled with debug information.
21926
21927 @node Tracebacks From Exception Occurrences (non-symbolic)
21928 @subsubsection Tracebacks From Exception Occurrences
21929
21930 @noindent
21931 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
21932 The stack traceback is attached to the exception information string, and can
21933 be retrieved in an exception handler within the Ada program, by means of the
21934 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
21935
21936 @smallexample @c ada
21937 with Ada.Text_IO;
21938 with Ada.Exceptions;
21939
21940 procedure STB is
21941
21942 use Ada;
21943 use Ada.Exceptions;
21944
21945 procedure P1 is
21946 K : Positive := 1;
21947 begin
21948 K := K - 1;
21949 exception
21950 when E : others =>
21951 Text_IO.Put_Line (Exception_Information (E));
21952 end P1;
21953
21954 procedure P2 is
21955 begin
21956 P1;
21957 end P2;
21958
21959 begin
21960 P2;
21961 end STB;
21962 @end smallexample
21963
21964 @noindent
21965 This program will output:
21966
21967 @smallexample
21968 $ stb
21969
21970 Exception name: CONSTRAINT_ERROR
21971 Message: stb.adb:12
21972 Call stack traceback locations:
21973 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
21974 @end smallexample
21975
21976 @node Tracebacks From Anywhere in a Program (non-symbolic)
21977 @subsubsection Tracebacks From Anywhere in a Program
21978
21979 @noindent
21980 It is also possible to retrieve a stack traceback from anywhere in a
21981 program. For this you need to
21982 use the @code{GNAT.Traceback} API. This package includes a procedure called
21983 @code{Call_Chain} that computes a complete stack traceback, as well as useful
21984 display procedures described below. It is not necessary to use the
21985 @option{-E gnatbind} option in this case, because the stack traceback mechanism
21986 is invoked explicitly.
21987
21988 @noindent
21989 In the following example we compute a traceback at a specific location in
21990 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
21991 convert addresses to strings:
21992
21993 @smallexample @c ada
21994 with Ada.Text_IO;
21995 with GNAT.Traceback;
21996 with GNAT.Debug_Utilities;
21997
21998 procedure STB is
21999
22000 use Ada;
22001 use GNAT;
22002 use GNAT.Traceback;
22003
22004 procedure P1 is
22005 TB : Tracebacks_Array (1 .. 10);
22006 -- We are asking for a maximum of 10 stack frames.
22007 Len : Natural;
22008 -- Len will receive the actual number of stack frames returned.
22009 begin
22010 Call_Chain (TB, Len);
22011
22012 Text_IO.Put ("In STB.P1 : ");
22013
22014 for K in 1 .. Len loop
22015 Text_IO.Put (Debug_Utilities.Image (TB (K)));
22016 Text_IO.Put (' ');
22017 end loop;
22018
22019 Text_IO.New_Line;
22020 end P1;
22021
22022 procedure P2 is
22023 begin
22024 P1;
22025 end P2;
22026
22027 begin
22028 P2;
22029 end STB;
22030 @end smallexample
22031
22032 @smallexample
22033 $ gnatmake -g stb
22034 $ stb
22035
22036 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
22037 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
22038 @end smallexample
22039
22040 @noindent
22041 You can then get further information by invoking the @code{addr2line}
22042 tool as described earlier (note that the hexadecimal addresses
22043 need to be specified in C format, with a leading ``0x'').
22044
22045 @node Symbolic Traceback
22046 @subsection Symbolic Traceback
22047 @cindex traceback, symbolic
22048
22049 @noindent
22050 A symbolic traceback is a stack traceback in which procedure names are
22051 associated with each code location.
22052
22053 @noindent
22054 Note that this feature is not supported on all platforms. See
22055 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
22056 list of currently supported platforms.
22057
22058 @noindent
22059 Note that the symbolic traceback requires that the program be compiled
22060 with debug information. If it is not compiled with debug information
22061 only the non-symbolic information will be valid.
22062
22063 @menu
22064 * Tracebacks From Exception Occurrences (symbolic)::
22065 * Tracebacks From Anywhere in a Program (symbolic)::
22066 @end menu
22067
22068 @node Tracebacks From Exception Occurrences (symbolic)
22069 @subsubsection Tracebacks From Exception Occurrences
22070
22071 @smallexample @c ada
22072 with Ada.Text_IO;
22073 with GNAT.Traceback.Symbolic;
22074
22075 procedure STB is
22076
22077 procedure P1 is
22078 begin
22079 raise Constraint_Error;
22080 end P1;
22081
22082 procedure P2 is
22083 begin
22084 P1;
22085 end P2;
22086
22087 procedure P3 is
22088 begin
22089 P2;
22090 end P3;
22091
22092 begin
22093 P3;
22094 exception
22095 when E : others =>
22096 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
22097 end STB;
22098 @end smallexample
22099
22100 @smallexample
22101 $ gnatmake -g .\stb -bargs -E
22102 $ stb
22103
22104 0040149F in stb.p1 at stb.adb:8
22105 004014B7 in stb.p2 at stb.adb:13
22106 004014CF in stb.p3 at stb.adb:18
22107 004015DD in ada.stb at stb.adb:22
22108 00401461 in main at b~stb.adb:168
22109 004011C4 in __mingw_CRTStartup at crt1.c:200
22110 004011F1 in mainCRTStartup at crt1.c:222
22111 77E892A4 in ?? at ??:0
22112 @end smallexample
22113
22114 @noindent
22115 In the above example the ``.\'' syntax in the @command{gnatmake} command
22116 is currently required by @command{addr2line} for files that are in
22117 the current working directory.
22118 Moreover, the exact sequence of linker options may vary from platform
22119 to platform.
22120 The above @option{-largs} section is for Windows platforms. By contrast,
22121 under Unix there is no need for the @option{-largs} section.
22122 Differences across platforms are due to details of linker implementation.
22123
22124 @node Tracebacks From Anywhere in a Program (symbolic)
22125 @subsubsection Tracebacks From Anywhere in a Program
22126
22127 @noindent
22128 It is possible to get a symbolic stack traceback
22129 from anywhere in a program, just as for non-symbolic tracebacks.
22130 The first step is to obtain a non-symbolic
22131 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
22132 information. Here is an example:
22133
22134 @smallexample @c ada
22135 with Ada.Text_IO;
22136 with GNAT.Traceback;
22137 with GNAT.Traceback.Symbolic;
22138
22139 procedure STB is
22140
22141 use Ada;
22142 use GNAT.Traceback;
22143 use GNAT.Traceback.Symbolic;
22144
22145 procedure P1 is
22146 TB : Tracebacks_Array (1 .. 10);
22147 -- We are asking for a maximum of 10 stack frames.
22148 Len : Natural;
22149 -- Len will receive the actual number of stack frames returned.
22150 begin
22151 Call_Chain (TB, Len);
22152 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
22153 end P1;
22154
22155 procedure P2 is
22156 begin
22157 P1;
22158 end P2;
22159
22160 begin
22161 P2;
22162 end STB;
22163 @end smallexample
22164
22165 @c ******************************
22166 @ifset vms
22167 @node Compatibility with HP Ada
22168 @chapter Compatibility with HP Ada
22169 @cindex Compatibility
22170
22171 @noindent
22172 @cindex DEC Ada
22173 @cindex HP Ada
22174 @cindex Compatibility between GNAT and HP Ada
22175 This chapter compares HP Ada (formerly known as ``DEC Ada'')
22176 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
22177 GNAT is highly compatible
22178 with HP Ada, and it should generally be straightforward to port code
22179 from the HP Ada environment to GNAT. However, there are a few language
22180 and implementation differences of which the user must be aware. These
22181 differences are discussed in this chapter. In
22182 addition, the operating environment and command structure for the
22183 compiler are different, and these differences are also discussed.
22184
22185 For further details on these and other compatibility issues,
22186 see Appendix E of the HP publication
22187 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
22188
22189 Except where otherwise indicated, the description of GNAT for OpenVMS
22190 applies to both the Alpha and I64 platforms.
22191
22192 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
22193 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22194
22195 The discussion in this chapter addresses specifically the implementation
22196 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
22197 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
22198 GNAT always follows the Alpha implementation.
22199
22200 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
22201 attributes are recognized, although only a subset of them can sensibly
22202 be implemented. The description of pragmas in
22203 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
22204 indicates whether or not they are applicable to non-VMS systems.
22205
22206 @menu
22207 * Ada Language Compatibility::
22208 * Differences in the Definition of Package System::
22209 * Language-Related Features::
22210 * The Package STANDARD::
22211 * The Package SYSTEM::
22212 * Tasking and Task-Related Features::
22213 * Pragmas and Pragma-Related Features::
22214 * Library of Predefined Units::
22215 * Bindings::
22216 * Main Program Definition::
22217 * Implementation-Defined Attributes::
22218 * Compiler and Run-Time Interfacing::
22219 * Program Compilation and Library Management::
22220 * Input-Output::
22221 * Implementation Limits::
22222 * Tools and Utilities::
22223 @end menu
22224
22225 @node Ada Language Compatibility
22226 @section Ada Language Compatibility
22227
22228 @noindent
22229 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
22230 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
22231 with Ada 83, and therefore Ada 83 programs will compile
22232 and run under GNAT with
22233 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
22234 provides details on specific incompatibilities.
22235
22236 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
22237 as well as the pragma @code{ADA_83}, to force the compiler to
22238 operate in Ada 83 mode. This mode does not guarantee complete
22239 conformance to Ada 83, but in practice is sufficient to
22240 eliminate most sources of incompatibilities.
22241 In particular, it eliminates the recognition of the
22242 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
22243 in Ada 83 programs is legal, and handles the cases of packages
22244 with optional bodies, and generics that instantiate unconstrained
22245 types without the use of @code{(<>)}.
22246
22247 @node Differences in the Definition of Package System
22248 @section Differences in the Definition of Package @code{System}
22249
22250 @noindent
22251 An Ada compiler is allowed to add
22252 implementation-dependent declarations to package @code{System}.
22253 In normal mode,
22254 GNAT does not take advantage of this permission, and the version of
22255 @code{System} provided by GNAT exactly matches that defined in the Ada
22256 Reference Manual.
22257
22258 However, HP Ada adds an extensive set of declarations to package
22259 @code{System},
22260 as fully documented in the HP Ada manuals. To minimize changes required
22261 for programs that make use of these extensions, GNAT provides the pragma
22262 @code{Extend_System} for extending the definition of package System. By using:
22263 @cindex pragma @code{Extend_System}
22264 @cindex @code{Extend_System} pragma
22265
22266 @smallexample @c ada
22267 @group
22268 @cartouche
22269 pragma Extend_System (Aux_DEC);
22270 @end cartouche
22271 @end group
22272 @end smallexample
22273
22274 @noindent
22275 the set of definitions in @code{System} is extended to include those in
22276 package @code{System.Aux_DEC}.
22277 @cindex @code{System.Aux_DEC} package
22278 @cindex @code{Aux_DEC} package (child of @code{System})
22279 These definitions are incorporated directly into package @code{System},
22280 as though they had been declared there. For a
22281 list of the declarations added, see the spec of this package,
22282 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
22283 @cindex @file{s-auxdec.ads} file
22284 The pragma @code{Extend_System} is a configuration pragma, which means that
22285 it can be placed in the file @file{gnat.adc}, so that it will automatically
22286 apply to all subsequent compilations. See @ref{Configuration Pragmas},
22287 for further details.
22288
22289 An alternative approach that avoids the use of the non-standard
22290 @code{Extend_System} pragma is to add a context clause to the unit that
22291 references these facilities:
22292
22293 @smallexample @c ada
22294 @cartouche
22295 with System.Aux_DEC;
22296 use System.Aux_DEC;
22297 @end cartouche
22298 @end smallexample
22299
22300 @noindent
22301 The effect is not quite semantically identical to incorporating
22302 the declarations directly into package @code{System},
22303 but most programs will not notice a difference
22304 unless they use prefix notation (e.g.@: @code{System.Integer_8})
22305 to reference the entities directly in package @code{System}.
22306 For units containing such references,
22307 the prefixes must either be removed, or the pragma @code{Extend_System}
22308 must be used.
22309
22310 @node Language-Related Features
22311 @section Language-Related Features
22312
22313 @noindent
22314 The following sections highlight differences in types,
22315 representations of types, operations, alignment, and
22316 related topics.
22317
22318 @menu
22319 * Integer Types and Representations::
22320 * Floating-Point Types and Representations::
22321 * Pragmas Float_Representation and Long_Float::
22322 * Fixed-Point Types and Representations::
22323 * Record and Array Component Alignment::
22324 * Address Clauses::
22325 * Other Representation Clauses::
22326 @end menu
22327
22328 @node Integer Types and Representations
22329 @subsection Integer Types and Representations
22330
22331 @noindent
22332 The set of predefined integer types is identical in HP Ada and GNAT.
22333 Furthermore the representation of these integer types is also identical,
22334 including the capability of size clauses forcing biased representation.
22335
22336 In addition,
22337 HP Ada for OpenVMS Alpha systems has defined the
22338 following additional integer types in package @code{System}:
22339
22340 @itemize @bullet
22341
22342 @item
22343 @code{INTEGER_8}
22344
22345 @item
22346 @code{INTEGER_16}
22347
22348 @item
22349 @code{INTEGER_32}
22350
22351 @item
22352 @code{INTEGER_64}
22353
22354 @item
22355 @code{LARGEST_INTEGER}
22356 @end itemize
22357
22358 @noindent
22359 In GNAT, the first four of these types may be obtained from the
22360 standard Ada package @code{Interfaces}.
22361 Alternatively, by use of the pragma @code{Extend_System}, identical
22362 declarations can be referenced directly in package @code{System}.
22363 On both GNAT and HP Ada, the maximum integer size is 64 bits.
22364
22365 @node Floating-Point Types and Representations
22366 @subsection Floating-Point Types and Representations
22367 @cindex Floating-Point types
22368
22369 @noindent
22370 The set of predefined floating-point types is identical in HP Ada and GNAT.
22371 Furthermore the representation of these floating-point
22372 types is also identical. One important difference is that the default
22373 representation for HP Ada is @code{VAX_Float}, but the default representation
22374 for GNAT is IEEE.
22375
22376 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
22377 pragma @code{Float_Representation} as described in the HP Ada
22378 documentation.
22379 For example, the declarations:
22380
22381 @smallexample @c ada
22382 @cartouche
22383 type F_Float is digits 6;
22384 pragma Float_Representation (VAX_Float, F_Float);
22385 @end cartouche
22386 @end smallexample
22387
22388 @noindent
22389 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
22390 format.
22391 This set of declarations actually appears in @code{System.Aux_DEC},
22392 which contains
22393 the full set of additional floating-point declarations provided in
22394 the HP Ada version of package @code{System}.
22395 This and similar declarations may be accessed in a user program
22396 by using pragma @code{Extend_System}. The use of this
22397 pragma, and the related pragma @code{Long_Float} is described in further
22398 detail in the following section.
22399
22400 @node Pragmas Float_Representation and Long_Float
22401 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
22402
22403 @noindent
22404 HP Ada provides the pragma @code{Float_Representation}, which
22405 acts as a program library switch to allow control over
22406 the internal representation chosen for the predefined
22407 floating-point types declared in the package @code{Standard}.
22408 The format of this pragma is as follows:
22409
22410 @smallexample @c ada
22411 @cartouche
22412 pragma Float_Representation(VAX_Float | IEEE_Float);
22413 @end cartouche
22414 @end smallexample
22415
22416 @noindent
22417 This pragma controls the representation of floating-point
22418 types as follows:
22419
22420 @itemize @bullet
22421 @item
22422 @code{VAX_Float} specifies that floating-point
22423 types are represented by default with the VAX system hardware types
22424 @code{F-floating}, @code{D-floating}, @code{G-floating}.
22425 Note that the @code{H-floating}
22426 type was available only on VAX systems, and is not available
22427 in either HP Ada or GNAT.
22428
22429 @item
22430 @code{IEEE_Float} specifies that floating-point
22431 types are represented by default with the IEEE single and
22432 double floating-point types.
22433 @end itemize
22434
22435 @noindent
22436 GNAT provides an identical implementation of the pragma
22437 @code{Float_Representation}, except that it functions as a
22438 configuration pragma. Note that the
22439 notion of configuration pragma corresponds closely to the
22440 HP Ada notion of a program library switch.
22441
22442 When no pragma is used in GNAT, the default is @code{IEEE_Float},
22443 which is different
22444 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
22445 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
22446 advisable to change the format of numbers passed to standard library
22447 routines, and if necessary explicit type conversions may be needed.
22448
22449 The use of @code{IEEE_Float} is recommended in GNAT since it is more
22450 efficient, and (given that it conforms to an international standard)
22451 potentially more portable.
22452 The situation in which @code{VAX_Float} may be useful is in interfacing
22453 to existing code and data that expect the use of @code{VAX_Float}.
22454 In such a situation use the predefined @code{VAX_Float}
22455 types in package @code{System}, as extended by
22456 @code{Extend_System}. For example, use @code{System.F_Float}
22457 to specify the 32-bit @code{F-Float} format.
22458
22459 @noindent
22460 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
22461 to allow control over the internal representation chosen
22462 for the predefined type @code{Long_Float} and for floating-point
22463 type declarations with digits specified in the range 7 .. 15.
22464 The format of this pragma is as follows:
22465
22466 @smallexample @c ada
22467 @cartouche
22468 pragma Long_Float (D_FLOAT | G_FLOAT);
22469 @end cartouche
22470 @end smallexample
22471
22472 @node Fixed-Point Types and Representations
22473 @subsection Fixed-Point Types and Representations
22474
22475 @noindent
22476 On HP Ada for OpenVMS Alpha systems, rounding is
22477 away from zero for both positive and negative numbers.
22478 Therefore, @code{+0.5} rounds to @code{1},
22479 and @code{-0.5} rounds to @code{-1}.
22480
22481 On GNAT the results of operations
22482 on fixed-point types are in accordance with the Ada
22483 rules. In particular, results of operations on decimal
22484 fixed-point types are truncated.
22485
22486 @node Record and Array Component Alignment
22487 @subsection Record and Array Component Alignment
22488
22489 @noindent
22490 On HP Ada for OpenVMS Alpha, all non-composite components
22491 are aligned on natural boundaries. For example, 1-byte
22492 components are aligned on byte boundaries, 2-byte
22493 components on 2-byte boundaries, 4-byte components on 4-byte
22494 byte boundaries, and so on. The OpenVMS Alpha hardware
22495 runs more efficiently with naturally aligned data.
22496
22497 On GNAT, alignment rules are compatible
22498 with HP Ada for OpenVMS Alpha.
22499
22500 @node Address Clauses
22501 @subsection Address Clauses
22502
22503 @noindent
22504 In HP Ada and GNAT, address clauses are supported for
22505 objects and imported subprograms.
22506 The predefined type @code{System.Address} is a private type
22507 in both compilers on Alpha OpenVMS, with the same representation
22508 (it is simply a machine pointer). Addition, subtraction, and comparison
22509 operations are available in the standard Ada package
22510 @code{System.Storage_Elements}, or in package @code{System}
22511 if it is extended to include @code{System.Aux_DEC} using a
22512 pragma @code{Extend_System} as previously described.
22513
22514 Note that code that @code{with}'s both this extended package @code{System}
22515 and the package @code{System.Storage_Elements} should not @code{use}
22516 both packages, or ambiguities will result. In general it is better
22517 not to mix these two sets of facilities. The Ada package was
22518 designed specifically to provide the kind of features that HP Ada
22519 adds directly to package @code{System}.
22520
22521 The type @code{System.Address} is a 64-bit integer type in GNAT for
22522 I64 OpenVMS. For more information,
22523 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22524
22525 GNAT is compatible with HP Ada in its handling of address
22526 clauses, except for some limitations in
22527 the form of address clauses for composite objects with
22528 initialization. Such address clauses are easily replaced
22529 by the use of an explicitly-defined constant as described
22530 in the Ada Reference Manual (13.1(22)). For example, the sequence
22531 of declarations:
22532
22533 @smallexample @c ada
22534 @cartouche
22535 X, Y : Integer := Init_Func;
22536 Q : String (X .. Y) := "abc";
22537 @dots{}
22538 for Q'Address use Compute_Address;
22539 @end cartouche
22540 @end smallexample
22541
22542 @noindent
22543 will be rejected by GNAT, since the address cannot be computed at the time
22544 that @code{Q} is declared. To achieve the intended effect, write instead:
22545
22546 @smallexample @c ada
22547 @group
22548 @cartouche
22549 X, Y : Integer := Init_Func;
22550 Q_Address : constant Address := Compute_Address;
22551 Q : String (X .. Y) := "abc";
22552 @dots{}
22553 for Q'Address use Q_Address;
22554 @end cartouche
22555 @end group
22556 @end smallexample
22557
22558 @noindent
22559 which will be accepted by GNAT (and other Ada compilers), and is also
22560 compatible with Ada 83. A fuller description of the restrictions
22561 on address specifications is found in @ref{Top, GNAT Reference Manual,
22562 About This Guide, gnat_rm, GNAT Reference Manual}.
22563
22564 @node Other Representation Clauses
22565 @subsection Other Representation Clauses
22566
22567 @noindent
22568 GNAT implements in a compatible manner all the representation
22569 clauses supported by HP Ada. In addition, GNAT
22570 implements the representation clause forms that were introduced in Ada 95,
22571 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
22572
22573 @node The Package STANDARD
22574 @section The Package @code{STANDARD}
22575
22576 @noindent
22577 The package @code{STANDARD}, as implemented by HP Ada, is fully
22578 described in the @cite{Ada Reference Manual} and in the
22579 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
22580 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
22581
22582 In addition, HP Ada supports the Latin-1 character set in
22583 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
22584 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
22585 the type @code{WIDE_CHARACTER}.
22586
22587 The floating-point types supported by GNAT are those
22588 supported by HP Ada, but the defaults are different, and are controlled by
22589 pragmas. See @ref{Floating-Point Types and Representations}, for details.
22590
22591 @node The Package SYSTEM
22592 @section The Package @code{SYSTEM}
22593
22594 @noindent
22595 HP Ada provides a specific version of the package
22596 @code{SYSTEM} for each platform on which the language is implemented.
22597 For the complete spec of the package @code{SYSTEM}, see
22598 Appendix F of the @cite{HP Ada Language Reference Manual}.
22599
22600 On HP Ada, the package @code{SYSTEM} includes the following conversion
22601 functions:
22602 @itemize @bullet
22603 @item @code{TO_ADDRESS(INTEGER)}
22604
22605 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
22606
22607 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
22608
22609 @item @code{TO_INTEGER(ADDRESS)}
22610
22611 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
22612
22613 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
22614 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
22615 @end itemize
22616
22617 @noindent
22618 By default, GNAT supplies a version of @code{SYSTEM} that matches
22619 the definition given in the @cite{Ada Reference Manual}.
22620 This
22621 is a subset of the HP system definitions, which is as
22622 close as possible to the original definitions. The only difference
22623 is that the definition of @code{SYSTEM_NAME} is different:
22624
22625 @smallexample @c ada
22626 @cartouche
22627 type Name is (SYSTEM_NAME_GNAT);
22628 System_Name : constant Name := SYSTEM_NAME_GNAT;
22629 @end cartouche
22630 @end smallexample
22631
22632 @noindent
22633 Also, GNAT adds the Ada declarations for
22634 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
22635
22636 However, the use of the following pragma causes GNAT
22637 to extend the definition of package @code{SYSTEM} so that it
22638 encompasses the full set of HP-specific extensions,
22639 including the functions listed above:
22640
22641 @smallexample @c ada
22642 @cartouche
22643 pragma Extend_System (Aux_DEC);
22644 @end cartouche
22645 @end smallexample
22646
22647 @noindent
22648 The pragma @code{Extend_System} is a configuration pragma that
22649 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
22650 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
22651
22652 HP Ada does not allow the recompilation of the package
22653 @code{SYSTEM}. Instead HP Ada provides several pragmas
22654 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
22655 to modify values in the package @code{SYSTEM}.
22656 On OpenVMS Alpha systems, the pragma
22657 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
22658 its single argument.
22659
22660 GNAT does permit the recompilation of package @code{SYSTEM} using
22661 the special switch @option{-gnatg}, and this switch can be used if
22662 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
22663 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
22664 or @code{MEMORY_SIZE} by any other means.
22665
22666 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
22667 enumeration literal @code{SYSTEM_NAME_GNAT}.
22668
22669 The definitions provided by the use of
22670
22671 @smallexample @c ada
22672 pragma Extend_System (AUX_Dec);
22673 @end smallexample
22674
22675 @noindent
22676 are virtually identical to those provided by the HP Ada 83 package
22677 @code{SYSTEM}. One important difference is that the name of the
22678 @code{TO_ADDRESS}
22679 function for type @code{UNSIGNED_LONGWORD} is changed to
22680 @code{TO_ADDRESS_LONG}.
22681 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
22682 discussion of why this change was necessary.
22683
22684 @noindent
22685 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
22686 is in fact
22687 an extension to Ada 83 not strictly compatible with the reference manual.
22688 GNAT, in order to be exactly compatible with the standard,
22689 does not provide this capability. In HP Ada 83, the
22690 point of this definition is to deal with a call like:
22691
22692 @smallexample @c ada
22693 TO_ADDRESS (16#12777#);
22694 @end smallexample
22695
22696 @noindent
22697 Normally, according to Ada 83 semantics, one would expect this to be
22698 ambiguous, since it matches both the @code{INTEGER} and
22699 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
22700 However, in HP Ada 83, there is no ambiguity, since the
22701 definition using @i{universal_integer} takes precedence.
22702
22703 In GNAT, since the version with @i{universal_integer} cannot be supplied,
22704 it is
22705 not possible to be 100% compatible. Since there are many programs using
22706 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
22707 GNAT was
22708 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
22709 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
22710
22711 @smallexample @c ada
22712 function To_Address (X : Integer) return Address;
22713 pragma Pure_Function (To_Address);
22714
22715 function To_Address_Long (X : Unsigned_Longword) return Address;
22716 pragma Pure_Function (To_Address_Long);
22717 @end smallexample
22718
22719 @noindent
22720 This means that programs using @code{TO_ADDRESS} for
22721 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
22722
22723 @node Tasking and Task-Related Features
22724 @section Tasking and Task-Related Features
22725
22726 @noindent
22727 This section compares the treatment of tasking in GNAT
22728 and in HP Ada for OpenVMS Alpha.
22729 The GNAT description applies to both Alpha and I64 OpenVMS.
22730 For detailed information on tasking in
22731 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
22732 relevant run-time reference manual.
22733
22734 @menu
22735 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
22736 * Assigning Task IDs::
22737 * Task IDs and Delays::
22738 * Task-Related Pragmas::
22739 * Scheduling and Task Priority::
22740 * The Task Stack::
22741 * External Interrupts::
22742 @end menu
22743
22744 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22745 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22746
22747 @noindent
22748 On OpenVMS Alpha systems, each Ada task (except a passive
22749 task) is implemented as a single stream of execution
22750 that is created and managed by the kernel. On these
22751 systems, HP Ada tasking support is based on DECthreads,
22752 an implementation of the POSIX standard for threads.
22753
22754 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
22755 code that calls DECthreads routines can be used together.
22756 The interaction between Ada tasks and DECthreads routines
22757 can have some benefits. For example when on OpenVMS Alpha,
22758 HP Ada can call C code that is already threaded.
22759
22760 GNAT uses the facilities of DECthreads,
22761 and Ada tasks are mapped to threads.
22762
22763 @node Assigning Task IDs
22764 @subsection Assigning Task IDs
22765
22766 @noindent
22767 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
22768 the environment task that executes the main program. On
22769 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
22770 that have been created but are not yet activated.
22771
22772 On OpenVMS Alpha systems, task IDs are assigned at
22773 activation. On GNAT systems, task IDs are also assigned at
22774 task creation but do not have the same form or values as
22775 task ID values in HP Ada. There is no null task, and the
22776 environment task does not have a specific task ID value.
22777
22778 @node Task IDs and Delays
22779 @subsection Task IDs and Delays
22780
22781 @noindent
22782 On OpenVMS Alpha systems, tasking delays are implemented
22783 using Timer System Services. The Task ID is used for the
22784 identification of the timer request (the @code{REQIDT} parameter).
22785 If Timers are used in the application take care not to use
22786 @code{0} for the identification, because cancelling such a timer
22787 will cancel all timers and may lead to unpredictable results.
22788
22789 @node Task-Related Pragmas
22790 @subsection Task-Related Pragmas
22791
22792 @noindent
22793 Ada supplies the pragma @code{TASK_STORAGE}, which allows
22794 specification of the size of the guard area for a task
22795 stack. (The guard area forms an area of memory that has no
22796 read or write access and thus helps in the detection of
22797 stack overflow.) On OpenVMS Alpha systems, if the pragma
22798 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
22799 area is created. In the absence of a pragma @code{TASK_STORAGE},
22800 a default guard area is created.
22801
22802 GNAT supplies the following task-related pragmas:
22803
22804 @itemize @bullet
22805 @item @code{TASK_INFO}
22806
22807 This pragma appears within a task definition and
22808 applies to the task in which it appears. The argument
22809 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
22810
22811 @item @code{TASK_STORAGE}
22812
22813 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
22814 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
22815 @code{SUPPRESS}, and @code{VOLATILE}.
22816 @end itemize
22817 @node Scheduling and Task Priority
22818 @subsection Scheduling and Task Priority
22819
22820 @noindent
22821 HP Ada implements the Ada language requirement that
22822 when two tasks are eligible for execution and they have
22823 different priorities, the lower priority task does not
22824 execute while the higher priority task is waiting. The HP
22825 Ada Run-Time Library keeps a task running until either the
22826 task is suspended or a higher priority task becomes ready.
22827
22828 On OpenVMS Alpha systems, the default strategy is round-
22829 robin with preemption. Tasks of equal priority take turns
22830 at the processor. A task is run for a certain period of
22831 time and then placed at the tail of the ready queue for
22832 its priority level.
22833
22834 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
22835 which can be used to enable or disable round-robin
22836 scheduling of tasks with the same priority.
22837 See the relevant HP Ada run-time reference manual for
22838 information on using the pragmas to control HP Ada task
22839 scheduling.
22840
22841 GNAT follows the scheduling rules of Annex D (Real-Time
22842 Annex) of the @cite{Ada Reference Manual}. In general, this
22843 scheduling strategy is fully compatible with HP Ada
22844 although it provides some additional constraints (as
22845 fully documented in Annex D).
22846 GNAT implements time slicing control in a manner compatible with
22847 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
22848 are identical to the HP Ada 83 pragma of the same name.
22849 Note that it is not possible to mix GNAT tasking and
22850 HP Ada 83 tasking in the same program, since the two run-time
22851 libraries are not compatible.
22852
22853 @node The Task Stack
22854 @subsection The Task Stack
22855
22856 @noindent
22857 In HP Ada, a task stack is allocated each time a
22858 non-passive task is activated. As soon as the task is
22859 terminated, the storage for the task stack is deallocated.
22860 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
22861 a default stack size is used. Also, regardless of the size
22862 specified, some additional space is allocated for task
22863 management purposes. On OpenVMS Alpha systems, at least
22864 one page is allocated.
22865
22866 GNAT handles task stacks in a similar manner. In accordance with
22867 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
22868 an alternative method for controlling the task stack size.
22869 The specification of the attribute @code{T'STORAGE_SIZE} is also
22870 supported in a manner compatible with HP Ada.
22871
22872 @node External Interrupts
22873 @subsection External Interrupts
22874
22875 @noindent
22876 On HP Ada, external interrupts can be associated with task entries.
22877 GNAT is compatible with HP Ada in its handling of external interrupts.
22878
22879 @node Pragmas and Pragma-Related Features
22880 @section Pragmas and Pragma-Related Features
22881
22882 @noindent
22883 Both HP Ada and GNAT supply all language-defined pragmas
22884 as specified by the Ada 83 standard. GNAT also supplies all
22885 language-defined pragmas introduced by Ada 95 and Ada 2005.
22886 In addition, GNAT implements the implementation-defined pragmas
22887 from HP Ada 83.
22888
22889 @itemize @bullet
22890 @item @code{AST_ENTRY}
22891
22892 @item @code{COMMON_OBJECT}
22893
22894 @item @code{COMPONENT_ALIGNMENT}
22895
22896 @item @code{EXPORT_EXCEPTION}
22897
22898 @item @code{EXPORT_FUNCTION}
22899
22900 @item @code{EXPORT_OBJECT}
22901
22902 @item @code{EXPORT_PROCEDURE}
22903
22904 @item @code{EXPORT_VALUED_PROCEDURE}
22905
22906 @item @code{FLOAT_REPRESENTATION}
22907
22908 @item @code{IDENT}
22909
22910 @item @code{IMPORT_EXCEPTION}
22911
22912 @item @code{IMPORT_FUNCTION}
22913
22914 @item @code{IMPORT_OBJECT}
22915
22916 @item @code{IMPORT_PROCEDURE}
22917
22918 @item @code{IMPORT_VALUED_PROCEDURE}
22919
22920 @item @code{INLINE_GENERIC}
22921
22922 @item @code{INTERFACE_NAME}
22923
22924 @item @code{LONG_FLOAT}
22925
22926 @item @code{MAIN_STORAGE}
22927
22928 @item @code{PASSIVE}
22929
22930 @item @code{PSECT_OBJECT}
22931
22932 @item @code{SHARE_GENERIC}
22933
22934 @item @code{SUPPRESS_ALL}
22935
22936 @item @code{TASK_STORAGE}
22937
22938 @item @code{TIME_SLICE}
22939
22940 @item @code{TITLE}
22941 @end itemize
22942
22943 @noindent
22944 These pragmas are all fully implemented, with the exception of @code{TITLE},
22945 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
22946 recognized, but which have no
22947 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
22948 use of Ada protected objects. In GNAT, all generics are inlined.
22949
22950 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
22951 a separate subprogram specification which must appear before the
22952 subprogram body.
22953
22954 GNAT also supplies a number of implementation-defined pragmas including the
22955 following:
22956
22957 @itemize @bullet
22958 @item @code{ABORT_DEFER}
22959
22960 @item @code{ADA_83}
22961
22962 @item @code{ADA_95}
22963
22964 @item @code{ADA_05}
22965
22966 @item @code{Ada_2005}
22967
22968 @item @code{Ada_12}
22969
22970 @item @code{Ada_2012}
22971
22972 @item @code{ALLOW_INTEGER_ADDRESS}
22973
22974 @item @code{ANNOTATE}
22975
22976 @item @code{ASSERT}
22977
22978 @item @code{C_PASS_BY_COPY}
22979
22980 @item @code{CPP_CLASS}
22981
22982 @item @code{CPP_CONSTRUCTOR}
22983
22984 @item @code{CPP_DESTRUCTOR}
22985
22986 @item @code{DEBUG}
22987
22988 @item @code{EXTEND_SYSTEM}
22989
22990 @item @code{LINKER_ALIAS}
22991
22992 @item @code{LINKER_SECTION}
22993
22994 @item @code{MACHINE_ATTRIBUTE}
22995
22996 @item @code{NO_RETURN}
22997
22998 @item @code{PURE_FUNCTION}
22999
23000 @item @code{SOURCE_FILE_NAME}
23001
23002 @item @code{SOURCE_REFERENCE}
23003
23004 @item @code{TASK_INFO}
23005
23006 @item @code{UNCHECKED_UNION}
23007
23008 @item @code{UNIMPLEMENTED_UNIT}
23009
23010 @item @code{UNIVERSAL_DATA}
23011
23012 @item @code{UNSUPPRESS}
23013
23014 @item @code{WARNINGS}
23015
23016 @item @code{WEAK_EXTERNAL}
23017 @end itemize
23018
23019 @noindent
23020 For full details on these and other GNAT implementation-defined pragmas,
23021 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
23022 Manual}.
23023
23024 @menu
23025 * Restrictions on the Pragma INLINE::
23026 * Restrictions on the Pragma INTERFACE::
23027 * Restrictions on the Pragma SYSTEM_NAME::
23028 @end menu
23029
23030 @node Restrictions on the Pragma INLINE
23031 @subsection Restrictions on Pragma @code{INLINE}
23032
23033 @noindent
23034 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
23035 @itemize @bullet
23036 @item Parameters cannot have a task type.
23037
23038 @item Function results cannot be task types, unconstrained
23039 array types, or unconstrained types with discriminants.
23040
23041 @item Bodies cannot declare the following:
23042 @itemize @bullet
23043 @item Subprogram body or stub (imported subprogram is allowed)
23044
23045 @item Tasks
23046
23047 @item Generic declarations
23048
23049 @item Instantiations
23050
23051 @item Exceptions
23052
23053 @item Access types (types derived from access types allowed)
23054
23055 @item Array or record types
23056
23057 @item Dependent tasks
23058
23059 @item Direct recursive calls of subprogram or containing
23060 subprogram, directly or via a renaming
23061
23062 @end itemize
23063 @end itemize
23064
23065 @noindent
23066 In GNAT, the only restriction on pragma @code{INLINE} is that the
23067 body must occur before the call if both are in the same
23068 unit, and the size must be appropriately small. There are
23069 no other specific restrictions which cause subprograms to
23070 be incapable of being inlined.
23071
23072 @node Restrictions on the Pragma INTERFACE
23073 @subsection Restrictions on Pragma @code{INTERFACE}
23074
23075 @noindent
23076 The following restrictions on pragma @code{INTERFACE}
23077 are enforced by both HP Ada and GNAT:
23078 @itemize @bullet
23079 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
23080 Default is the default on OpenVMS Alpha systems.
23081
23082 @item Parameter passing: Language specifies default
23083 mechanisms but can be overridden with an @code{EXPORT} pragma.
23084
23085 @itemize @bullet
23086 @item Ada: Use internal Ada rules.
23087
23088 @item Bliss, C: Parameters must be mode @code{in}; cannot be
23089 record or task type. Result cannot be a string, an
23090 array, or a record.
23091
23092 @item Fortran: Parameters cannot have a task type. Result cannot
23093 be a string, an array, or a record.
23094 @end itemize
23095 @end itemize
23096
23097 @noindent
23098 GNAT is entirely upwards compatible with HP Ada, and in addition allows
23099 record parameters for all languages.
23100
23101 @node Restrictions on the Pragma SYSTEM_NAME
23102 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
23103
23104 @noindent
23105 For HP Ada for OpenVMS Alpha, the enumeration literal
23106 for the type @code{NAME} is @code{OPENVMS_AXP}.
23107 In GNAT, the enumeration
23108 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
23109
23110 @node Library of Predefined Units
23111 @section Library of Predefined Units
23112
23113 @noindent
23114 A library of predefined units is provided as part of the
23115 HP Ada and GNAT implementations. HP Ada does not provide
23116 the package @code{MACHINE_CODE} but instead recommends importing
23117 assembler code.
23118
23119 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
23120 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
23121 version.
23122 The HP Ada Predefined Library units are modified to remove post-Ada 83
23123 incompatibilities and to make them interoperable with GNAT
23124 (@pxref{Changes to DECLIB}, for details).
23125 The units are located in the @file{DECLIB} directory.
23126
23127 The GNAT RTL is contained in
23128 the @file{ADALIB} directory, and
23129 the default search path is set up to find @code{DECLIB} units in preference
23130 to @code{ADALIB} units with the same name (@code{TEXT_IO},
23131 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
23132
23133 @menu
23134 * Changes to DECLIB::
23135 @end menu
23136
23137 @node Changes to DECLIB
23138 @subsection Changes to @code{DECLIB}
23139
23140 @noindent
23141 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
23142 compatibility are minor and include the following:
23143
23144 @itemize @bullet
23145 @item Adjusting the location of pragmas and record representation
23146 clauses to obey Ada 95 (and thus Ada 2005) rules
23147
23148 @item Adding the proper notation to generic formal parameters
23149 that take unconstrained types in instantiation
23150
23151 @item Adding pragma @code{ELABORATE_BODY} to package specs
23152 that have package bodies not otherwise allowed
23153
23154 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
23155 ``@code{PROTECTD}''.
23156 Currently these are found only in the @code{STARLET} package spec.
23157
23158 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
23159 where the address size is constrained to 32 bits.
23160 @end itemize
23161
23162 @noindent
23163 None of the above changes is visible to users.
23164
23165 @node Bindings
23166 @section Bindings
23167
23168 @noindent
23169 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
23170 @itemize @bullet
23171
23172 @item Command Language Interpreter (CLI interface)
23173
23174 @item DECtalk Run-Time Library (DTK interface)
23175
23176 @item Librarian utility routines (LBR interface)
23177
23178 @item General Purpose Run-Time Library (LIB interface)
23179
23180 @item Math Run-Time Library (MTH interface)
23181
23182 @item National Character Set Run-Time Library (NCS interface)
23183
23184 @item Compiled Code Support Run-Time Library (OTS interface)
23185
23186 @item Parallel Processing Run-Time Library (PPL interface)
23187
23188 @item Screen Management Run-Time Library (SMG interface)
23189
23190 @item Sort Run-Time Library (SOR interface)
23191
23192 @item String Run-Time Library (STR interface)
23193
23194 @item STARLET System Library
23195 @findex Starlet
23196
23197 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
23198
23199 @item X Windows Toolkit (XT interface)
23200
23201 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
23202 @end itemize
23203
23204 @noindent
23205 GNAT provides implementations of these HP bindings in the @code{DECLIB}
23206 directory, on both the Alpha and I64 OpenVMS platforms.
23207
23208 The X components of DECLIB compatibility package are located in a separate
23209 library, called XDECGNAT, which is not linked with by default; this library
23210 must be explicitly linked with any application that makes use of any X facilities,
23211 with a command similar to
23212
23213 @code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
23214
23215 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
23216 in the
23217 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
23218 A pragma @code{Linker_Options} has been added to packages @code{Xm},
23219 @code{Xt}, and @code{X_Lib}
23220 causing the default X/Motif sharable image libraries to be linked in. This
23221 is done via options files named @file{xm.opt}, @file{xt.opt}, and
23222 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
23223
23224 It may be necessary to edit these options files to update or correct the
23225 library names if, for example, the newer X/Motif bindings from
23226 @file{ADA$EXAMPLES}
23227 had been (previous to installing GNAT) copied and renamed to supersede the
23228 default @file{ADA$PREDEFINED} versions.
23229
23230 @menu
23231 * Shared Libraries and Options Files::
23232 * Interfaces to C::
23233 @end menu
23234
23235 @node Shared Libraries and Options Files
23236 @subsection Shared Libraries and Options Files
23237
23238 @noindent
23239 When using the HP Ada
23240 predefined X and Motif bindings, the linking with their sharable images is
23241 done automatically by @command{GNAT LINK}.
23242 When using other X and Motif bindings, you need
23243 to add the corresponding sharable images to the command line for
23244 @code{GNAT LINK}. When linking with shared libraries, or with
23245 @file{.OPT} files, you must
23246 also add them to the command line for @command{GNAT LINK}.
23247
23248 A shared library to be used with GNAT is built in the same way as other
23249 libraries under VMS. The VMS Link command can be used in standard fashion.
23250
23251 @node Interfaces to C
23252 @subsection Interfaces to C
23253
23254 @noindent
23255 HP Ada
23256 provides the following Ada types and operations:
23257
23258 @itemize @bullet
23259 @item C types package (@code{C_TYPES})
23260
23261 @item C strings (@code{C_TYPES.NULL_TERMINATED})
23262
23263 @item Other_types (@code{SHORT_INT})
23264 @end itemize
23265
23266 @noindent
23267 Interfacing to C with GNAT, you can use the above approach
23268 described for HP Ada or the facilities of Annex B of
23269 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
23270 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
23271 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
23272
23273 The @option{-gnatF} qualifier forces default and explicit
23274 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
23275 to be uppercased for compatibility with the default behavior
23276 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
23277
23278 @node Main Program Definition
23279 @section Main Program Definition
23280
23281 @noindent
23282 The following section discusses differences in the
23283 definition of main programs on HP Ada and GNAT.
23284 On HP Ada, main programs are defined to meet the
23285 following conditions:
23286 @itemize @bullet
23287 @item Procedure with no formal parameters (returns @code{0} upon
23288 normal completion)
23289
23290 @item Procedure with no formal parameters (returns @code{42} when
23291 an unhandled exception is raised)
23292
23293 @item Function with no formal parameters whose returned value
23294 is of a discrete type
23295
23296 @item Procedure with one @code{out} formal of a discrete type for
23297 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
23298
23299 @end itemize
23300
23301 @noindent
23302 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
23303 a main function or main procedure returns a discrete
23304 value whose size is less than 64 bits (32 on VAX systems),
23305 the value is zero- or sign-extended as appropriate.
23306 On GNAT, main programs are defined as follows:
23307 @itemize @bullet
23308 @item Must be a non-generic, parameterless subprogram that
23309 is either a procedure or function returning an Ada
23310 @code{STANDARD.INTEGER} (the predefined type)
23311
23312 @item Cannot be a generic subprogram or an instantiation of a
23313 generic subprogram
23314 @end itemize
23315
23316 @node Implementation-Defined Attributes
23317 @section Implementation-Defined Attributes
23318
23319 @noindent
23320 GNAT provides all HP Ada implementation-defined
23321 attributes.
23322
23323 @node Compiler and Run-Time Interfacing
23324 @section Compiler and Run-Time Interfacing
23325
23326 @noindent
23327 HP Ada provides the following qualifiers to pass options to the linker
23328 (ACS LINK):
23329 @itemize @bullet
23330 @item @option{/WAIT} and @option{/SUBMIT}
23331
23332 @item @option{/COMMAND}
23333
23334 @item @option{/@r{[}NO@r{]}MAP}
23335
23336 @item @option{/OUTPUT=@var{file-spec}}
23337
23338 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
23339 @end itemize
23340
23341 @noindent
23342 To pass options to the linker, GNAT provides the following
23343 switches:
23344
23345 @itemize @bullet
23346 @item @option{/EXECUTABLE=@var{exec-name}}
23347
23348 @item @option{/VERBOSE}
23349
23350 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
23351 @end itemize
23352
23353 @noindent
23354 For more information on these switches, see
23355 @ref{Switches for gnatlink}.
23356 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
23357 to control optimization. HP Ada also supplies the
23358 following pragmas:
23359 @itemize @bullet
23360 @item @code{OPTIMIZE}
23361
23362 @item @code{INLINE}
23363
23364 @item @code{INLINE_GENERIC}
23365
23366 @item @code{SUPPRESS_ALL}
23367
23368 @item @code{PASSIVE}
23369 @end itemize
23370
23371 @noindent
23372 In GNAT, optimization is controlled strictly by command
23373 line parameters, as described in the corresponding section of this guide.
23374 The HP pragmas for control of optimization are
23375 recognized but ignored.
23376
23377 Note that in GNAT, the default is optimization off, whereas in HP Ada
23378 the default is that optimization is turned on.
23379
23380 @node Program Compilation and Library Management
23381 @section Program Compilation and Library Management
23382
23383 @noindent
23384 HP Ada and GNAT provide a comparable set of commands to
23385 build programs. HP Ada also provides a program library,
23386 which is a concept that does not exist on GNAT. Instead,
23387 GNAT provides directories of sources that are compiled as
23388 needed.
23389
23390 The following table summarizes
23391 the HP Ada commands and provides
23392 equivalent GNAT commands. In this table, some GNAT
23393 equivalents reflect the fact that GNAT does not use the
23394 concept of a program library. Instead, it uses a model
23395 in which collections of source and object files are used
23396 in a manner consistent with other languages like C and
23397 Fortran. Therefore, standard system file commands are used
23398 to manipulate these elements. Those GNAT commands are marked with
23399 an asterisk.
23400 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
23401
23402 @need 1500
23403 @multitable @columnfractions .35 .65
23404
23405 @item @emph{HP Ada Command}
23406 @tab @emph{GNAT Equivalent / Description}
23407
23408 @item @command{ADA}
23409 @tab @command{GNAT COMPILE}@*
23410 Invokes the compiler to compile one or more Ada source files.
23411
23412 @item @command{ACS ATTACH}@*
23413 @tab [No equivalent]@*
23414 Switches control of terminal from current process running the program
23415 library manager.
23416
23417 @item @command{ACS CHECK}
23418 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
23419 Forms the execution closure of one
23420 or more compiled units and checks completeness and currency.
23421
23422 @item @command{ACS COMPILE}
23423 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23424 Forms the execution closure of one or
23425 more specified units, checks completeness and currency,
23426 identifies units that have revised source files, compiles same,
23427 and recompiles units that are or will become obsolete.
23428 Also completes incomplete generic instantiations.
23429
23430 @item @command{ACS COPY FOREIGN}
23431 @tab Copy (*)@*
23432 Copies a foreign object file into the program library as a
23433 library unit body.
23434
23435 @item @command{ACS COPY UNIT}
23436 @tab Copy (*)@*
23437 Copies a compiled unit from one program library to another.
23438
23439 @item @command{ACS CREATE LIBRARY}
23440 @tab Create /directory (*)@*
23441 Creates a program library.
23442
23443 @item @command{ACS CREATE SUBLIBRARY}
23444 @tab Create /directory (*)@*
23445 Creates a program sublibrary.
23446
23447 @item @command{ACS DELETE LIBRARY}
23448 @tab @*
23449 Deletes a program library and its contents.
23450
23451 @item @command{ACS DELETE SUBLIBRARY}
23452 @tab @*
23453 Deletes a program sublibrary and its contents.
23454
23455 @item @command{ACS DELETE UNIT}
23456 @tab Delete file (*)@*
23457 On OpenVMS systems, deletes one or more compiled units from
23458 the current program library.
23459
23460 @item @command{ACS DIRECTORY}
23461 @tab Directory (*)@*
23462 On OpenVMS systems, lists units contained in the current
23463 program library.
23464
23465 @item @command{ACS ENTER FOREIGN}
23466 @tab Copy (*)@*
23467 Allows the import of a foreign body as an Ada library
23468 spec and enters a reference to a pointer.
23469
23470 @item @command{ACS ENTER UNIT}
23471 @tab Copy (*)@*
23472 Enters a reference (pointer) from the current program library to
23473 a unit compiled into another program library.
23474
23475 @item @command{ACS EXIT}
23476 @tab [No equivalent]@*
23477 Exits from the program library manager.
23478
23479 @item @command{ACS EXPORT}
23480 @tab Copy (*)@*
23481 Creates an object file that contains system-specific object code
23482 for one or more units. With GNAT, object files can simply be copied
23483 into the desired directory.
23484
23485 @item @command{ACS EXTRACT SOURCE}
23486 @tab Copy (*)@*
23487 Allows access to the copied source file for each Ada compilation unit
23488
23489 @item @command{ACS HELP}
23490 @tab @command{HELP GNAT}@*
23491 Provides online help.
23492
23493 @item @command{ACS LINK}
23494 @tab @command{GNAT LINK}@*
23495 Links an object file containing Ada units into an executable file.
23496
23497 @item @command{ACS LOAD}
23498 @tab Copy (*)@*
23499 Loads (partially compiles) Ada units into the program library.
23500 Allows loading a program from a collection of files into a library
23501 without knowing the relationship among units.
23502
23503 @item @command{ACS MERGE}
23504 @tab Copy (*)@*
23505 Merges into the current program library, one or more units from
23506 another library where they were modified.
23507
23508 @item @command{ACS RECOMPILE}
23509 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23510 Recompiles from external or copied source files any obsolete
23511 unit in the closure. Also, completes any incomplete generic
23512 instantiations.
23513
23514 @item @command{ACS REENTER}
23515 @tab @command{GNAT MAKE}@*
23516 Reenters current references to units compiled after last entered
23517 with the @command{ACS ENTER UNIT} command.
23518
23519 @item @command{ACS SET LIBRARY}
23520 @tab Set default (*)@*
23521 Defines a program library to be the compilation context as well
23522 as the target library for compiler output and commands in general.
23523
23524 @item @command{ACS SET PRAGMA}
23525 @tab Edit @file{gnat.adc} (*)@*
23526 Redefines specified values of the library characteristics
23527 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
23528 and @code{Float_Representation}.
23529
23530 @item @command{ACS SET SOURCE}
23531 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
23532 Defines the source file search list for the @command{ACS COMPILE} command.
23533
23534 @item @command{ACS SHOW LIBRARY}
23535 @tab Directory (*)@*
23536 Lists information about one or more program libraries.
23537
23538 @item @command{ACS SHOW PROGRAM}
23539 @tab [No equivalent]@*
23540 Lists information about the execution closure of one or
23541 more units in the program library.
23542
23543 @item @command{ACS SHOW SOURCE}
23544 @tab Show logical @code{ADA_INCLUDE_PATH}@*
23545 Shows the source file search used when compiling units.
23546
23547 @item @command{ACS SHOW VERSION}
23548 @tab Compile with @option{VERBOSE} option
23549 Displays the version number of the compiler and program library
23550 manager used.
23551
23552 @item @command{ACS SPAWN}
23553 @tab [No equivalent]@*
23554 Creates a subprocess of the current process (same as @command{DCL SPAWN}
23555 command).
23556
23557 @item @command{ACS VERIFY}
23558 @tab [No equivalent]@*
23559 Performs a series of consistency checks on a program library to
23560 determine whether the library structure and library files are in
23561 valid form.
23562 @end multitable
23563
23564 @noindent
23565
23566 @node Input-Output
23567 @section Input-Output
23568
23569 @noindent
23570 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
23571 Management Services (RMS) to perform operations on
23572 external files.
23573
23574 @noindent
23575 HP Ada and GNAT predefine an identical set of input-
23576 output packages. To make the use of the
23577 generic @code{TEXT_IO} operations more convenient, HP Ada
23578 provides predefined library packages that instantiate the
23579 integer and floating-point operations for the predefined
23580 integer and floating-point types as shown in the following table.
23581
23582 @multitable @columnfractions .45 .55
23583 @item @emph{Package Name} @tab Instantiation
23584
23585 @item @code{INTEGER_TEXT_IO}
23586 @tab @code{INTEGER_IO(INTEGER)}
23587
23588 @item @code{SHORT_INTEGER_TEXT_IO}
23589 @tab @code{INTEGER_IO(SHORT_INTEGER)}
23590
23591 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
23592 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
23593
23594 @item @code{FLOAT_TEXT_IO}
23595 @tab @code{FLOAT_IO(FLOAT)}
23596
23597 @item @code{LONG_FLOAT_TEXT_IO}
23598 @tab @code{FLOAT_IO(LONG_FLOAT)}
23599 @end multitable
23600
23601 @noindent
23602 The HP Ada predefined packages and their operations
23603 are implemented using OpenVMS Alpha files and input-output
23604 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
23605 Familiarity with the following is recommended:
23606 @itemize @bullet
23607 @item RMS file organizations and access methods
23608
23609 @item OpenVMS file specifications and directories
23610
23611 @item OpenVMS File Definition Language (FDL)
23612 @end itemize
23613
23614 @noindent
23615 GNAT provides I/O facilities that are completely
23616 compatible with HP Ada. The distribution includes the
23617 standard HP Ada versions of all I/O packages, operating
23618 in a manner compatible with HP Ada. In particular, the
23619 following packages are by default the HP Ada (Ada 83)
23620 versions of these packages rather than the renamings
23621 suggested in Annex J of the Ada Reference Manual:
23622 @itemize @bullet
23623 @item @code{TEXT_IO}
23624
23625 @item @code{SEQUENTIAL_IO}
23626
23627 @item @code{DIRECT_IO}
23628 @end itemize
23629
23630 @noindent
23631 The use of the standard child package syntax (for
23632 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
23633 packages.
23634 GNAT provides HP-compatible predefined instantiations
23635 of the @code{TEXT_IO} packages, and also
23636 provides the standard predefined instantiations required
23637 by the @cite{Ada Reference Manual}.
23638
23639 For further information on how GNAT interfaces to the file
23640 system or how I/O is implemented in programs written in
23641 mixed languages, see @ref{Implementation of the Standard I/O,,,
23642 gnat_rm, GNAT Reference Manual}.
23643 This chapter covers the following:
23644 @itemize @bullet
23645 @item Standard I/O packages
23646
23647 @item @code{FORM} strings
23648
23649 @item @code{ADA.DIRECT_IO}
23650
23651 @item @code{ADA.SEQUENTIAL_IO}
23652
23653 @item @code{ADA.TEXT_IO}
23654
23655 @item Stream pointer positioning
23656
23657 @item Reading and writing non-regular files
23658
23659 @item @code{GET_IMMEDIATE}
23660
23661 @item Treating @code{TEXT_IO} files as streams
23662
23663 @item Shared files
23664
23665 @item Open modes
23666 @end itemize
23667
23668 @node Implementation Limits
23669 @section Implementation Limits
23670
23671 @noindent
23672 The following table lists implementation limits for HP Ada
23673 and GNAT systems.
23674 @multitable @columnfractions .60 .20 .20
23675 @sp 1
23676 @item @emph{Compilation Parameter}
23677 @tab @emph{HP Ada}
23678 @tab @emph{GNAT}
23679 @sp 1
23680
23681 @item In a subprogram or entry declaration, maximum number of
23682 formal parameters that are of an unconstrained record type
23683 @tab 32
23684 @tab No set limit
23685 @sp 1
23686
23687 @item Maximum identifier length (number of characters)
23688 @tab 255
23689 @tab 32766
23690 @sp 1
23691
23692 @item Maximum number of characters in a source line
23693 @tab 255
23694 @tab 32766
23695 @sp 1
23696
23697 @item Maximum collection size (number of bytes)
23698 @tab 2**31-1
23699 @tab 2**31-1
23700 @sp 1
23701
23702 @item Maximum number of discriminants for a record type
23703 @tab 245
23704 @tab No set limit
23705 @sp 1
23706
23707 @item Maximum number of formal parameters in an entry or
23708 subprogram declaration
23709 @tab 246
23710 @tab No set limit
23711 @sp 1
23712
23713 @item Maximum number of dimensions in an array type
23714 @tab 255
23715 @tab No set limit
23716 @sp 1
23717
23718 @item Maximum number of library units and subunits in a compilation.
23719 @tab 4095
23720 @tab No set limit
23721 @sp 1
23722
23723 @item Maximum number of library units and subunits in an execution.
23724 @tab 16383
23725 @tab No set limit
23726 @sp 1
23727
23728 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
23729 or @code{PSECT_OBJECT}
23730 @tab 32757
23731 @tab No set limit
23732 @sp 1
23733
23734 @item Maximum number of enumeration literals in an enumeration type
23735 definition
23736 @tab 65535
23737 @tab No set limit
23738 @sp 1
23739
23740 @item Maximum number of lines in a source file
23741 @tab 65534
23742 @tab No set limit
23743 @sp 1
23744
23745 @item Maximum number of bits in any object
23746 @tab 2**31-1
23747 @tab 2**31-1
23748 @sp 1
23749
23750 @item Maximum size of the static portion of a stack frame (approximate)
23751 @tab 2**31-1
23752 @tab 2**31-1
23753 @end multitable
23754
23755 @node Tools and Utilities
23756 @section Tools and Utilities
23757
23758 @noindent
23759 The following table lists some of the OpenVMS development tools
23760 available for HP Ada, and the corresponding tools for
23761 use with @value{EDITION} on Alpha and I64 platforms.
23762 Aside from the debugger, all the OpenVMS tools identified are part
23763 of the DECset package.
23764
23765 @iftex
23766 @c Specify table in TeX since Texinfo does a poor job
23767 @tex
23768 \smallskip
23769 \smallskip
23770 \settabs\+Language-Sensitive Editor\quad
23771 &Product with HP Ada\quad
23772 &\cr
23773 \+\it Tool
23774 &\it Product with HP Ada
23775 & \it Product with @value{EDITION}\cr
23776 \smallskip
23777 \+Code Management System
23778 &HP CMS
23779 & HP CMS\cr
23780 \smallskip
23781 \+Language-Sensitive Editor
23782 &HP LSE
23783 & emacs or HP LSE (Alpha)\cr
23784 \+
23785 &
23786 & HP LSE (I64)\cr
23787 \smallskip
23788 \+Debugger
23789 &OpenVMS Debug
23790 & gdb (Alpha),\cr
23791 \+
23792 &
23793 & OpenVMS Debug (I64)\cr
23794 \smallskip
23795 \+Source Code Analyzer /
23796 &HP SCA
23797 & GNAT XREF\cr
23798 \+Cross Referencer
23799 &
23800 &\cr
23801 \smallskip
23802 \+Test Manager
23803 &HP Digital Test
23804 & HP DTM\cr
23805 \+
23806 &Manager (DTM)
23807 &\cr
23808 \smallskip
23809 \+Performance and
23810 & HP PCA
23811 & HP PCA\cr
23812 \+Coverage Analyzer
23813 &
23814 &\cr
23815 \smallskip
23816 \+Module Management
23817 & HP MMS
23818 & Not applicable\cr
23819 \+ System
23820 &
23821 &\cr
23822 \smallskip
23823 \smallskip
23824 @end tex
23825 @end iftex
23826
23827 @ifnottex
23828 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
23829 @c the TeX version above for the printed version
23830 @flushleft
23831 @c @multitable @columnfractions .3 .4 .4
23832 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
23833 @item @i{Tool}
23834 @tab @i{Tool with HP Ada}
23835 @tab @i{Tool with @value{EDITION}}
23836 @item Code Management@*System
23837 @tab HP CMS
23838 @tab HP CMS
23839 @item Language-Sensitive@*Editor
23840 @tab HP LSE
23841 @tab emacs or HP LSE (Alpha)
23842 @item
23843 @tab
23844 @tab HP LSE (I64)
23845 @item Debugger
23846 @tab OpenVMS Debug
23847 @tab gdb (Alpha),
23848 @item
23849 @tab
23850 @tab OpenVMS Debug (I64)
23851 @item Source Code Analyzer /@*Cross Referencer
23852 @tab HP SCA
23853 @tab GNAT XREF
23854 @item Test Manager
23855 @tab HP Digital Test@*Manager (DTM)
23856 @tab HP DTM
23857 @item Performance and@*Coverage Analyzer
23858 @tab HP PCA
23859 @tab HP PCA
23860 @item Module Management@*System
23861 @tab HP MMS
23862 @tab Not applicable
23863 @end multitable
23864 @end flushleft
23865 @end ifnottex
23866
23867 @end ifset
23868
23869 @c **************************************
23870 @node Platform-Specific Information for the Run-Time Libraries
23871 @appendix Platform-Specific Information for the Run-Time Libraries
23872 @cindex Tasking and threads libraries
23873 @cindex Threads libraries and tasking
23874 @cindex Run-time libraries (platform-specific information)
23875
23876 @noindent
23877 The GNAT run-time implementation may vary with respect to both the
23878 underlying threads library and the exception handling scheme.
23879 For threads support, one or more of the following are supplied:
23880 @itemize @bullet
23881 @item @b{native threads library}, a binding to the thread package from
23882 the underlying operating system
23883
23884 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
23885 POSIX thread package
23886 @end itemize
23887
23888 @noindent
23889 For exception handling, either or both of two models are supplied:
23890 @itemize @bullet
23891 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
23892 Most programs should experience a substantial speed improvement by
23893 being compiled with a ZCX run-time.
23894 This is especially true for
23895 tasking applications or applications with many exception handlers.}
23896 @cindex Zero-Cost Exceptions
23897 @cindex ZCX (Zero-Cost Exceptions)
23898 which uses binder-generated tables that
23899 are interrogated at run time to locate a handler
23900
23901 @item @b{setjmp / longjmp} (``SJLJ''),
23902 @cindex setjmp/longjmp Exception Model
23903 @cindex SJLJ (setjmp/longjmp Exception Model)
23904 which uses dynamically-set data to establish
23905 the set of handlers
23906 @end itemize
23907
23908 @noindent
23909 This appendix summarizes which combinations of threads and exception support
23910 are supplied on various GNAT platforms.
23911 It then shows how to select a particular library either
23912 permanently or temporarily,
23913 explains the properties of (and tradeoffs among) the various threads
23914 libraries, and provides some additional
23915 information about several specific platforms.
23916
23917 @menu
23918 * Summary of Run-Time Configurations::
23919 * Specifying a Run-Time Library::
23920 * Choosing the Scheduling Policy::
23921 * Solaris-Specific Considerations::
23922 * Linux-Specific Considerations::
23923 * AIX-Specific Considerations::
23924 * RTX-Specific Considerations::
23925 * HP-UX-Specific Considerations::
23926 @end menu
23927
23928 @node Summary of Run-Time Configurations
23929 @section Summary of Run-Time Configurations
23930
23931 @multitable @columnfractions .30 .70
23932 @item @b{alpha-openvms}
23933 @item @code{@ @ }@i{rts-native (default)}
23934 @item @code{@ @ @ @ }Tasking @tab native VMS threads
23935 @item @code{@ @ @ @ }Exceptions @tab ZCX
23936 @*
23937 @item @code{@ @ }@i{rts-sjlj}
23938 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
23939 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23940 @*
23941 @item @b{ia64-hp_linux}
23942 @item @code{@ @ }@i{rts-native (default)}
23943 @item @code{@ @ @ @ }Tasking @tab pthread library
23944 @item @code{@ @ @ @ }Exceptions @tab ZCX
23945 @*
23946 @item @b{ia64-hpux}
23947 @item @code{@ @ }@i{rts-native (default)}
23948 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
23949 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23950 @*
23951 @item @b{ia64-openvms}
23952 @item @code{@ @ }@i{rts-native (default)}
23953 @item @code{@ @ @ @ }Tasking @tab native VMS threads
23954 @item @code{@ @ @ @ }Exceptions @tab ZCX
23955 @*
23956 @item @b{ia64-sgi_linux}
23957 @item @code{@ @ }@i{rts-native (default)}
23958 @item @code{@ @ @ @ }Tasking @tab pthread library
23959 @item @code{@ @ @ @ }Exceptions @tab ZCX
23960 @*
23961 @item @b{pa-hpux}
23962 @item @code{@ @ }@i{rts-native (default)}
23963 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
23964 @item @code{@ @ @ @ }Exceptions @tab ZCX
23965 @*
23966 @item @code{@ @ }@i{rts-sjlj}
23967 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
23968 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23969 @*
23970 @item @b{ppc-aix}
23971 @item @code{@ @ }@i{rts-native (default)}
23972 @item @code{@ @ @ @ }Tasking @tab native AIX threads
23973 @item @code{@ @ @ @ }Exceptions @tab ZCX
23974 @*
23975 @item @code{@ @ }@i{rts-sjlj}
23976 @item @code{@ @ @ @ }Tasking @tab native AIX threads
23977 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23978 @*
23979 @item @b{ppc-darwin}
23980 @item @code{@ @ }@i{rts-native (default)}
23981 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
23982 @item @code{@ @ @ @ }Exceptions @tab ZCX
23983 @*
23984 @item @b{sparc-solaris} @tab
23985 @item @code{@ @ }@i{rts-native (default)}
23986 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
23987 @item @code{@ @ @ @ }Exceptions @tab ZCX
23988 @*
23989 @item @code{@ @ }@i{rts-pthread}
23990 @item @code{@ @ @ @ }Tasking @tab pthread library
23991 @item @code{@ @ @ @ }Exceptions @tab ZCX
23992 @*
23993 @item @code{@ @ }@i{rts-sjlj}
23994 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
23995 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23996 @*
23997 @item @b{sparc64-solaris} @tab
23998 @item @code{@ @ }@i{rts-native (default)}
23999 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24000 @item @code{@ @ @ @ }Exceptions @tab ZCX
24001 @*
24002 @item @b{x86-linux}
24003 @item @code{@ @ }@i{rts-native (default)}
24004 @item @code{@ @ @ @ }Tasking @tab pthread library
24005 @item @code{@ @ @ @ }Exceptions @tab ZCX
24006 @*
24007 @item @code{@ @ }@i{rts-sjlj}
24008 @item @code{@ @ @ @ }Tasking @tab pthread library
24009 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24010 @*
24011 @item @b{x86-lynx}
24012 @item @code{@ @ }@i{rts-native (default)}
24013 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
24014 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24015 @*
24016 @item @b{x86-solaris}
24017 @item @code{@ @ }@i{rts-native (default)}
24018 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
24019 @item @code{@ @ @ @ }Exceptions @tab ZCX
24020 @*
24021 @item @code{@ @ }@i{rts-sjlj}
24022 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24023 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24024 @*
24025 @item @b{x86-windows}
24026 @item @code{@ @ }@i{rts-native (default)}
24027 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
24028 @item @code{@ @ @ @ }Exceptions @tab ZCX
24029 @*
24030 @item @code{@ @ }@i{rts-sjlj}
24031 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
24032 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24033 @*
24034 @item @b{x86-windows-rtx}
24035 @item @code{@ @ }@i{rts-rtx-rtss (default)}
24036 @item @code{@ @ @ @ }Tasking @tab RTX real-time subsystem RTSS threads (kernel mode)
24037 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24038 @*
24039 @item @code{@ @ }@i{rts-rtx-w32}
24040 @item @code{@ @ @ @ }Tasking @tab RTX Win32 threads (user mode)
24041 @item @code{@ @ @ @ }Exceptions @tab ZCX
24042 @*
24043 @item @b{x86_64-linux}
24044 @item @code{@ @ }@i{rts-native (default)}
24045 @item @code{@ @ @ @ }Tasking @tab pthread library
24046 @item @code{@ @ @ @ }Exceptions @tab ZCX
24047 @*
24048 @item @code{@ @ }@i{rts-sjlj}
24049 @item @code{@ @ @ @ }Tasking @tab pthread library
24050 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24051 @*
24052 @end multitable
24053
24054 @node Specifying a Run-Time Library
24055 @section Specifying a Run-Time Library
24056
24057 @noindent
24058 The @file{adainclude} subdirectory containing the sources of the GNAT
24059 run-time library, and the @file{adalib} subdirectory containing the
24060 @file{ALI} files and the static and/or shared GNAT library, are located
24061 in the gcc target-dependent area:
24062
24063 @smallexample
24064 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
24065 @end smallexample
24066
24067 @noindent
24068 As indicated above, on some platforms several run-time libraries are supplied.
24069 These libraries are installed in the target dependent area and
24070 contain a complete source and binary subdirectory. The detailed description
24071 below explains the differences between the different libraries in terms of
24072 their thread support.
24073
24074 The default run-time library (when GNAT is installed) is @emph{rts-native}.
24075 This default run time is selected by the means of soft links.
24076 For example on x86-linux:
24077
24078 @smallexample
24079 @group
24080 $(target-dir)
24081 |
24082 +--- adainclude----------+
24083 | |
24084 +--- adalib-----------+ |
24085 | | |
24086 +--- rts-native | |
24087 | | | |
24088 | +--- adainclude <---+
24089 | | |
24090 | +--- adalib <----+
24091 |
24092 +--- rts-sjlj
24093 |
24094 +--- adainclude
24095 |
24096 +--- adalib
24097 @end group
24098 @end smallexample
24099
24100 @noindent
24101 If the @i{rts-sjlj} library is to be selected on a permanent basis,
24102 these soft links can be modified with the following commands:
24103
24104 @smallexample
24105 $ cd $target
24106 $ rm -f adainclude adalib
24107 $ ln -s rts-sjlj/adainclude adainclude
24108 $ ln -s rts-sjlj/adalib adalib
24109 @end smallexample
24110
24111 @noindent
24112 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
24113 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
24114 @file{$target/ada_object_path}.
24115
24116 Selecting another run-time library temporarily can be
24117 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
24118 @cindex @option{--RTS} option
24119
24120 @node Choosing the Scheduling Policy
24121 @section Choosing the Scheduling Policy
24122
24123 @noindent
24124 When using a POSIX threads implementation, you have a choice of several
24125 scheduling policies: @code{SCHED_FIFO},
24126 @cindex @code{SCHED_FIFO} scheduling policy
24127 @code{SCHED_RR}
24128 @cindex @code{SCHED_RR} scheduling policy
24129 and @code{SCHED_OTHER}.
24130 @cindex @code{SCHED_OTHER} scheduling policy
24131 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
24132 or @code{SCHED_RR} requires special (e.g., root) privileges.
24133
24134 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
24135 @code{SCHED_FIFO},
24136 @cindex @code{SCHED_FIFO} scheduling policy
24137 you can use one of the following:
24138
24139 @itemize @bullet
24140 @item
24141 @code{pragma Time_Slice (0.0)}
24142 @cindex pragma Time_Slice
24143 @item
24144 the corresponding binder option @option{-T0}
24145 @cindex @option{-T0} option
24146 @item
24147 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
24148 @cindex pragma Task_Dispatching_Policy
24149 @end itemize
24150
24151 @noindent
24152 To specify @code{SCHED_RR},
24153 @cindex @code{SCHED_RR} scheduling policy
24154 you should use @code{pragma Time_Slice} with a
24155 value greater than @code{0.0}, or else use the corresponding @option{-T}
24156 binder option.
24157
24158 @node Solaris-Specific Considerations
24159 @section Solaris-Specific Considerations
24160 @cindex Solaris Sparc threads libraries
24161
24162 @noindent
24163 This section addresses some topics related to the various threads libraries
24164 on Sparc Solaris.
24165
24166 @menu
24167 * Solaris Threads Issues::
24168 @end menu
24169
24170 @node Solaris Threads Issues
24171 @subsection Solaris Threads Issues
24172
24173 @noindent
24174 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
24175 library based on POSIX threads --- @emph{rts-pthread}.
24176 @cindex rts-pthread threads library
24177 This run-time library has the advantage of being mostly shared across all
24178 POSIX-compliant thread implementations, and it also provides under
24179 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
24180 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
24181 and @code{PTHREAD_PRIO_PROTECT}
24182 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
24183 semantics that can be selected using the predefined pragma
24184 @code{Locking_Policy}
24185 @cindex pragma Locking_Policy (under rts-pthread)
24186 with respectively
24187 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
24188 @cindex @code{Inheritance_Locking} (under rts-pthread)
24189 @cindex @code{Ceiling_Locking} (under rts-pthread)
24190
24191 As explained above, the native run-time library is based on the Solaris thread
24192 library (@code{libthread}) and is the default library.
24193
24194 When the Solaris threads library is used (this is the default), programs
24195 compiled with GNAT can automatically take advantage of
24196 and can thus execute on multiple processors.
24197 The user can alternatively specify a processor on which the program should run
24198 to emulate a single-processor system. The multiprocessor / uniprocessor choice
24199 is made by
24200 setting the environment variable @env{GNAT_PROCESSOR}
24201 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
24202 to one of the following:
24203
24204 @table @code
24205 @item -2
24206 Use the default configuration (run the program on all
24207 available processors) - this is the same as having @code{GNAT_PROCESSOR}
24208 unset
24209
24210 @item -1
24211 Let the run-time implementation choose one processor and run the program on
24212 that processor
24213
24214 @item 0 .. Last_Proc
24215 Run the program on the specified processor.
24216 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
24217 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
24218 @end table
24219
24220 @node Linux-Specific Considerations
24221 @section Linux-Specific Considerations
24222 @cindex Linux threads libraries
24223
24224 @noindent
24225 On GNU/Linux without NPTL support (usually system with GNU C Library
24226 older than 2.3), the signal model is not POSIX compliant, which means
24227 that to send a signal to the process, you need to send the signal to all
24228 threads, e.g.@: by using @code{killpg()}.
24229
24230 @node AIX-Specific Considerations
24231 @section AIX-Specific Considerations
24232 @cindex AIX resolver library
24233
24234 @noindent
24235 On AIX, the resolver library initializes some internal structure on
24236 the first call to @code{get*by*} functions, which are used to implement
24237 @code{GNAT.Sockets.Get_Host_By_Name} and
24238 @code{GNAT.Sockets.Get_Host_By_Address}.
24239 If such initialization occurs within an Ada task, and the stack size for
24240 the task is the default size, a stack overflow may occur.
24241
24242 To avoid this overflow, the user should either ensure that the first call
24243 to @code{GNAT.Sockets.Get_Host_By_Name} or
24244 @code{GNAT.Sockets.Get_Host_By_Addrss}
24245 occurs in the environment task, or use @code{pragma Storage_Size} to
24246 specify a sufficiently large size for the stack of the task that contains
24247 this call.
24248
24249 @node RTX-Specific Considerations
24250 @section RTX-Specific Considerations
24251 @cindex RTX libraries
24252
24253 @noindent
24254 The Real-time Extension (RTX) to Windows is based on the Windows Win32
24255 API. Applications can be built to work in two different modes:
24256
24257 @itemize @bullet
24258 @item
24259 Windows executables that run in Ring 3 to utilize memory protection
24260 (@emph{rts-rtx-w32}).
24261
24262 @item
24263 Real-time subsystem (RTSS) executables that run in Ring 0, where
24264 performance can be optimized with RTSS applications taking precedent
24265 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
24266 the Microsoft linker to handle RTSS libraries.
24267
24268 @end itemize
24269
24270 @node HP-UX-Specific Considerations
24271 @section HP-UX-Specific Considerations
24272 @cindex HP-UX Scheduling
24273
24274 @noindent
24275 On HP-UX, appropriate privileges are required to change the scheduling
24276 parameters of a task. The calling process must have appropriate
24277 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
24278 successfully change the scheduling parameters.
24279
24280 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
24281 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
24282 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
24283
24284 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
24285 one of the following:
24286
24287 @itemize @bullet
24288 @item
24289 @code{pragma Time_Slice (0.0)}
24290 @cindex pragma Time_Slice
24291 @item
24292 the corresponding binder option @option{-T0}
24293 @cindex @option{-T0} option
24294 @item
24295 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
24296 @cindex pragma Task_Dispatching_Policy
24297 @end itemize
24298
24299 @noindent
24300 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
24301 you should use @code{pragma Time_Slice} with a
24302 value greater than @code{0.0}, or use the corresponding @option{-T}
24303 binder option, or set the @code{pragma Task_Dispatching_Policy
24304 (Round_Robin_Within_Priorities)}.
24305
24306 @c *******************************
24307 @node Example of Binder Output File
24308 @appendix Example of Binder Output File
24309
24310 @noindent
24311 This Appendix displays the source code for @command{gnatbind}'s output
24312 file generated for a simple ``Hello World'' program.
24313 Comments have been added for clarification purposes.
24314
24315 @smallexample @c adanocomment
24316 @iftex
24317 @leftskip=0cm
24318 @end iftex
24319 -- The package is called Ada_Main unless this name is actually used
24320 -- as a unit name in the partition, in which case some other unique
24321 -- name is used.
24322
24323 with System;
24324 package ada_main is
24325
24326 Elab_Final_Code : Integer;
24327 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
24328
24329 -- The main program saves the parameters (argument count,
24330 -- argument values, environment pointer) in global variables
24331 -- for later access by other units including
24332 -- Ada.Command_Line.
24333
24334 gnat_argc : Integer;
24335 gnat_argv : System.Address;
24336 gnat_envp : System.Address;
24337
24338 -- The actual variables are stored in a library routine. This
24339 -- is useful for some shared library situations, where there
24340 -- are problems if variables are not in the library.
24341
24342 pragma Import (C, gnat_argc);
24343 pragma Import (C, gnat_argv);
24344 pragma Import (C, gnat_envp);
24345
24346 -- The exit status is similarly an external location
24347
24348 gnat_exit_status : Integer;
24349 pragma Import (C, gnat_exit_status);
24350
24351 GNAT_Version : constant String :=
24352 "GNAT Version: 6.0.0w (20061115)";
24353 pragma Export (C, GNAT_Version, "__gnat_version");
24354
24355 -- This is the generated adafinal routine that performs
24356 -- finalization at the end of execution. In the case where
24357 -- Ada is the main program, this main program makes a call
24358 -- to adafinal at program termination.
24359
24360 procedure adafinal;
24361 pragma Export (C, adafinal, "adafinal");
24362
24363 -- This is the generated adainit routine that performs
24364 -- initialization at the start of execution. In the case
24365 -- where Ada is the main program, this main program makes
24366 -- a call to adainit at program startup.
24367
24368 procedure adainit;
24369 pragma Export (C, adainit, "adainit");
24370
24371 -- This routine is called at the start of execution. It is
24372 -- a dummy routine that is used by the debugger to breakpoint
24373 -- at the start of execution.
24374
24375 procedure Break_Start;
24376 pragma Import (C, Break_Start, "__gnat_break_start");
24377
24378 -- This is the actual generated main program (it would be
24379 -- suppressed if the no main program switch were used). As
24380 -- required by standard system conventions, this program has
24381 -- the external name main.
24382
24383 function main
24384 (argc : Integer;
24385 argv : System.Address;
24386 envp : System.Address)
24387 return Integer;
24388 pragma Export (C, main, "main");
24389
24390 -- The following set of constants give the version
24391 -- identification values for every unit in the bound
24392 -- partition. This identification is computed from all
24393 -- dependent semantic units, and corresponds to the
24394 -- string that would be returned by use of the
24395 -- Body_Version or Version attributes.
24396
24397 type Version_32 is mod 2 ** 32;
24398 u00001 : constant Version_32 := 16#7880BEB3#;
24399 u00002 : constant Version_32 := 16#0D24CBD0#;
24400 u00003 : constant Version_32 := 16#3283DBEB#;
24401 u00004 : constant Version_32 := 16#2359F9ED#;
24402 u00005 : constant Version_32 := 16#664FB847#;
24403 u00006 : constant Version_32 := 16#68E803DF#;
24404 u00007 : constant Version_32 := 16#5572E604#;
24405 u00008 : constant Version_32 := 16#46B173D8#;
24406 u00009 : constant Version_32 := 16#156A40CF#;
24407 u00010 : constant Version_32 := 16#033DABE0#;
24408 u00011 : constant Version_32 := 16#6AB38FEA#;
24409 u00012 : constant Version_32 := 16#22B6217D#;
24410 u00013 : constant Version_32 := 16#68A22947#;
24411 u00014 : constant Version_32 := 16#18CC4A56#;
24412 u00015 : constant Version_32 := 16#08258E1B#;
24413 u00016 : constant Version_32 := 16#367D5222#;
24414 u00017 : constant Version_32 := 16#20C9ECA4#;
24415 u00018 : constant Version_32 := 16#50D32CB6#;
24416 u00019 : constant Version_32 := 16#39A8BB77#;
24417 u00020 : constant Version_32 := 16#5CF8FA2B#;
24418 u00021 : constant Version_32 := 16#2F1EB794#;
24419 u00022 : constant Version_32 := 16#31AB6444#;
24420 u00023 : constant Version_32 := 16#1574B6E9#;
24421 u00024 : constant Version_32 := 16#5109C189#;
24422 u00025 : constant Version_32 := 16#56D770CD#;
24423 u00026 : constant Version_32 := 16#02F9DE3D#;
24424 u00027 : constant Version_32 := 16#08AB6B2C#;
24425 u00028 : constant Version_32 := 16#3FA37670#;
24426 u00029 : constant Version_32 := 16#476457A0#;
24427 u00030 : constant Version_32 := 16#731E1B6E#;
24428 u00031 : constant Version_32 := 16#23C2E789#;
24429 u00032 : constant Version_32 := 16#0F1BD6A1#;
24430 u00033 : constant Version_32 := 16#7C25DE96#;
24431 u00034 : constant Version_32 := 16#39ADFFA2#;
24432 u00035 : constant Version_32 := 16#571DE3E7#;
24433 u00036 : constant Version_32 := 16#5EB646AB#;
24434 u00037 : constant Version_32 := 16#4249379B#;
24435 u00038 : constant Version_32 := 16#0357E00A#;
24436 u00039 : constant Version_32 := 16#3784FB72#;
24437 u00040 : constant Version_32 := 16#2E723019#;
24438 u00041 : constant Version_32 := 16#623358EA#;
24439 u00042 : constant Version_32 := 16#107F9465#;
24440 u00043 : constant Version_32 := 16#6843F68A#;
24441 u00044 : constant Version_32 := 16#63305874#;
24442 u00045 : constant Version_32 := 16#31E56CE1#;
24443 u00046 : constant Version_32 := 16#02917970#;
24444 u00047 : constant Version_32 := 16#6CCBA70E#;
24445 u00048 : constant Version_32 := 16#41CD4204#;
24446 u00049 : constant Version_32 := 16#572E3F58#;
24447 u00050 : constant Version_32 := 16#20729FF5#;
24448 u00051 : constant Version_32 := 16#1D4F93E8#;
24449 u00052 : constant Version_32 := 16#30B2EC3D#;
24450 u00053 : constant Version_32 := 16#34054F96#;
24451 u00054 : constant Version_32 := 16#5A199860#;
24452 u00055 : constant Version_32 := 16#0E7F912B#;
24453 u00056 : constant Version_32 := 16#5760634A#;
24454 u00057 : constant Version_32 := 16#5D851835#;
24455
24456 -- The following Export pragmas export the version numbers
24457 -- with symbolic names ending in B (for body) or S
24458 -- (for spec) so that they can be located in a link. The
24459 -- information provided here is sufficient to track down
24460 -- the exact versions of units used in a given build.
24461
24462 pragma Export (C, u00001, "helloB");
24463 pragma Export (C, u00002, "system__standard_libraryB");
24464 pragma Export (C, u00003, "system__standard_libraryS");
24465 pragma Export (C, u00004, "adaS");
24466 pragma Export (C, u00005, "ada__text_ioB");
24467 pragma Export (C, u00006, "ada__text_ioS");
24468 pragma Export (C, u00007, "ada__exceptionsB");
24469 pragma Export (C, u00008, "ada__exceptionsS");
24470 pragma Export (C, u00009, "gnatS");
24471 pragma Export (C, u00010, "gnat__heap_sort_aB");
24472 pragma Export (C, u00011, "gnat__heap_sort_aS");
24473 pragma Export (C, u00012, "systemS");
24474 pragma Export (C, u00013, "system__exception_tableB");
24475 pragma Export (C, u00014, "system__exception_tableS");
24476 pragma Export (C, u00015, "gnat__htableB");
24477 pragma Export (C, u00016, "gnat__htableS");
24478 pragma Export (C, u00017, "system__exceptionsS");
24479 pragma Export (C, u00018, "system__machine_state_operationsB");
24480 pragma Export (C, u00019, "system__machine_state_operationsS");
24481 pragma Export (C, u00020, "system__machine_codeS");
24482 pragma Export (C, u00021, "system__storage_elementsB");
24483 pragma Export (C, u00022, "system__storage_elementsS");
24484 pragma Export (C, u00023, "system__secondary_stackB");
24485 pragma Export (C, u00024, "system__secondary_stackS");
24486 pragma Export (C, u00025, "system__parametersB");
24487 pragma Export (C, u00026, "system__parametersS");
24488 pragma Export (C, u00027, "system__soft_linksB");
24489 pragma Export (C, u00028, "system__soft_linksS");
24490 pragma Export (C, u00029, "system__stack_checkingB");
24491 pragma Export (C, u00030, "system__stack_checkingS");
24492 pragma Export (C, u00031, "system__tracebackB");
24493 pragma Export (C, u00032, "system__tracebackS");
24494 pragma Export (C, u00033, "ada__streamsS");
24495 pragma Export (C, u00034, "ada__tagsB");
24496 pragma Export (C, u00035, "ada__tagsS");
24497 pragma Export (C, u00036, "system__string_opsB");
24498 pragma Export (C, u00037, "system__string_opsS");
24499 pragma Export (C, u00038, "interfacesS");
24500 pragma Export (C, u00039, "interfaces__c_streamsB");
24501 pragma Export (C, u00040, "interfaces__c_streamsS");
24502 pragma Export (C, u00041, "system__file_ioB");
24503 pragma Export (C, u00042, "system__file_ioS");
24504 pragma Export (C, u00043, "ada__finalizationB");
24505 pragma Export (C, u00044, "ada__finalizationS");
24506 pragma Export (C, u00045, "system__finalization_rootB");
24507 pragma Export (C, u00046, "system__finalization_rootS");
24508 pragma Export (C, u00047, "system__finalization_implementationB");
24509 pragma Export (C, u00048, "system__finalization_implementationS");
24510 pragma Export (C, u00049, "system__string_ops_concat_3B");
24511 pragma Export (C, u00050, "system__string_ops_concat_3S");
24512 pragma Export (C, u00051, "system__stream_attributesB");
24513 pragma Export (C, u00052, "system__stream_attributesS");
24514 pragma Export (C, u00053, "ada__io_exceptionsS");
24515 pragma Export (C, u00054, "system__unsigned_typesS");
24516 pragma Export (C, u00055, "system__file_control_blockS");
24517 pragma Export (C, u00056, "ada__finalization__list_controllerB");
24518 pragma Export (C, u00057, "ada__finalization__list_controllerS");
24519
24520 -- BEGIN ELABORATION ORDER
24521 -- ada (spec)
24522 -- gnat (spec)
24523 -- gnat.heap_sort_a (spec)
24524 -- gnat.heap_sort_a (body)
24525 -- gnat.htable (spec)
24526 -- gnat.htable (body)
24527 -- interfaces (spec)
24528 -- system (spec)
24529 -- system.machine_code (spec)
24530 -- system.parameters (spec)
24531 -- system.parameters (body)
24532 -- interfaces.c_streams (spec)
24533 -- interfaces.c_streams (body)
24534 -- system.standard_library (spec)
24535 -- ada.exceptions (spec)
24536 -- system.exception_table (spec)
24537 -- system.exception_table (body)
24538 -- ada.io_exceptions (spec)
24539 -- system.exceptions (spec)
24540 -- system.storage_elements (spec)
24541 -- system.storage_elements (body)
24542 -- system.machine_state_operations (spec)
24543 -- system.machine_state_operations (body)
24544 -- system.secondary_stack (spec)
24545 -- system.stack_checking (spec)
24546 -- system.soft_links (spec)
24547 -- system.soft_links (body)
24548 -- system.stack_checking (body)
24549 -- system.secondary_stack (body)
24550 -- system.standard_library (body)
24551 -- system.string_ops (spec)
24552 -- system.string_ops (body)
24553 -- ada.tags (spec)
24554 -- ada.tags (body)
24555 -- ada.streams (spec)
24556 -- system.finalization_root (spec)
24557 -- system.finalization_root (body)
24558 -- system.string_ops_concat_3 (spec)
24559 -- system.string_ops_concat_3 (body)
24560 -- system.traceback (spec)
24561 -- system.traceback (body)
24562 -- ada.exceptions (body)
24563 -- system.unsigned_types (spec)
24564 -- system.stream_attributes (spec)
24565 -- system.stream_attributes (body)
24566 -- system.finalization_implementation (spec)
24567 -- system.finalization_implementation (body)
24568 -- ada.finalization (spec)
24569 -- ada.finalization (body)
24570 -- ada.finalization.list_controller (spec)
24571 -- ada.finalization.list_controller (body)
24572 -- system.file_control_block (spec)
24573 -- system.file_io (spec)
24574 -- system.file_io (body)
24575 -- ada.text_io (spec)
24576 -- ada.text_io (body)
24577 -- hello (body)
24578 -- END ELABORATION ORDER
24579
24580 end ada_main;
24581
24582 -- The following source file name pragmas allow the generated file
24583 -- names to be unique for different main programs. They are needed
24584 -- since the package name will always be Ada_Main.
24585
24586 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
24587 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
24588
24589 -- Generated package body for Ada_Main starts here
24590
24591 package body ada_main is
24592
24593 -- The actual finalization is performed by calling the
24594 -- library routine in System.Standard_Library.Adafinal
24595
24596 procedure Do_Finalize;
24597 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
24598
24599 -------------
24600 -- adainit --
24601 -------------
24602
24603 @findex adainit
24604 procedure adainit is
24605
24606 -- These booleans are set to True once the associated unit has
24607 -- been elaborated. It is also used to avoid elaborating the
24608 -- same unit twice.
24609
24610 E040 : Boolean;
24611 pragma Import (Ada, E040, "interfaces__c_streams_E");
24612
24613 E008 : Boolean;
24614 pragma Import (Ada, E008, "ada__exceptions_E");
24615
24616 E014 : Boolean;
24617 pragma Import (Ada, E014, "system__exception_table_E");
24618
24619 E053 : Boolean;
24620 pragma Import (Ada, E053, "ada__io_exceptions_E");
24621
24622 E017 : Boolean;
24623 pragma Import (Ada, E017, "system__exceptions_E");
24624
24625 E024 : Boolean;
24626 pragma Import (Ada, E024, "system__secondary_stack_E");
24627
24628 E030 : Boolean;
24629 pragma Import (Ada, E030, "system__stack_checking_E");
24630
24631 E028 : Boolean;
24632 pragma Import (Ada, E028, "system__soft_links_E");
24633
24634 E035 : Boolean;
24635 pragma Import (Ada, E035, "ada__tags_E");
24636
24637 E033 : Boolean;
24638 pragma Import (Ada, E033, "ada__streams_E");
24639
24640 E046 : Boolean;
24641 pragma Import (Ada, E046, "system__finalization_root_E");
24642
24643 E048 : Boolean;
24644 pragma Import (Ada, E048, "system__finalization_implementation_E");
24645
24646 E044 : Boolean;
24647 pragma Import (Ada, E044, "ada__finalization_E");
24648
24649 E057 : Boolean;
24650 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
24651
24652 E055 : Boolean;
24653 pragma Import (Ada, E055, "system__file_control_block_E");
24654
24655 E042 : Boolean;
24656 pragma Import (Ada, E042, "system__file_io_E");
24657
24658 E006 : Boolean;
24659 pragma Import (Ada, E006, "ada__text_io_E");
24660
24661 -- Set_Globals is a library routine that stores away the
24662 -- value of the indicated set of global values in global
24663 -- variables within the library.
24664
24665 procedure Set_Globals
24666 (Main_Priority : Integer;
24667 Time_Slice_Value : Integer;
24668 WC_Encoding : Character;
24669 Locking_Policy : Character;
24670 Queuing_Policy : Character;
24671 Task_Dispatching_Policy : Character;
24672 Adafinal : System.Address;
24673 Unreserve_All_Interrupts : Integer;
24674 Exception_Tracebacks : Integer);
24675 @findex __gnat_set_globals
24676 pragma Import (C, Set_Globals, "__gnat_set_globals");
24677
24678 -- SDP_Table_Build is a library routine used to build the
24679 -- exception tables. See unit Ada.Exceptions in files
24680 -- a-except.ads/adb for full details of how zero cost
24681 -- exception handling works. This procedure, the call to
24682 -- it, and the two following tables are all omitted if the
24683 -- build is in longjmp/setjmp exception mode.
24684
24685 @findex SDP_Table_Build
24686 @findex Zero Cost Exceptions
24687 procedure SDP_Table_Build
24688 (SDP_Addresses : System.Address;
24689 SDP_Count : Natural;
24690 Elab_Addresses : System.Address;
24691 Elab_Addr_Count : Natural);
24692 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
24693
24694 -- Table of Unit_Exception_Table addresses. Used for zero
24695 -- cost exception handling to build the top level table.
24696
24697 ST : aliased constant array (1 .. 23) of System.Address := (
24698 Hello'UET_Address,
24699 Ada.Text_Io'UET_Address,
24700 Ada.Exceptions'UET_Address,
24701 Gnat.Heap_Sort_A'UET_Address,
24702 System.Exception_Table'UET_Address,
24703 System.Machine_State_Operations'UET_Address,
24704 System.Secondary_Stack'UET_Address,
24705 System.Parameters'UET_Address,
24706 System.Soft_Links'UET_Address,
24707 System.Stack_Checking'UET_Address,
24708 System.Traceback'UET_Address,
24709 Ada.Streams'UET_Address,
24710 Ada.Tags'UET_Address,
24711 System.String_Ops'UET_Address,
24712 Interfaces.C_Streams'UET_Address,
24713 System.File_Io'UET_Address,
24714 Ada.Finalization'UET_Address,
24715 System.Finalization_Root'UET_Address,
24716 System.Finalization_Implementation'UET_Address,
24717 System.String_Ops_Concat_3'UET_Address,
24718 System.Stream_Attributes'UET_Address,
24719 System.File_Control_Block'UET_Address,
24720 Ada.Finalization.List_Controller'UET_Address);
24721
24722 -- Table of addresses of elaboration routines. Used for
24723 -- zero cost exception handling to make sure these
24724 -- addresses are included in the top level procedure
24725 -- address table.
24726
24727 EA : aliased constant array (1 .. 23) of System.Address := (
24728 adainit'Code_Address,
24729 Do_Finalize'Code_Address,
24730 Ada.Exceptions'Elab_Spec'Address,
24731 System.Exceptions'Elab_Spec'Address,
24732 Interfaces.C_Streams'Elab_Spec'Address,
24733 System.Exception_Table'Elab_Body'Address,
24734 Ada.Io_Exceptions'Elab_Spec'Address,
24735 System.Stack_Checking'Elab_Spec'Address,
24736 System.Soft_Links'Elab_Body'Address,
24737 System.Secondary_Stack'Elab_Body'Address,
24738 Ada.Tags'Elab_Spec'Address,
24739 Ada.Tags'Elab_Body'Address,
24740 Ada.Streams'Elab_Spec'Address,
24741 System.Finalization_Root'Elab_Spec'Address,
24742 Ada.Exceptions'Elab_Body'Address,
24743 System.Finalization_Implementation'Elab_Spec'Address,
24744 System.Finalization_Implementation'Elab_Body'Address,
24745 Ada.Finalization'Elab_Spec'Address,
24746 Ada.Finalization.List_Controller'Elab_Spec'Address,
24747 System.File_Control_Block'Elab_Spec'Address,
24748 System.File_Io'Elab_Body'Address,
24749 Ada.Text_Io'Elab_Spec'Address,
24750 Ada.Text_Io'Elab_Body'Address);
24751
24752 -- Start of processing for adainit
24753
24754 begin
24755
24756 -- Call SDP_Table_Build to build the top level procedure
24757 -- table for zero cost exception handling (omitted in
24758 -- longjmp/setjmp mode).
24759
24760 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
24761
24762 -- Call Set_Globals to record various information for
24763 -- this partition. The values are derived by the binder
24764 -- from information stored in the ali files by the compiler.
24765
24766 @findex __gnat_set_globals
24767 Set_Globals
24768 (Main_Priority => -1,
24769 -- Priority of main program, -1 if no pragma Priority used
24770
24771 Time_Slice_Value => -1,
24772 -- Time slice from Time_Slice pragma, -1 if none used
24773
24774 WC_Encoding => 'b',
24775 -- Wide_Character encoding used, default is brackets
24776
24777 Locking_Policy => ' ',
24778 -- Locking_Policy used, default of space means not
24779 -- specified, otherwise it is the first character of
24780 -- the policy name.
24781
24782 Queuing_Policy => ' ',
24783 -- Queuing_Policy used, default of space means not
24784 -- specified, otherwise it is the first character of
24785 -- the policy name.
24786
24787 Task_Dispatching_Policy => ' ',
24788 -- Task_Dispatching_Policy used, default of space means
24789 -- not specified, otherwise first character of the
24790 -- policy name.
24791
24792 Adafinal => System.Null_Address,
24793 -- Address of Adafinal routine, not used anymore
24794
24795 Unreserve_All_Interrupts => 0,
24796 -- Set true if pragma Unreserve_All_Interrupts was used
24797
24798 Exception_Tracebacks => 0);
24799 -- Indicates if exception tracebacks are enabled
24800
24801 Elab_Final_Code := 1;
24802
24803 -- Now we have the elaboration calls for all units in the partition.
24804 -- The Elab_Spec and Elab_Body attributes generate references to the
24805 -- implicit elaboration procedures generated by the compiler for
24806 -- each unit that requires elaboration.
24807
24808 if not E040 then
24809 Interfaces.C_Streams'Elab_Spec;
24810 end if;
24811 E040 := True;
24812 if not E008 then
24813 Ada.Exceptions'Elab_Spec;
24814 end if;
24815 if not E014 then
24816 System.Exception_Table'Elab_Body;
24817 E014 := True;
24818 end if;
24819 if not E053 then
24820 Ada.Io_Exceptions'Elab_Spec;
24821 E053 := True;
24822 end if;
24823 if not E017 then
24824 System.Exceptions'Elab_Spec;
24825 E017 := True;
24826 end if;
24827 if not E030 then
24828 System.Stack_Checking'Elab_Spec;
24829 end if;
24830 if not E028 then
24831 System.Soft_Links'Elab_Body;
24832 E028 := True;
24833 end if;
24834 E030 := True;
24835 if not E024 then
24836 System.Secondary_Stack'Elab_Body;
24837 E024 := True;
24838 end if;
24839 if not E035 then
24840 Ada.Tags'Elab_Spec;
24841 end if;
24842 if not E035 then
24843 Ada.Tags'Elab_Body;
24844 E035 := True;
24845 end if;
24846 if not E033 then
24847 Ada.Streams'Elab_Spec;
24848 E033 := True;
24849 end if;
24850 if not E046 then
24851 System.Finalization_Root'Elab_Spec;
24852 end if;
24853 E046 := True;
24854 if not E008 then
24855 Ada.Exceptions'Elab_Body;
24856 E008 := True;
24857 end if;
24858 if not E048 then
24859 System.Finalization_Implementation'Elab_Spec;
24860 end if;
24861 if not E048 then
24862 System.Finalization_Implementation'Elab_Body;
24863 E048 := True;
24864 end if;
24865 if not E044 then
24866 Ada.Finalization'Elab_Spec;
24867 end if;
24868 E044 := True;
24869 if not E057 then
24870 Ada.Finalization.List_Controller'Elab_Spec;
24871 end if;
24872 E057 := True;
24873 if not E055 then
24874 System.File_Control_Block'Elab_Spec;
24875 E055 := True;
24876 end if;
24877 if not E042 then
24878 System.File_Io'Elab_Body;
24879 E042 := True;
24880 end if;
24881 if not E006 then
24882 Ada.Text_Io'Elab_Spec;
24883 end if;
24884 if not E006 then
24885 Ada.Text_Io'Elab_Body;
24886 E006 := True;
24887 end if;
24888
24889 Elab_Final_Code := 0;
24890 end adainit;
24891
24892 --------------
24893 -- adafinal --
24894 --------------
24895
24896 @findex adafinal
24897 procedure adafinal is
24898 begin
24899 Do_Finalize;
24900 end adafinal;
24901
24902 ----------
24903 -- main --
24904 ----------
24905
24906 -- main is actually a function, as in the ANSI C standard,
24907 -- defined to return the exit status. The three parameters
24908 -- are the argument count, argument values and environment
24909 -- pointer.
24910
24911 @findex Main Program
24912 function main
24913 (argc : Integer;
24914 argv : System.Address;
24915 envp : System.Address)
24916 return Integer
24917 is
24918 -- The initialize routine performs low level system
24919 -- initialization using a standard library routine which
24920 -- sets up signal handling and performs any other
24921 -- required setup. The routine can be found in file
24922 -- a-init.c.
24923
24924 @findex __gnat_initialize
24925 procedure initialize;
24926 pragma Import (C, initialize, "__gnat_initialize");
24927
24928 -- The finalize routine performs low level system
24929 -- finalization using a standard library routine. The
24930 -- routine is found in file a-final.c and in the standard
24931 -- distribution is a dummy routine that does nothing, so
24932 -- really this is a hook for special user finalization.
24933
24934 @findex __gnat_finalize
24935 procedure finalize;
24936 pragma Import (C, finalize, "__gnat_finalize");
24937
24938 -- We get to the main program of the partition by using
24939 -- pragma Import because if we try to with the unit and
24940 -- call it Ada style, then not only do we waste time
24941 -- recompiling it, but also, we don't really know the right
24942 -- switches (e.g.@: identifier character set) to be used
24943 -- to compile it.
24944
24945 procedure Ada_Main_Program;
24946 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
24947
24948 -- Start of processing for main
24949
24950 begin
24951 -- Save global variables
24952
24953 gnat_argc := argc;
24954 gnat_argv := argv;
24955 gnat_envp := envp;
24956
24957 -- Call low level system initialization
24958
24959 Initialize;
24960
24961 -- Call our generated Ada initialization routine
24962
24963 adainit;
24964
24965 -- This is the point at which we want the debugger to get
24966 -- control
24967
24968 Break_Start;
24969
24970 -- Now we call the main program of the partition
24971
24972 Ada_Main_Program;
24973
24974 -- Perform Ada finalization
24975
24976 adafinal;
24977
24978 -- Perform low level system finalization
24979
24980 Finalize;
24981
24982 -- Return the proper exit status
24983 return (gnat_exit_status);
24984 end;
24985
24986 -- This section is entirely comments, so it has no effect on the
24987 -- compilation of the Ada_Main package. It provides the list of
24988 -- object files and linker options, as well as some standard
24989 -- libraries needed for the link. The gnatlink utility parses
24990 -- this b~hello.adb file to read these comment lines to generate
24991 -- the appropriate command line arguments for the call to the
24992 -- system linker. The BEGIN/END lines are used for sentinels for
24993 -- this parsing operation.
24994
24995 -- The exact file names will of course depend on the environment,
24996 -- host/target and location of files on the host system.
24997
24998 @findex Object file list
24999 -- BEGIN Object file/option list
25000 -- ./hello.o
25001 -- -L./
25002 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
25003 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
25004 -- END Object file/option list
25005
25006 end ada_main;
25007 @end smallexample
25008
25009 @noindent
25010 The Ada code in the above example is exactly what is generated by the
25011 binder. We have added comments to more clearly indicate the function
25012 of each part of the generated @code{Ada_Main} package.
25013
25014 The code is standard Ada in all respects, and can be processed by any
25015 tools that handle Ada. In particular, it is possible to use the debugger
25016 in Ada mode to debug the generated @code{Ada_Main} package. For example,
25017 suppose that for reasons that you do not understand, your program is crashing
25018 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
25019 you can place a breakpoint on the call:
25020
25021 @smallexample @c ada
25022 Ada.Text_Io'Elab_Body;
25023 @end smallexample
25024
25025 @noindent
25026 and trace the elaboration routine for this package to find out where
25027 the problem might be (more usually of course you would be debugging
25028 elaboration code in your own application).
25029
25030 @node Elaboration Order Handling in GNAT
25031 @appendix Elaboration Order Handling in GNAT
25032 @cindex Order of elaboration
25033 @cindex Elaboration control
25034
25035 @menu
25036 * Elaboration Code::
25037 * Checking the Elaboration Order::
25038 * Controlling the Elaboration Order::
25039 * Controlling Elaboration in GNAT - Internal Calls::
25040 * Controlling Elaboration in GNAT - External Calls::
25041 * Default Behavior in GNAT - Ensuring Safety::
25042 * Treatment of Pragma Elaborate::
25043 * Elaboration Issues for Library Tasks::
25044 * Mixing Elaboration Models::
25045 * What to Do If the Default Elaboration Behavior Fails::
25046 * Elaboration for Dispatching Calls::
25047 * Summary of Procedures for Elaboration Control::
25048 * Other Elaboration Order Considerations::
25049 @end menu
25050
25051 @noindent
25052 This chapter describes the handling of elaboration code in Ada and
25053 in GNAT, and discusses how the order of elaboration of program units can
25054 be controlled in GNAT, either automatically or with explicit programming
25055 features.
25056
25057 @node Elaboration Code
25058 @section Elaboration Code
25059
25060 @noindent
25061 Ada provides rather general mechanisms for executing code at elaboration
25062 time, that is to say before the main program starts executing. Such code arises
25063 in three contexts:
25064
25065 @table @asis
25066 @item Initializers for variables.
25067 Variables declared at the library level, in package specs or bodies, can
25068 require initialization that is performed at elaboration time, as in:
25069 @smallexample @c ada
25070 @cartouche
25071 Sqrt_Half : Float := Sqrt (0.5);
25072 @end cartouche
25073 @end smallexample
25074
25075 @item Package initialization code
25076 Code in a @code{BEGIN-END} section at the outer level of a package body is
25077 executed as part of the package body elaboration code.
25078
25079 @item Library level task allocators
25080 Tasks that are declared using task allocators at the library level
25081 start executing immediately and hence can execute at elaboration time.
25082 @end table
25083
25084 @noindent
25085 Subprogram calls are possible in any of these contexts, which means that
25086 any arbitrary part of the program may be executed as part of the elaboration
25087 code. It is even possible to write a program which does all its work at
25088 elaboration time, with a null main program, although stylistically this
25089 would usually be considered an inappropriate way to structure
25090 a program.
25091
25092 An important concern arises in the context of elaboration code:
25093 we have to be sure that it is executed in an appropriate order. What we
25094 have is a series of elaboration code sections, potentially one section
25095 for each unit in the program. It is important that these execute
25096 in the correct order. Correctness here means that, taking the above
25097 example of the declaration of @code{Sqrt_Half},
25098 if some other piece of
25099 elaboration code references @code{Sqrt_Half},
25100 then it must run after the
25101 section of elaboration code that contains the declaration of
25102 @code{Sqrt_Half}.
25103
25104 There would never be any order of elaboration problem if we made a rule
25105 that whenever you @code{with} a unit, you must elaborate both the spec and body
25106 of that unit before elaborating the unit doing the @code{with}'ing:
25107
25108 @smallexample @c ada
25109 @group
25110 @cartouche
25111 with Unit_1;
25112 package Unit_2 is @dots{}
25113 @end cartouche
25114 @end group
25115 @end smallexample
25116
25117 @noindent
25118 would require that both the body and spec of @code{Unit_1} be elaborated
25119 before the spec of @code{Unit_2}. However, a rule like that would be far too
25120 restrictive. In particular, it would make it impossible to have routines
25121 in separate packages that were mutually recursive.
25122
25123 You might think that a clever enough compiler could look at the actual
25124 elaboration code and determine an appropriate correct order of elaboration,
25125 but in the general case, this is not possible. Consider the following
25126 example.
25127
25128 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
25129 that references
25130 the variable @code{Sqrt_1}, which is declared in the elaboration code
25131 of the body of @code{Unit_1}:
25132
25133 @smallexample @c ada
25134 @cartouche
25135 Sqrt_1 : Float := Sqrt (0.1);
25136 @end cartouche
25137 @end smallexample
25138
25139 @noindent
25140 The elaboration code of the body of @code{Unit_1} also contains:
25141
25142 @smallexample @c ada
25143 @group
25144 @cartouche
25145 if expression_1 = 1 then
25146 Q := Unit_2.Func_2;
25147 end if;
25148 @end cartouche
25149 @end group
25150 @end smallexample
25151
25152 @noindent
25153 @code{Unit_2} is exactly parallel,
25154 it has a procedure @code{Func_2} that references
25155 the variable @code{Sqrt_2}, which is declared in the elaboration code of
25156 the body @code{Unit_2}:
25157
25158 @smallexample @c ada
25159 @cartouche
25160 Sqrt_2 : Float := Sqrt (0.1);
25161 @end cartouche
25162 @end smallexample
25163
25164 @noindent
25165 The elaboration code of the body of @code{Unit_2} also contains:
25166
25167 @smallexample @c ada
25168 @group
25169 @cartouche
25170 if expression_2 = 2 then
25171 Q := Unit_1.Func_1;
25172 end if;
25173 @end cartouche
25174 @end group
25175 @end smallexample
25176
25177 @noindent
25178 Now the question is, which of the following orders of elaboration is
25179 acceptable:
25180
25181 @smallexample
25182 @group
25183 Spec of Unit_1
25184 Spec of Unit_2
25185 Body of Unit_1
25186 Body of Unit_2
25187 @end group
25188 @end smallexample
25189
25190 @noindent
25191 or
25192
25193 @smallexample
25194 @group
25195 Spec of Unit_2
25196 Spec of Unit_1
25197 Body of Unit_2
25198 Body of Unit_1
25199 @end group
25200 @end smallexample
25201
25202 @noindent
25203 If you carefully analyze the flow here, you will see that you cannot tell
25204 at compile time the answer to this question.
25205 If @code{expression_1} is not equal to 1,
25206 and @code{expression_2} is not equal to 2,
25207 then either order is acceptable, because neither of the function calls is
25208 executed. If both tests evaluate to true, then neither order is acceptable
25209 and in fact there is no correct order.
25210
25211 If one of the two expressions is true, and the other is false, then one
25212 of the above orders is correct, and the other is incorrect. For example,
25213 if @code{expression_1} /= 1 and @code{expression_2} = 2,
25214 then the call to @code{Func_1}
25215 will occur, but not the call to @code{Func_2.}
25216 This means that it is essential
25217 to elaborate the body of @code{Unit_1} before
25218 the body of @code{Unit_2}, so the first
25219 order of elaboration is correct and the second is wrong.
25220
25221 By making @code{expression_1} and @code{expression_2}
25222 depend on input data, or perhaps
25223 the time of day, we can make it impossible for the compiler or binder
25224 to figure out which of these expressions will be true, and hence it
25225 is impossible to guarantee a safe order of elaboration at run time.
25226
25227 @node Checking the Elaboration Order
25228 @section Checking the Elaboration Order
25229
25230 @noindent
25231 In some languages that involve the same kind of elaboration problems,
25232 e.g.@: Java and C++, the programmer is expected to worry about these
25233 ordering problems himself, and it is common to
25234 write a program in which an incorrect elaboration order gives
25235 surprising results, because it references variables before they
25236 are initialized.
25237 Ada is designed to be a safe language, and a programmer-beware approach is
25238 clearly not sufficient. Consequently, the language provides three lines
25239 of defense:
25240
25241 @table @asis
25242 @item Standard rules
25243 Some standard rules restrict the possible choice of elaboration
25244 order. In particular, if you @code{with} a unit, then its spec is always
25245 elaborated before the unit doing the @code{with}. Similarly, a parent
25246 spec is always elaborated before the child spec, and finally
25247 a spec is always elaborated before its corresponding body.
25248
25249 @item Dynamic elaboration checks
25250 @cindex Elaboration checks
25251 @cindex Checks, elaboration
25252 Dynamic checks are made at run time, so that if some entity is accessed
25253 before it is elaborated (typically by means of a subprogram call)
25254 then the exception (@code{Program_Error}) is raised.
25255
25256 @item Elaboration control
25257 Facilities are provided for the programmer to specify the desired order
25258 of elaboration.
25259 @end table
25260
25261 Let's look at these facilities in more detail. First, the rules for
25262 dynamic checking. One possible rule would be simply to say that the
25263 exception is raised if you access a variable which has not yet been
25264 elaborated. The trouble with this approach is that it could require
25265 expensive checks on every variable reference. Instead Ada has two
25266 rules which are a little more restrictive, but easier to check, and
25267 easier to state:
25268
25269 @table @asis
25270 @item Restrictions on calls
25271 A subprogram can only be called at elaboration time if its body
25272 has been elaborated. The rules for elaboration given above guarantee
25273 that the spec of the subprogram has been elaborated before the
25274 call, but not the body. If this rule is violated, then the
25275 exception @code{Program_Error} is raised.
25276
25277 @item Restrictions on instantiations
25278 A generic unit can only be instantiated if the body of the generic
25279 unit has been elaborated. Again, the rules for elaboration given above
25280 guarantee that the spec of the generic unit has been elaborated
25281 before the instantiation, but not the body. If this rule is
25282 violated, then the exception @code{Program_Error} is raised.
25283 @end table
25284
25285 @noindent
25286 The idea is that if the body has been elaborated, then any variables
25287 it references must have been elaborated; by checking for the body being
25288 elaborated we guarantee that none of its references causes any
25289 trouble. As we noted above, this is a little too restrictive, because a
25290 subprogram that has no non-local references in its body may in fact be safe
25291 to call. However, it really would be unsafe to rely on this, because
25292 it would mean that the caller was aware of details of the implementation
25293 in the body. This goes against the basic tenets of Ada.
25294
25295 A plausible implementation can be described as follows.
25296 A Boolean variable is associated with each subprogram
25297 and each generic unit. This variable is initialized to False, and is set to
25298 True at the point body is elaborated. Every call or instantiation checks the
25299 variable, and raises @code{Program_Error} if the variable is False.
25300
25301 Note that one might think that it would be good enough to have one Boolean
25302 variable for each package, but that would not deal with cases of trying
25303 to call a body in the same package as the call
25304 that has not been elaborated yet.
25305 Of course a compiler may be able to do enough analysis to optimize away
25306 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
25307 does such optimizations, but still the easiest conceptual model is to
25308 think of there being one variable per subprogram.
25309
25310 @node Controlling the Elaboration Order
25311 @section Controlling the Elaboration Order
25312
25313 @noindent
25314 In the previous section we discussed the rules in Ada which ensure
25315 that @code{Program_Error} is raised if an incorrect elaboration order is
25316 chosen. This prevents erroneous executions, but we need mechanisms to
25317 specify a correct execution and avoid the exception altogether.
25318 To achieve this, Ada provides a number of features for controlling
25319 the order of elaboration. We discuss these features in this section.
25320
25321 First, there are several ways of indicating to the compiler that a given
25322 unit has no elaboration problems:
25323
25324 @table @asis
25325 @item packages that do not require a body
25326 A library package that does not require a body does not permit
25327 a body (this rule was introduced in Ada 95).
25328 Thus if we have a such a package, as in:
25329
25330 @smallexample @c ada
25331 @group
25332 @cartouche
25333 package Definitions is
25334 generic
25335 type m is new integer;
25336 package Subp is
25337 type a is array (1 .. 10) of m;
25338 type b is array (1 .. 20) of m;
25339 end Subp;
25340 end Definitions;
25341 @end cartouche
25342 @end group
25343 @end smallexample
25344
25345 @noindent
25346 A package that @code{with}'s @code{Definitions} may safely instantiate
25347 @code{Definitions.Subp} because the compiler can determine that there
25348 definitely is no package body to worry about in this case
25349
25350 @item pragma Pure
25351 @cindex pragma Pure
25352 @findex Pure
25353 Places sufficient restrictions on a unit to guarantee that
25354 no call to any subprogram in the unit can result in an
25355 elaboration problem. This means that the compiler does not need
25356 to worry about the point of elaboration of such units, and in
25357 particular, does not need to check any calls to any subprograms
25358 in this unit.
25359
25360 @item pragma Preelaborate
25361 @findex Preelaborate
25362 @cindex pragma Preelaborate
25363 This pragma places slightly less stringent restrictions on a unit than
25364 does pragma Pure,
25365 but these restrictions are still sufficient to ensure that there
25366 are no elaboration problems with any calls to the unit.
25367
25368 @item pragma Elaborate_Body
25369 @findex Elaborate_Body
25370 @cindex pragma Elaborate_Body
25371 This pragma requires that the body of a unit be elaborated immediately
25372 after its spec. Suppose a unit @code{A} has such a pragma,
25373 and unit @code{B} does
25374 a @code{with} of unit @code{A}. Recall that the standard rules require
25375 the spec of unit @code{A}
25376 to be elaborated before the @code{with}'ing unit; given the pragma in
25377 @code{A}, we also know that the body of @code{A}
25378 will be elaborated before @code{B}, so
25379 that calls to @code{A} are safe and do not need a check.
25380 @end table
25381
25382 @noindent
25383 Note that,
25384 unlike pragma @code{Pure} and pragma @code{Preelaborate},
25385 the use of
25386 @code{Elaborate_Body} does not guarantee that the program is
25387 free of elaboration problems, because it may not be possible
25388 to satisfy the requested elaboration order.
25389 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
25390 If a programmer
25391 marks @code{Unit_1} as @code{Elaborate_Body},
25392 and not @code{Unit_2,} then the order of
25393 elaboration will be:
25394
25395 @smallexample
25396 @group
25397 Spec of Unit_2
25398 Spec of Unit_1
25399 Body of Unit_1
25400 Body of Unit_2
25401 @end group
25402 @end smallexample
25403
25404 @noindent
25405 Now that means that the call to @code{Func_1} in @code{Unit_2}
25406 need not be checked,
25407 it must be safe. But the call to @code{Func_2} in
25408 @code{Unit_1} may still fail if
25409 @code{Expression_1} is equal to 1,
25410 and the programmer must still take
25411 responsibility for this not being the case.
25412
25413 If all units carry a pragma @code{Elaborate_Body}, then all problems are
25414 eliminated, except for calls entirely within a body, which are
25415 in any case fully under programmer control. However, using the pragma
25416 everywhere is not always possible.
25417 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
25418 we marked both of them as having pragma @code{Elaborate_Body}, then
25419 clearly there would be no possible elaboration order.
25420
25421 The above pragmas allow a server to guarantee safe use by clients, and
25422 clearly this is the preferable approach. Consequently a good rule
25423 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
25424 and if this is not possible,
25425 mark them as @code{Elaborate_Body} if possible.
25426 As we have seen, there are situations where neither of these
25427 three pragmas can be used.
25428 So we also provide methods for clients to control the
25429 order of elaboration of the servers on which they depend:
25430
25431 @table @asis
25432 @item pragma Elaborate (unit)
25433 @findex Elaborate
25434 @cindex pragma Elaborate
25435 This pragma is placed in the context clause, after a @code{with} clause,
25436 and it requires that the body of the named unit be elaborated before
25437 the unit in which the pragma occurs. The idea is to use this pragma
25438 if the current unit calls at elaboration time, directly or indirectly,
25439 some subprogram in the named unit.
25440
25441 @item pragma Elaborate_All (unit)
25442 @findex Elaborate_All
25443 @cindex pragma Elaborate_All
25444 This is a stronger version of the Elaborate pragma. Consider the
25445 following example:
25446
25447 @smallexample
25448 Unit A @code{with}'s unit B and calls B.Func in elab code
25449 Unit B @code{with}'s unit C, and B.Func calls C.Func
25450 @end smallexample
25451
25452 @noindent
25453 Now if we put a pragma @code{Elaborate (B)}
25454 in unit @code{A}, this ensures that the
25455 body of @code{B} is elaborated before the call, but not the
25456 body of @code{C}, so
25457 the call to @code{C.Func} could still cause @code{Program_Error} to
25458 be raised.
25459
25460 The effect of a pragma @code{Elaborate_All} is stronger, it requires
25461 not only that the body of the named unit be elaborated before the
25462 unit doing the @code{with}, but also the bodies of all units that the
25463 named unit uses, following @code{with} links transitively. For example,
25464 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
25465 then it requires
25466 not only that the body of @code{B} be elaborated before @code{A},
25467 but also the
25468 body of @code{C}, because @code{B} @code{with}'s @code{C}.
25469 @end table
25470
25471 @noindent
25472 We are now in a position to give a usage rule in Ada for avoiding
25473 elaboration problems, at least if dynamic dispatching and access to
25474 subprogram values are not used. We will handle these cases separately
25475 later.
25476
25477 The rule is simple. If a unit has elaboration code that can directly or
25478 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
25479 a generic package in a @code{with}'ed unit,
25480 then if the @code{with}'ed unit does not have
25481 pragma @code{Pure} or @code{Preelaborate}, then the client should have
25482 a pragma @code{Elaborate_All}
25483 for the @code{with}'ed unit. By following this rule a client is
25484 assured that calls can be made without risk of an exception.
25485
25486 For generic subprogram instantiations, the rule can be relaxed to
25487 require only a pragma @code{Elaborate} since elaborating the body
25488 of a subprogram cannot cause any transitive elaboration (we are
25489 not calling the subprogram in this case, just elaborating its
25490 declaration).
25491
25492 If this rule is not followed, then a program may be in one of four
25493 states:
25494
25495 @table @asis
25496 @item No order exists
25497 No order of elaboration exists which follows the rules, taking into
25498 account any @code{Elaborate}, @code{Elaborate_All},
25499 or @code{Elaborate_Body} pragmas. In
25500 this case, an Ada compiler must diagnose the situation at bind
25501 time, and refuse to build an executable program.
25502
25503 @item One or more orders exist, all incorrect
25504 One or more acceptable elaboration orders exist, and all of them
25505 generate an elaboration order problem. In this case, the binder
25506 can build an executable program, but @code{Program_Error} will be raised
25507 when the program is run.
25508
25509 @item Several orders exist, some right, some incorrect
25510 One or more acceptable elaboration orders exists, and some of them
25511 work, and some do not. The programmer has not controlled
25512 the order of elaboration, so the binder may or may not pick one of
25513 the correct orders, and the program may or may not raise an
25514 exception when it is run. This is the worst case, because it means
25515 that the program may fail when moved to another compiler, or even
25516 another version of the same compiler.
25517
25518 @item One or more orders exists, all correct
25519 One ore more acceptable elaboration orders exist, and all of them
25520 work. In this case the program runs successfully. This state of
25521 affairs can be guaranteed by following the rule we gave above, but
25522 may be true even if the rule is not followed.
25523 @end table
25524
25525 @noindent
25526 Note that one additional advantage of following our rules on the use
25527 of @code{Elaborate} and @code{Elaborate_All}
25528 is that the program continues to stay in the ideal (all orders OK) state
25529 even if maintenance
25530 changes some bodies of some units. Conversely, if a program that does
25531 not follow this rule happens to be safe at some point, this state of affairs
25532 may deteriorate silently as a result of maintenance changes.
25533
25534 You may have noticed that the above discussion did not mention
25535 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
25536 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
25537 code in the body makes calls to some other unit, so it is still necessary
25538 to use @code{Elaborate_All} on such units.
25539
25540 @node Controlling Elaboration in GNAT - Internal Calls
25541 @section Controlling Elaboration in GNAT - Internal Calls
25542
25543 @noindent
25544 In the case of internal calls, i.e., calls within a single package, the
25545 programmer has full control over the order of elaboration, and it is up
25546 to the programmer to elaborate declarations in an appropriate order. For
25547 example writing:
25548
25549 @smallexample @c ada
25550 @group
25551 @cartouche
25552 function One return Float;
25553
25554 Q : Float := One;
25555
25556 function One return Float is
25557 begin
25558 return 1.0;
25559 end One;
25560 @end cartouche
25561 @end group
25562 @end smallexample
25563
25564 @noindent
25565 will obviously raise @code{Program_Error} at run time, because function
25566 One will be called before its body is elaborated. In this case GNAT will
25567 generate a warning that the call will raise @code{Program_Error}:
25568
25569 @smallexample
25570 @group
25571 @cartouche
25572 1. procedure y is
25573 2. function One return Float;
25574 3.
25575 4. Q : Float := One;
25576 |
25577 >>> warning: cannot call "One" before body is elaborated
25578 >>> warning: Program_Error will be raised at run time
25579
25580 5.
25581 6. function One return Float is
25582 7. begin
25583 8. return 1.0;
25584 9. end One;
25585 10.
25586 11. begin
25587 12. null;
25588 13. end;
25589 @end cartouche
25590 @end group
25591 @end smallexample
25592
25593 @noindent
25594 Note that in this particular case, it is likely that the call is safe, because
25595 the function @code{One} does not access any global variables.
25596 Nevertheless in Ada, we do not want the validity of the check to depend on
25597 the contents of the body (think about the separate compilation case), so this
25598 is still wrong, as we discussed in the previous sections.
25599
25600 The error is easily corrected by rearranging the declarations so that the
25601 body of @code{One} appears before the declaration containing the call
25602 (note that in Ada 95 and Ada 2005,
25603 declarations can appear in any order, so there is no restriction that
25604 would prevent this reordering, and if we write:
25605
25606 @smallexample @c ada
25607 @group
25608 @cartouche
25609 function One return Float;
25610
25611 function One return Float is
25612 begin
25613 return 1.0;
25614 end One;
25615
25616 Q : Float := One;
25617 @end cartouche
25618 @end group
25619 @end smallexample
25620
25621 @noindent
25622 then all is well, no warning is generated, and no
25623 @code{Program_Error} exception
25624 will be raised.
25625 Things are more complicated when a chain of subprograms is executed:
25626
25627 @smallexample @c ada
25628 @group
25629 @cartouche
25630 function A return Integer;
25631 function B return Integer;
25632 function C return Integer;
25633
25634 function B return Integer is begin return A; end;
25635 function C return Integer is begin return B; end;
25636
25637 X : Integer := C;
25638
25639 function A return Integer is begin return 1; end;
25640 @end cartouche
25641 @end group
25642 @end smallexample
25643
25644 @noindent
25645 Now the call to @code{C}
25646 at elaboration time in the declaration of @code{X} is correct, because
25647 the body of @code{C} is already elaborated,
25648 and the call to @code{B} within the body of
25649 @code{C} is correct, but the call
25650 to @code{A} within the body of @code{B} is incorrect, because the body
25651 of @code{A} has not been elaborated, so @code{Program_Error}
25652 will be raised on the call to @code{A}.
25653 In this case GNAT will generate a
25654 warning that @code{Program_Error} may be
25655 raised at the point of the call. Let's look at the warning:
25656
25657 @smallexample
25658 @group
25659 @cartouche
25660 1. procedure x is
25661 2. function A return Integer;
25662 3. function B return Integer;
25663 4. function C return Integer;
25664 5.
25665 6. function B return Integer is begin return A; end;
25666 |
25667 >>> warning: call to "A" before body is elaborated may
25668 raise Program_Error
25669 >>> warning: "B" called at line 7
25670 >>> warning: "C" called at line 9
25671
25672 7. function C return Integer is begin return B; end;
25673 8.
25674 9. X : Integer := C;
25675 10.
25676 11. function A return Integer is begin return 1; end;
25677 12.
25678 13. begin
25679 14. null;
25680 15. end;
25681 @end cartouche
25682 @end group
25683 @end smallexample
25684
25685 @noindent
25686 Note that the message here says ``may raise'', instead of the direct case,
25687 where the message says ``will be raised''. That's because whether
25688 @code{A} is
25689 actually called depends in general on run-time flow of control.
25690 For example, if the body of @code{B} said
25691
25692 @smallexample @c ada
25693 @group
25694 @cartouche
25695 function B return Integer is
25696 begin
25697 if some-condition-depending-on-input-data then
25698 return A;
25699 else
25700 return 1;
25701 end if;
25702 end B;
25703 @end cartouche
25704 @end group
25705 @end smallexample
25706
25707 @noindent
25708 then we could not know until run time whether the incorrect call to A would
25709 actually occur, so @code{Program_Error} might
25710 or might not be raised. It is possible for a compiler to
25711 do a better job of analyzing bodies, to
25712 determine whether or not @code{Program_Error}
25713 might be raised, but it certainly
25714 couldn't do a perfect job (that would require solving the halting problem
25715 and is provably impossible), and because this is a warning anyway, it does
25716 not seem worth the effort to do the analysis. Cases in which it
25717 would be relevant are rare.
25718
25719 In practice, warnings of either of the forms given
25720 above will usually correspond to
25721 real errors, and should be examined carefully and eliminated.
25722 In the rare case where a warning is bogus, it can be suppressed by any of
25723 the following methods:
25724
25725 @itemize @bullet
25726 @item
25727 Compile with the @option{-gnatws} switch set
25728
25729 @item
25730 Suppress @code{Elaboration_Check} for the called subprogram
25731
25732 @item
25733 Use pragma @code{Warnings_Off} to turn warnings off for the call
25734 @end itemize
25735
25736 @noindent
25737 For the internal elaboration check case,
25738 GNAT by default generates the
25739 necessary run-time checks to ensure
25740 that @code{Program_Error} is raised if any
25741 call fails an elaboration check. Of course this can only happen if a
25742 warning has been issued as described above. The use of pragma
25743 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
25744 some of these checks, meaning that it may be possible (but is not
25745 guaranteed) for a program to be able to call a subprogram whose body
25746 is not yet elaborated, without raising a @code{Program_Error} exception.
25747
25748 @node Controlling Elaboration in GNAT - External Calls
25749 @section Controlling Elaboration in GNAT - External Calls
25750
25751 @noindent
25752 The previous section discussed the case in which the execution of a
25753 particular thread of elaboration code occurred entirely within a
25754 single unit. This is the easy case to handle, because a programmer
25755 has direct and total control over the order of elaboration, and
25756 furthermore, checks need only be generated in cases which are rare
25757 and which the compiler can easily detect.
25758 The situation is more complex when separate compilation is taken into account.
25759 Consider the following:
25760
25761 @smallexample @c ada
25762 @cartouche
25763 @group
25764 package Math is
25765 function Sqrt (Arg : Float) return Float;
25766 end Math;
25767
25768 package body Math is
25769 function Sqrt (Arg : Float) return Float is
25770 begin
25771 @dots{}
25772 end Sqrt;
25773 end Math;
25774 @end group
25775 @group
25776 with Math;
25777 package Stuff is
25778 X : Float := Math.Sqrt (0.5);
25779 end Stuff;
25780
25781 with Stuff;
25782 procedure Main is
25783 begin
25784 @dots{}
25785 end Main;
25786 @end group
25787 @end cartouche
25788 @end smallexample
25789
25790 @noindent
25791 where @code{Main} is the main program. When this program is executed, the
25792 elaboration code must first be executed, and one of the jobs of the
25793 binder is to determine the order in which the units of a program are
25794 to be elaborated. In this case we have four units: the spec and body
25795 of @code{Math},
25796 the spec of @code{Stuff} and the body of @code{Main}).
25797 In what order should the four separate sections of elaboration code
25798 be executed?
25799
25800 There are some restrictions in the order of elaboration that the binder
25801 can choose. In particular, if unit U has a @code{with}
25802 for a package @code{X}, then you
25803 are assured that the spec of @code{X}
25804 is elaborated before U , but you are
25805 not assured that the body of @code{X}
25806 is elaborated before U.
25807 This means that in the above case, the binder is allowed to choose the
25808 order:
25809
25810 @smallexample
25811 spec of Math
25812 spec of Stuff
25813 body of Math
25814 body of Main
25815 @end smallexample
25816
25817 @noindent
25818 but that's not good, because now the call to @code{Math.Sqrt}
25819 that happens during
25820 the elaboration of the @code{Stuff}
25821 spec happens before the body of @code{Math.Sqrt} is
25822 elaborated, and hence causes @code{Program_Error} exception to be raised.
25823 At first glance, one might say that the binder is misbehaving, because
25824 obviously you want to elaborate the body of something you @code{with}
25825 first, but
25826 that is not a general rule that can be followed in all cases. Consider
25827
25828 @smallexample @c ada
25829 @group
25830 @cartouche
25831 package X is @dots{}
25832
25833 package Y is @dots{}
25834
25835 with X;
25836 package body Y is @dots{}
25837
25838 with Y;
25839 package body X is @dots{}
25840 @end cartouche
25841 @end group
25842 @end smallexample
25843
25844 @noindent
25845 This is a common arrangement, and, apart from the order of elaboration
25846 problems that might arise in connection with elaboration code, this works fine.
25847 A rule that says that you must first elaborate the body of anything you
25848 @code{with} cannot work in this case:
25849 the body of @code{X} @code{with}'s @code{Y},
25850 which means you would have to
25851 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
25852 which means
25853 you have to elaborate the body of @code{X} first, but @dots{} and we have a
25854 loop that cannot be broken.
25855
25856 It is true that the binder can in many cases guess an order of elaboration
25857 that is unlikely to cause a @code{Program_Error}
25858 exception to be raised, and it tries to do so (in the
25859 above example of @code{Math/Stuff/Spec}, the GNAT binder will
25860 by default
25861 elaborate the body of @code{Math} right after its spec, so all will be well).
25862
25863 However, a program that blindly relies on the binder to be helpful can
25864 get into trouble, as we discussed in the previous sections, so
25865 GNAT
25866 provides a number of facilities for assisting the programmer in
25867 developing programs that are robust with respect to elaboration order.
25868
25869 @node Default Behavior in GNAT - Ensuring Safety
25870 @section Default Behavior in GNAT - Ensuring Safety
25871
25872 @noindent
25873 The default behavior in GNAT ensures elaboration safety. In its
25874 default mode GNAT implements the
25875 rule we previously described as the right approach. Let's restate it:
25876
25877 @itemize
25878 @item
25879 @emph{If a unit has elaboration code that can directly or indirectly make a
25880 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
25881 package in a @code{with}'ed unit, then if the @code{with}'ed unit
25882 does not have pragma @code{Pure} or
25883 @code{Preelaborate}, then the client should have an
25884 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
25885
25886 @emph{In the case of instantiating a generic subprogram, it is always
25887 sufficient to have only an @code{Elaborate} pragma for the
25888 @code{with}'ed unit.}
25889 @end itemize
25890
25891 @noindent
25892 By following this rule a client is assured that calls and instantiations
25893 can be made without risk of an exception.
25894
25895 In this mode GNAT traces all calls that are potentially made from
25896 elaboration code, and puts in any missing implicit @code{Elaborate}
25897 and @code{Elaborate_All} pragmas.
25898 The advantage of this approach is that no elaboration problems
25899 are possible if the binder can find an elaboration order that is
25900 consistent with these implicit @code{Elaborate} and
25901 @code{Elaborate_All} pragmas. The
25902 disadvantage of this approach is that no such order may exist.
25903
25904 If the binder does not generate any diagnostics, then it means that it has
25905 found an elaboration order that is guaranteed to be safe. However, the binder
25906 may still be relying on implicitly generated @code{Elaborate} and
25907 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
25908 guaranteed.
25909
25910 If it is important to guarantee portability, then the compilations should
25911 use the
25912 @option{-gnatwl}
25913 (warn on elaboration problems) switch. This will cause warning messages
25914 to be generated indicating the missing @code{Elaborate} and
25915 @code{Elaborate_All} pragmas.
25916 Consider the following source program:
25917
25918 @smallexample @c ada
25919 @group
25920 @cartouche
25921 with k;
25922 package j is
25923 m : integer := k.r;
25924 end;
25925 @end cartouche
25926 @end group
25927 @end smallexample
25928
25929 @noindent
25930 where it is clear that there
25931 should be a pragma @code{Elaborate_All}
25932 for unit @code{k}. An implicit pragma will be generated, and it is
25933 likely that the binder will be able to honor it. However, if you want
25934 to port this program to some other Ada compiler than GNAT.
25935 it is safer to include the pragma explicitly in the source. If this
25936 unit is compiled with the
25937 @option{-gnatwl}
25938 switch, then the compiler outputs a warning:
25939
25940 @smallexample
25941 @group
25942 @cartouche
25943 1. with k;
25944 2. package j is
25945 3. m : integer := k.r;
25946 |
25947 >>> warning: call to "r" may raise Program_Error
25948 >>> warning: missing pragma Elaborate_All for "k"
25949
25950 4. end;
25951 @end cartouche
25952 @end group
25953 @end smallexample
25954
25955 @noindent
25956 and these warnings can be used as a guide for supplying manually
25957 the missing pragmas. It is usually a bad idea to use this warning
25958 option during development. That's because it will warn you when
25959 you need to put in a pragma, but cannot warn you when it is time
25960 to take it out. So the use of pragma @code{Elaborate_All} may lead to
25961 unnecessary dependencies and even false circularities.
25962
25963 This default mode is more restrictive than the Ada Reference
25964 Manual, and it is possible to construct programs which will compile
25965 using the dynamic model described there, but will run into a
25966 circularity using the safer static model we have described.
25967
25968 Of course any Ada compiler must be able to operate in a mode
25969 consistent with the requirements of the Ada Reference Manual,
25970 and in particular must have the capability of implementing the
25971 standard dynamic model of elaboration with run-time checks.
25972
25973 In GNAT, this standard mode can be achieved either by the use of
25974 the @option{-gnatE} switch on the compiler (@command{gcc} or
25975 @command{gnatmake}) command, or by the use of the configuration pragma:
25976
25977 @smallexample @c ada
25978 pragma Elaboration_Checks (DYNAMIC);
25979 @end smallexample
25980
25981 @noindent
25982 Either approach will cause the unit affected to be compiled using the
25983 standard dynamic run-time elaboration checks described in the Ada
25984 Reference Manual. The static model is generally preferable, since it
25985 is clearly safer to rely on compile and link time checks rather than
25986 run-time checks. However, in the case of legacy code, it may be
25987 difficult to meet the requirements of the static model. This
25988 issue is further discussed in
25989 @ref{What to Do If the Default Elaboration Behavior Fails}.
25990
25991 Note that the static model provides a strict subset of the allowed
25992 behavior and programs of the Ada Reference Manual, so if you do
25993 adhere to the static model and no circularities exist,
25994 then you are assured that your program will
25995 work using the dynamic model, providing that you remove any
25996 pragma Elaborate statements from the source.
25997
25998 @node Treatment of Pragma Elaborate
25999 @section Treatment of Pragma Elaborate
26000 @cindex Pragma Elaborate
26001
26002 @noindent
26003 The use of @code{pragma Elaborate}
26004 should generally be avoided in Ada 95 and Ada 2005 programs,
26005 since there is no guarantee that transitive calls
26006 will be properly handled. Indeed at one point, this pragma was placed
26007 in Annex J (Obsolescent Features), on the grounds that it is never useful.
26008
26009 Now that's a bit restrictive. In practice, the case in which
26010 @code{pragma Elaborate} is useful is when the caller knows that there
26011 are no transitive calls, or that the called unit contains all necessary
26012 transitive @code{pragma Elaborate} statements, and legacy code often
26013 contains such uses.
26014
26015 Strictly speaking the static mode in GNAT should ignore such pragmas,
26016 since there is no assurance at compile time that the necessary safety
26017 conditions are met. In practice, this would cause GNAT to be incompatible
26018 with correctly written Ada 83 code that had all necessary
26019 @code{pragma Elaborate} statements in place. Consequently, we made the
26020 decision that GNAT in its default mode will believe that if it encounters
26021 a @code{pragma Elaborate} then the programmer knows what they are doing,
26022 and it will trust that no elaboration errors can occur.
26023
26024 The result of this decision is two-fold. First to be safe using the
26025 static mode, you should remove all @code{pragma Elaborate} statements.
26026 Second, when fixing circularities in existing code, you can selectively
26027 use @code{pragma Elaborate} statements to convince the static mode of
26028 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
26029 statement.
26030
26031 When using the static mode with @option{-gnatwl}, any use of
26032 @code{pragma Elaborate} will generate a warning about possible
26033 problems.
26034
26035 @node Elaboration Issues for Library Tasks
26036 @section Elaboration Issues for Library Tasks
26037 @cindex Library tasks, elaboration issues
26038 @cindex Elaboration of library tasks
26039
26040 @noindent
26041 In this section we examine special elaboration issues that arise for
26042 programs that declare library level tasks.
26043
26044 Generally the model of execution of an Ada program is that all units are
26045 elaborated, and then execution of the program starts. However, the
26046 declaration of library tasks definitely does not fit this model. The
26047 reason for this is that library tasks start as soon as they are declared
26048 (more precisely, as soon as the statement part of the enclosing package
26049 body is reached), that is to say before elaboration
26050 of the program is complete. This means that if such a task calls a
26051 subprogram, or an entry in another task, the callee may or may not be
26052 elaborated yet, and in the standard
26053 Reference Manual model of dynamic elaboration checks, you can even
26054 get timing dependent Program_Error exceptions, since there can be
26055 a race between the elaboration code and the task code.
26056
26057 The static model of elaboration in GNAT seeks to avoid all such
26058 dynamic behavior, by being conservative, and the conservative
26059 approach in this particular case is to assume that all the code
26060 in a task body is potentially executed at elaboration time if
26061 a task is declared at the library level.
26062
26063 This can definitely result in unexpected circularities. Consider
26064 the following example
26065
26066 @smallexample @c ada
26067 package Decls is
26068 task Lib_Task is
26069 entry Start;
26070 end Lib_Task;
26071
26072 type My_Int is new Integer;
26073
26074 function Ident (M : My_Int) return My_Int;
26075 end Decls;
26076
26077 with Utils;
26078 package body Decls is
26079 task body Lib_Task is
26080 begin
26081 accept Start;
26082 Utils.Put_Val (2);
26083 end Lib_Task;
26084
26085 function Ident (M : My_Int) return My_Int is
26086 begin
26087 return M;
26088 end Ident;
26089 end Decls;
26090
26091 with Decls;
26092 package Utils is
26093 procedure Put_Val (Arg : Decls.My_Int);
26094 end Utils;
26095
26096 with Text_IO;
26097 package body Utils is
26098 procedure Put_Val (Arg : Decls.My_Int) is
26099 begin
26100 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
26101 end Put_Val;
26102 end Utils;
26103
26104 with Decls;
26105 procedure Main is
26106 begin
26107 Decls.Lib_Task.Start;
26108 end;
26109 @end smallexample
26110
26111 @noindent
26112 If the above example is compiled in the default static elaboration
26113 mode, then a circularity occurs. The circularity comes from the call
26114 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
26115 this call occurs in elaboration code, we need an implicit pragma
26116 @code{Elaborate_All} for @code{Utils}. This means that not only must
26117 the spec and body of @code{Utils} be elaborated before the body
26118 of @code{Decls}, but also the spec and body of any unit that is
26119 @code{with'ed} by the body of @code{Utils} must also be elaborated before
26120 the body of @code{Decls}. This is the transitive implication of
26121 pragma @code{Elaborate_All} and it makes sense, because in general
26122 the body of @code{Put_Val} might have a call to something in a
26123 @code{with'ed} unit.
26124
26125 In this case, the body of Utils (actually its spec) @code{with's}
26126 @code{Decls}. Unfortunately this means that the body of @code{Decls}
26127 must be elaborated before itself, in case there is a call from the
26128 body of @code{Utils}.
26129
26130 Here is the exact chain of events we are worrying about:
26131
26132 @enumerate
26133 @item
26134 In the body of @code{Decls} a call is made from within the body of a library
26135 task to a subprogram in the package @code{Utils}. Since this call may
26136 occur at elaboration time (given that the task is activated at elaboration
26137 time), we have to assume the worst, i.e., that the
26138 call does happen at elaboration time.
26139
26140 @item
26141 This means that the body and spec of @code{Util} must be elaborated before
26142 the body of @code{Decls} so that this call does not cause an access before
26143 elaboration.
26144
26145 @item
26146 Within the body of @code{Util}, specifically within the body of
26147 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
26148 by this package.
26149
26150 @item
26151 One such @code{with}'ed package is package @code{Decls}, so there
26152 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
26153 In fact there is such a call in this example, but we would have to
26154 assume that there was such a call even if it were not there, since
26155 we are not supposed to write the body of @code{Decls} knowing what
26156 is in the body of @code{Utils}; certainly in the case of the
26157 static elaboration model, the compiler does not know what is in
26158 other bodies and must assume the worst.
26159
26160 @item
26161 This means that the spec and body of @code{Decls} must also be
26162 elaborated before we elaborate the unit containing the call, but
26163 that unit is @code{Decls}! This means that the body of @code{Decls}
26164 must be elaborated before itself, and that's a circularity.
26165 @end enumerate
26166
26167 @noindent
26168 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
26169 the body of @code{Decls} you will get a true Ada Reference Manual
26170 circularity that makes the program illegal.
26171
26172 In practice, we have found that problems with the static model of
26173 elaboration in existing code often arise from library tasks, so
26174 we must address this particular situation.
26175
26176 Note that if we compile and run the program above, using the dynamic model of
26177 elaboration (that is to say use the @option{-gnatE} switch),
26178 then it compiles, binds,
26179 links, and runs, printing the expected result of 2. Therefore in some sense
26180 the circularity here is only apparent, and we need to capture
26181 the properties of this program that distinguish it from other library-level
26182 tasks that have real elaboration problems.
26183
26184 We have four possible answers to this question:
26185
26186 @itemize @bullet
26187
26188 @item
26189 Use the dynamic model of elaboration.
26190
26191 If we use the @option{-gnatE} switch, then as noted above, the program works.
26192 Why is this? If we examine the task body, it is apparent that the task cannot
26193 proceed past the
26194 @code{accept} statement until after elaboration has been completed, because
26195 the corresponding entry call comes from the main program, not earlier.
26196 This is why the dynamic model works here. But that's really giving
26197 up on a precise analysis, and we prefer to take this approach only if we cannot
26198 solve the
26199 problem in any other manner. So let us examine two ways to reorganize
26200 the program to avoid the potential elaboration problem.
26201
26202 @item
26203 Split library tasks into separate packages.
26204
26205 Write separate packages, so that library tasks are isolated from
26206 other declarations as much as possible. Let us look at a variation on
26207 the above program.
26208
26209 @smallexample @c ada
26210 package Decls1 is
26211 task Lib_Task is
26212 entry Start;
26213 end Lib_Task;
26214 end Decls1;
26215
26216 with Utils;
26217 package body Decls1 is
26218 task body Lib_Task is
26219 begin
26220 accept Start;
26221 Utils.Put_Val (2);
26222 end Lib_Task;
26223 end Decls1;
26224
26225 package Decls2 is
26226 type My_Int is new Integer;
26227 function Ident (M : My_Int) return My_Int;
26228 end Decls2;
26229
26230 with Utils;
26231 package body Decls2 is
26232 function Ident (M : My_Int) return My_Int is
26233 begin
26234 return M;
26235 end Ident;
26236 end Decls2;
26237
26238 with Decls2;
26239 package Utils is
26240 procedure Put_Val (Arg : Decls2.My_Int);
26241 end Utils;
26242
26243 with Text_IO;
26244 package body Utils is
26245 procedure Put_Val (Arg : Decls2.My_Int) is
26246 begin
26247 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
26248 end Put_Val;
26249 end Utils;
26250
26251 with Decls1;
26252 procedure Main is
26253 begin
26254 Decls1.Lib_Task.Start;
26255 end;
26256 @end smallexample
26257
26258 @noindent
26259 All we have done is to split @code{Decls} into two packages, one
26260 containing the library task, and one containing everything else. Now
26261 there is no cycle, and the program compiles, binds, links and executes
26262 using the default static model of elaboration.
26263
26264 @item
26265 Declare separate task types.
26266
26267 A significant part of the problem arises because of the use of the
26268 single task declaration form. This means that the elaboration of
26269 the task type, and the elaboration of the task itself (i.e.@: the
26270 creation of the task) happen at the same time. A good rule
26271 of style in Ada is to always create explicit task types. By
26272 following the additional step of placing task objects in separate
26273 packages from the task type declaration, many elaboration problems
26274 are avoided. Here is another modified example of the example program:
26275
26276 @smallexample @c ada
26277 package Decls is
26278 task type Lib_Task_Type is
26279 entry Start;
26280 end Lib_Task_Type;
26281
26282 type My_Int is new Integer;
26283
26284 function Ident (M : My_Int) return My_Int;
26285 end Decls;
26286
26287 with Utils;
26288 package body Decls is
26289 task body Lib_Task_Type is
26290 begin
26291 accept Start;
26292 Utils.Put_Val (2);
26293 end Lib_Task_Type;
26294
26295 function Ident (M : My_Int) return My_Int is
26296 begin
26297 return M;
26298 end Ident;
26299 end Decls;
26300
26301 with Decls;
26302 package Utils is
26303 procedure Put_Val (Arg : Decls.My_Int);
26304 end Utils;
26305
26306 with Text_IO;
26307 package body Utils is
26308 procedure Put_Val (Arg : Decls.My_Int) is
26309 begin
26310 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
26311 end Put_Val;
26312 end Utils;
26313
26314 with Decls;
26315 package Declst is
26316 Lib_Task : Decls.Lib_Task_Type;
26317 end Declst;
26318
26319 with Declst;
26320 procedure Main is
26321 begin
26322 Declst.Lib_Task.Start;
26323 end;
26324 @end smallexample
26325
26326 @noindent
26327 What we have done here is to replace the @code{task} declaration in
26328 package @code{Decls} with a @code{task type} declaration. Then we
26329 introduce a separate package @code{Declst} to contain the actual
26330 task object. This separates the elaboration issues for
26331 the @code{task type}
26332 declaration, which causes no trouble, from the elaboration issues
26333 of the task object, which is also unproblematic, since it is now independent
26334 of the elaboration of @code{Utils}.
26335 This separation of concerns also corresponds to
26336 a generally sound engineering principle of separating declarations
26337 from instances. This version of the program also compiles, binds, links,
26338 and executes, generating the expected output.
26339
26340 @item
26341 Use No_Entry_Calls_In_Elaboration_Code restriction.
26342 @cindex No_Entry_Calls_In_Elaboration_Code
26343
26344 The previous two approaches described how a program can be restructured
26345 to avoid the special problems caused by library task bodies. in practice,
26346 however, such restructuring may be difficult to apply to existing legacy code,
26347 so we must consider solutions that do not require massive rewriting.
26348
26349 Let us consider more carefully why our original sample program works
26350 under the dynamic model of elaboration. The reason is that the code
26351 in the task body blocks immediately on the @code{accept}
26352 statement. Now of course there is nothing to prohibit elaboration
26353 code from making entry calls (for example from another library level task),
26354 so we cannot tell in isolation that
26355 the task will not execute the accept statement during elaboration.
26356
26357 However, in practice it is very unusual to see elaboration code
26358 make any entry calls, and the pattern of tasks starting
26359 at elaboration time and then immediately blocking on @code{accept} or
26360 @code{select} statements is very common. What this means is that
26361 the compiler is being too pessimistic when it analyzes the
26362 whole package body as though it might be executed at elaboration
26363 time.
26364
26365 If we know that the elaboration code contains no entry calls, (a very safe
26366 assumption most of the time, that could almost be made the default
26367 behavior), then we can compile all units of the program under control
26368 of the following configuration pragma:
26369
26370 @smallexample
26371 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
26372 @end smallexample
26373
26374 @noindent
26375 This pragma can be placed in the @file{gnat.adc} file in the usual
26376 manner. If we take our original unmodified program and compile it
26377 in the presence of a @file{gnat.adc} containing the above pragma,
26378 then once again, we can compile, bind, link, and execute, obtaining
26379 the expected result. In the presence of this pragma, the compiler does
26380 not trace calls in a task body, that appear after the first @code{accept}
26381 or @code{select} statement, and therefore does not report a potential
26382 circularity in the original program.
26383
26384 The compiler will check to the extent it can that the above
26385 restriction is not violated, but it is not always possible to do a
26386 complete check at compile time, so it is important to use this
26387 pragma only if the stated restriction is in fact met, that is to say
26388 no task receives an entry call before elaboration of all units is completed.
26389
26390 @end itemize
26391
26392 @node Mixing Elaboration Models
26393 @section Mixing Elaboration Models
26394 @noindent
26395 So far, we have assumed that the entire program is either compiled
26396 using the dynamic model or static model, ensuring consistency. It
26397 is possible to mix the two models, but rules have to be followed
26398 if this mixing is done to ensure that elaboration checks are not
26399 omitted.
26400
26401 The basic rule is that @emph{a unit compiled with the static model cannot
26402 be @code{with'ed} by a unit compiled with the dynamic model}. The
26403 reason for this is that in the static model, a unit assumes that
26404 its clients guarantee to use (the equivalent of) pragma
26405 @code{Elaborate_All} so that no elaboration checks are required
26406 in inner subprograms, and this assumption is violated if the
26407 client is compiled with dynamic checks.
26408
26409 The precise rule is as follows. A unit that is compiled with dynamic
26410 checks can only @code{with} a unit that meets at least one of the
26411 following criteria:
26412
26413 @itemize @bullet
26414
26415 @item
26416 The @code{with'ed} unit is itself compiled with dynamic elaboration
26417 checks (that is with the @option{-gnatE} switch.
26418
26419 @item
26420 The @code{with'ed} unit is an internal GNAT implementation unit from
26421 the System, Interfaces, Ada, or GNAT hierarchies.
26422
26423 @item
26424 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
26425
26426 @item
26427 The @code{with'ing} unit (that is the client) has an explicit pragma
26428 @code{Elaborate_All} for the @code{with'ed} unit.
26429
26430 @end itemize
26431
26432 @noindent
26433 If this rule is violated, that is if a unit with dynamic elaboration
26434 checks @code{with's} a unit that does not meet one of the above four
26435 criteria, then the binder (@code{gnatbind}) will issue a warning
26436 similar to that in the following example:
26437
26438 @smallexample
26439 warning: "x.ads" has dynamic elaboration checks and with's
26440 warning: "y.ads" which has static elaboration checks
26441 @end smallexample
26442
26443 @noindent
26444 These warnings indicate that the rule has been violated, and that as a result
26445 elaboration checks may be missed in the resulting executable file.
26446 This warning may be suppressed using the @option{-ws} binder switch
26447 in the usual manner.
26448
26449 One useful application of this mixing rule is in the case of a subsystem
26450 which does not itself @code{with} units from the remainder of the
26451 application. In this case, the entire subsystem can be compiled with
26452 dynamic checks to resolve a circularity in the subsystem, while
26453 allowing the main application that uses this subsystem to be compiled
26454 using the more reliable default static model.
26455
26456 @node What to Do If the Default Elaboration Behavior Fails
26457 @section What to Do If the Default Elaboration Behavior Fails
26458
26459 @noindent
26460 If the binder cannot find an acceptable order, it outputs detailed
26461 diagnostics. For example:
26462 @smallexample
26463 @group
26464 @iftex
26465 @leftskip=0cm
26466 @end iftex
26467 error: elaboration circularity detected
26468 info: "proc (body)" must be elaborated before "pack (body)"
26469 info: reason: Elaborate_All probably needed in unit "pack (body)"
26470 info: recompile "pack (body)" with -gnatwl
26471 info: for full details
26472 info: "proc (body)"
26473 info: is needed by its spec:
26474 info: "proc (spec)"
26475 info: which is withed by:
26476 info: "pack (body)"
26477 info: "pack (body)" must be elaborated before "proc (body)"
26478 info: reason: pragma Elaborate in unit "proc (body)"
26479 @end group
26480
26481 @end smallexample
26482
26483 @noindent
26484 In this case we have a cycle that the binder cannot break. On the one
26485 hand, there is an explicit pragma Elaborate in @code{proc} for
26486 @code{pack}. This means that the body of @code{pack} must be elaborated
26487 before the body of @code{proc}. On the other hand, there is elaboration
26488 code in @code{pack} that calls a subprogram in @code{proc}. This means
26489 that for maximum safety, there should really be a pragma
26490 Elaborate_All in @code{pack} for @code{proc} which would require that
26491 the body of @code{proc} be elaborated before the body of
26492 @code{pack}. Clearly both requirements cannot be satisfied.
26493 Faced with a circularity of this kind, you have three different options.
26494
26495 @table @asis
26496 @item Fix the program
26497 The most desirable option from the point of view of long-term maintenance
26498 is to rearrange the program so that the elaboration problems are avoided.
26499 One useful technique is to place the elaboration code into separate
26500 child packages. Another is to move some of the initialization code to
26501 explicitly called subprograms, where the program controls the order
26502 of initialization explicitly. Although this is the most desirable option,
26503 it may be impractical and involve too much modification, especially in
26504 the case of complex legacy code.
26505
26506 @item Perform dynamic checks
26507 If the compilations are done using the
26508 @option{-gnatE}
26509 (dynamic elaboration check) switch, then GNAT behaves in a quite different
26510 manner. Dynamic checks are generated for all calls that could possibly result
26511 in raising an exception. With this switch, the compiler does not generate
26512 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
26513 exactly as specified in the @cite{Ada Reference Manual}.
26514 The binder will generate
26515 an executable program that may or may not raise @code{Program_Error}, and then
26516 it is the programmer's job to ensure that it does not raise an exception. Note
26517 that it is important to compile all units with the switch, it cannot be used
26518 selectively.
26519
26520 @item Suppress checks
26521 The drawback of dynamic checks is that they generate a
26522 significant overhead at run time, both in space and time. If you
26523 are absolutely sure that your program cannot raise any elaboration
26524 exceptions, and you still want to use the dynamic elaboration model,
26525 then you can use the configuration pragma
26526 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
26527 example this pragma could be placed in the @file{gnat.adc} file.
26528
26529 @item Suppress checks selectively
26530 When you know that certain calls or instantiations in elaboration code cannot
26531 possibly lead to an elaboration error, and the binder nevertheless complains
26532 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
26533 elaboration circularities, it is possible to remove those warnings locally and
26534 obtain a program that will bind. Clearly this can be unsafe, and it is the
26535 responsibility of the programmer to make sure that the resulting program has no
26536 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
26537 used with different granularity to suppress warnings and break elaboration
26538 circularities:
26539
26540 @itemize @bullet
26541 @item
26542 Place the pragma that names the called subprogram in the declarative part
26543 that contains the call.
26544
26545 @item
26546 Place the pragma in the declarative part, without naming an entity. This
26547 disables warnings on all calls in the corresponding declarative region.
26548
26549 @item
26550 Place the pragma in the package spec that declares the called subprogram,
26551 and name the subprogram. This disables warnings on all elaboration calls to
26552 that subprogram.
26553
26554 @item
26555 Place the pragma in the package spec that declares the called subprogram,
26556 without naming any entity. This disables warnings on all elaboration calls to
26557 all subprograms declared in this spec.
26558
26559 @item Use Pragma Elaborate
26560 As previously described in section @xref{Treatment of Pragma Elaborate},
26561 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
26562 that no elaboration checks are required on calls to the designated unit.
26563 There may be cases in which the caller knows that no transitive calls
26564 can occur, so that a @code{pragma Elaborate} will be sufficient in a
26565 case where @code{pragma Elaborate_All} would cause a circularity.
26566 @end itemize
26567
26568 @noindent
26569 These five cases are listed in order of decreasing safety, and therefore
26570 require increasing programmer care in their application. Consider the
26571 following program:
26572
26573 @smallexample @c adanocomment
26574 package Pack1 is
26575 function F1 return Integer;
26576 X1 : Integer;
26577 end Pack1;
26578
26579 package Pack2 is
26580 function F2 return Integer;
26581 function Pure (x : integer) return integer;
26582 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
26583 -- pragma Suppress (Elaboration_Check); -- (4)
26584 end Pack2;
26585
26586 with Pack2;
26587 package body Pack1 is
26588 function F1 return Integer is
26589 begin
26590 return 100;
26591 end F1;
26592 Val : integer := Pack2.Pure (11); -- Elab. call (1)
26593 begin
26594 declare
26595 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
26596 -- pragma Suppress(Elaboration_Check); -- (2)
26597 begin
26598 X1 := Pack2.F2 + 1; -- Elab. call (2)
26599 end;
26600 end Pack1;
26601
26602 with Pack1;
26603 package body Pack2 is
26604 function F2 return Integer is
26605 begin
26606 return Pack1.F1;
26607 end F2;
26608 function Pure (x : integer) return integer is
26609 begin
26610 return x ** 3 - 3 * x;
26611 end;
26612 end Pack2;
26613
26614 with Pack1, Ada.Text_IO;
26615 procedure Proc3 is
26616 begin
26617 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
26618 end Proc3;
26619 @end smallexample
26620 In the absence of any pragmas, an attempt to bind this program produces
26621 the following diagnostics:
26622 @smallexample
26623 @group
26624 @iftex
26625 @leftskip=.5cm
26626 @end iftex
26627 error: elaboration circularity detected
26628 info: "pack1 (body)" must be elaborated before "pack1 (body)"
26629 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
26630 info: recompile "pack1 (body)" with -gnatwl for full details
26631 info: "pack1 (body)"
26632 info: must be elaborated along with its spec:
26633 info: "pack1 (spec)"
26634 info: which is withed by:
26635 info: "pack2 (body)"
26636 info: which must be elaborated along with its spec:
26637 info: "pack2 (spec)"
26638 info: which is withed by:
26639 info: "pack1 (body)"
26640 @end group
26641 @end smallexample
26642 The sources of the circularity are the two calls to @code{Pack2.Pure} and
26643 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
26644 F2 is safe, even though F2 calls F1, because the call appears after the
26645 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
26646 remove the warning on the call. It is also possible to use pragma (2)
26647 because there are no other potentially unsafe calls in the block.
26648
26649 @noindent
26650 The call to @code{Pure} is safe because this function does not depend on the
26651 state of @code{Pack2}. Therefore any call to this function is safe, and it
26652 is correct to place pragma (3) in the corresponding package spec.
26653
26654 @noindent
26655 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
26656 warnings on all calls to functions declared therein. Note that this is not
26657 necessarily safe, and requires more detailed examination of the subprogram
26658 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
26659 be already elaborated.
26660 @end table
26661
26662 @noindent
26663 It is hard to generalize on which of these four approaches should be
26664 taken. Obviously if it is possible to fix the program so that the default
26665 treatment works, this is preferable, but this may not always be practical.
26666 It is certainly simple enough to use
26667 @option{-gnatE}
26668 but the danger in this case is that, even if the GNAT binder
26669 finds a correct elaboration order, it may not always do so,
26670 and certainly a binder from another Ada compiler might not. A
26671 combination of testing and analysis (for which the warnings generated
26672 with the
26673 @option{-gnatwl}
26674 switch can be useful) must be used to ensure that the program is free
26675 of errors. One switch that is useful in this testing is the
26676 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
26677 switch for
26678 @code{gnatbind}.
26679 Normally the binder tries to find an order that has the best chance
26680 of avoiding elaboration problems. However, if this switch is used, the binder
26681 plays a devil's advocate role, and tries to choose the order that
26682 has the best chance of failing. If your program works even with this
26683 switch, then it has a better chance of being error free, but this is still
26684 not a guarantee.
26685
26686 For an example of this approach in action, consider the C-tests (executable
26687 tests) from the ACVC suite. If these are compiled and run with the default
26688 treatment, then all but one of them succeed without generating any error
26689 diagnostics from the binder. However, there is one test that fails, and
26690 this is not surprising, because the whole point of this test is to ensure
26691 that the compiler can handle cases where it is impossible to determine
26692 a correct order statically, and it checks that an exception is indeed
26693 raised at run time.
26694
26695 This one test must be compiled and run using the
26696 @option{-gnatE}
26697 switch, and then it passes. Alternatively, the entire suite can
26698 be run using this switch. It is never wrong to run with the dynamic
26699 elaboration switch if your code is correct, and we assume that the
26700 C-tests are indeed correct (it is less efficient, but efficiency is
26701 not a factor in running the ACVC tests.)
26702
26703 @node Elaboration for Dispatching Calls
26704 @section Elaboration for Dispatching Calls
26705 @cindex Dispatching calls
26706
26707 @noindent
26708 In rare cases, the static elaboration model fails to prevent
26709 dispatching calls to not-yet-elaborated subprograms. In such cases, we
26710 fall back to run-time checks; premature calls to any primitive
26711 operation of a tagged type before the body of the operation has been
26712 elaborated will raise @code{Program_Error}.
26713
26714 Access-to-subprogram types, however, are handled conservatively, and
26715 do not require run-time checks. This was not true in earlier versions
26716 of the compiler; you can use the @option{-gnatd.U} debug switch to
26717 revert to the old behavior if the new conservative behavior causes
26718 elaboration cycles.
26719
26720 @node Summary of Procedures for Elaboration Control
26721 @section Summary of Procedures for Elaboration Control
26722 @cindex Elaboration control
26723
26724 @noindent
26725 First, compile your program with the default options, using none of
26726 the special elaboration control switches. If the binder successfully
26727 binds your program, then you can be confident that, apart from issues
26728 raised by the use of access-to-subprogram types and dynamic dispatching,
26729 the program is free of elaboration errors. If it is important that the
26730 program be portable, then use the
26731 @option{-gnatwl}
26732 switch to generate warnings about missing @code{Elaborate} or
26733 @code{Elaborate_All} pragmas, and supply the missing pragmas.
26734
26735 If the program fails to bind using the default static elaboration
26736 handling, then you can fix the program to eliminate the binder
26737 message, or recompile the entire program with the
26738 @option{-gnatE} switch to generate dynamic elaboration checks,
26739 and, if you are sure there really are no elaboration problems,
26740 use a global pragma @code{Suppress (Elaboration_Check)}.
26741
26742 @node Other Elaboration Order Considerations
26743 @section Other Elaboration Order Considerations
26744 @noindent
26745 This section has been entirely concerned with the issue of finding a valid
26746 elaboration order, as defined by the Ada Reference Manual. In a case
26747 where several elaboration orders are valid, the task is to find one
26748 of the possible valid elaboration orders (and the static model in GNAT
26749 will ensure that this is achieved).
26750
26751 The purpose of the elaboration rules in the Ada Reference Manual is to
26752 make sure that no entity is accessed before it has been elaborated. For
26753 a subprogram, this means that the spec and body must have been elaborated
26754 before the subprogram is called. For an object, this means that the object
26755 must have been elaborated before its value is read or written. A violation
26756 of either of these two requirements is an access before elaboration order,
26757 and this section has been all about avoiding such errors.
26758
26759 In the case where more than one order of elaboration is possible, in the
26760 sense that access before elaboration errors are avoided, then any one of
26761 the orders is ``correct'' in the sense that it meets the requirements of
26762 the Ada Reference Manual, and no such error occurs.
26763
26764 However, it may be the case for a given program, that there are
26765 constraints on the order of elaboration that come not from consideration
26766 of avoiding elaboration errors, but rather from extra-lingual logic
26767 requirements. Consider this example:
26768
26769 @smallexample @c ada
26770 with Init_Constants;
26771 package Constants is
26772 X : Integer := 0;
26773 Y : Integer := 0;
26774 end Constants;
26775
26776 package Init_Constants is
26777 procedure P; -- require a body
26778 end Init_Constants;
26779
26780 with Constants;
26781 package body Init_Constants is
26782 procedure P is begin null; end;
26783 begin
26784 Constants.X := 3;
26785 Constants.Y := 4;
26786 end Init_Constants;
26787
26788 with Constants;
26789 package Calc is
26790 Z : Integer := Constants.X + Constants.Y;
26791 end Calc;
26792
26793 with Calc;
26794 with Text_IO; use Text_IO;
26795 procedure Main is
26796 begin
26797 Put_Line (Calc.Z'Img);
26798 end Main;
26799 @end smallexample
26800
26801 @noindent
26802 In this example, there is more than one valid order of elaboration. For
26803 example both the following are correct orders:
26804
26805 @smallexample
26806 Init_Constants spec
26807 Constants spec
26808 Calc spec
26809 Init_Constants body
26810 Main body
26811
26812 and
26813
26814 Init_Constants spec
26815 Init_Constants body
26816 Constants spec
26817 Calc spec
26818 Main body
26819 @end smallexample
26820
26821 @noindent
26822 There is no language rule to prefer one or the other, both are correct
26823 from an order of elaboration point of view. But the programmatic effects
26824 of the two orders are very different. In the first, the elaboration routine
26825 of @code{Calc} initializes @code{Z} to zero, and then the main program
26826 runs with this value of zero. But in the second order, the elaboration
26827 routine of @code{Calc} runs after the body of Init_Constants has set
26828 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
26829 runs.
26830
26831 One could perhaps by applying pretty clever non-artificial intelligence
26832 to the situation guess that it is more likely that the second order of
26833 elaboration is the one desired, but there is no formal linguistic reason
26834 to prefer one over the other. In fact in this particular case, GNAT will
26835 prefer the second order, because of the rule that bodies are elaborated
26836 as soon as possible, but it's just luck that this is what was wanted
26837 (if indeed the second order was preferred).
26838
26839 If the program cares about the order of elaboration routines in a case like
26840 this, it is important to specify the order required. In this particular
26841 case, that could have been achieved by adding to the spec of Calc:
26842
26843 @smallexample @c ada
26844 pragma Elaborate_All (Constants);
26845 @end smallexample
26846
26847 @noindent
26848 which requires that the body (if any) and spec of @code{Constants},
26849 as well as the body and spec of any unit @code{with}'ed by
26850 @code{Constants} be elaborated before @code{Calc} is elaborated.
26851
26852 Clearly no automatic method can always guess which alternative you require,
26853 and if you are working with legacy code that had constraints of this kind
26854 which were not properly specified by adding @code{Elaborate} or
26855 @code{Elaborate_All} pragmas, then indeed it is possible that two different
26856 compilers can choose different orders.
26857
26858 However, GNAT does attempt to diagnose the common situation where there
26859 are uninitialized variables in the visible part of a package spec, and the
26860 corresponding package body has an elaboration block that directly or
26861 indirectly initialized one or more of these variables. This is the situation
26862 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
26863 a warning that suggests this addition if it detects this situation.
26864
26865 The @code{gnatbind}
26866 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
26867 out problems. This switch causes bodies to be elaborated as late as possible
26868 instead of as early as possible. In the example above, it would have forced
26869 the choice of the first elaboration order. If you get different results
26870 when using this switch, and particularly if one set of results is right,
26871 and one is wrong as far as you are concerned, it shows that you have some
26872 missing @code{Elaborate} pragmas. For the example above, we have the
26873 following output:
26874
26875 @smallexample
26876 gnatmake -f -q main
26877 main
26878 7
26879 gnatmake -f -q main -bargs -p
26880 main
26881 0
26882 @end smallexample
26883
26884 @noindent
26885 It is of course quite unlikely that both these results are correct, so
26886 it is up to you in a case like this to investigate the source of the
26887 difference, by looking at the two elaboration orders that are chosen,
26888 and figuring out which is correct, and then adding the necessary
26889 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
26890
26891
26892 @c **********************************
26893 @node Overflow Check Handling in GNAT
26894 @appendix Overflow Check Handling in GNAT
26895 @cindex Overflow checks
26896 @cindex Checks (overflow)
26897 @c **********************************
26898
26899 @menu
26900 * Background::
26901 * Overflow Checking Modes in GNAT::
26902 * Specifying the Desired Mode::
26903 * Default Settings::
26904 * Implementation Notes::
26905 @end menu
26906
26907
26908 @node Background
26909 @section Background
26910
26911 @noindent
26912 Overflow checks are checks that the compiler may make to ensure
26913 that intermediate results are not out of range. For example:
26914
26915 @smallexample @c ada
26916 A : Integer;
26917 ...
26918 A := A + 1;
26919 @end smallexample
26920
26921 @noindent
26922 if @code{A} has the value @code{Integer'Last}, then the addition may cause
26923 overflow since the result is out of range of the type @code{Integer}.
26924 In this case @code{Constraint_Error} will be raised if checks are
26925 enabled.
26926
26927 A trickier situation arises in examples like the following:
26928
26929 @smallexample @c ada
26930 A, C : Integer;
26931 ...
26932 A := (A + 1) + C;
26933 @end smallexample
26934
26935 @noindent
26936 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
26937 Now the final result of the expression on the right hand side is
26938 @code{Integer'Last} which is in range, but the question arises whether the
26939 intermediate addition of @code{(A + 1)} raises an overflow error.
26940
26941 The (perhaps surprising) answer is that the Ada language
26942 definition does not answer this question. Instead it leaves
26943 it up to the implementation to do one of two things if overflow
26944 checks are enabled.
26945
26946 @itemize @bullet
26947 @item
26948 raise an exception (@code{Constraint_Error}), or
26949
26950 @item
26951 yield the correct mathematical result which is then used in
26952 subsequent operations.
26953 @end itemize
26954
26955 @noindent
26956 If the compiler chooses the first approach, then the assignment of this
26957 example will indeed raise @code{Constraint_Error} if overflow checking is
26958 enabled, or result in erroneous execution if overflow checks are suppressed.
26959
26960 But if the compiler
26961 chooses the second approach, then it can perform both additions yielding
26962 the correct mathematical result, which is in range, so no exception
26963 will be raised, and the right result is obtained, regardless of whether
26964 overflow checks are suppressed.
26965
26966 Note that in the first example an
26967 exception will be raised in either case, since if the compiler
26968 gives the correct mathematical result for the addition, it will
26969 be out of range of the target type of the assignment, and thus
26970 fails the range check.
26971
26972 This lack of specified behavior in the handling of overflow for
26973 intermediate results is a source of non-portability, and can thus
26974 be problematic when programs are ported. Most typically this arises
26975 in a situation where the original compiler did not raise an exception,
26976 and then the application is moved to a compiler where the check is
26977 performed on the intermediate result and an unexpected exception is
26978 raised.
26979
26980 Furthermore, when using Ada 2012's preconditions and other
26981 assertion forms, another issue arises. Consider:
26982
26983 @smallexample @c ada
26984 procedure P (A, B : Integer) with
26985 Pre => A + B <= Integer'Last;
26986 @end smallexample
26987
26988 @noindent
26989 One often wants to regard arithmetic in a context like this from
26990 a mathematical point of view. So for example, if the two actual parameters
26991 for a call to @code{P} are both @code{Integer'Last}, then
26992 the precondition should be regarded as False. If we are executing
26993 in a mode with run-time checks enabled for preconditions, then we would
26994 like this precondition to fail, rather than raising an exception
26995 because of the intermediate overflow.
26996
26997 However, the language definition leaves the specification of
26998 whether the above condition fails (raising @code{Assert_Error}) or
26999 causes an intermediate overflow (raising @code{Constraint_Error})
27000 up to the implementation.
27001
27002 The situation is worse in a case such as the following:
27003
27004 @smallexample @c ada
27005 procedure Q (A, B, C : Integer) with
27006 Pre => A + B + C <= Integer'Last;
27007 @end smallexample
27008
27009 @noindent
27010 Consider the call
27011
27012 @smallexample @c ada
27013 Q (A => Integer'Last, B => 1, C => -1);
27014 @end smallexample
27015
27016 @noindent
27017 From a mathematical point of view the precondition
27018 is True, but at run time we may (but are not guaranteed to) get an
27019 exception raised because of the intermediate overflow (and we really
27020 would prefer this precondition to be considered True at run time).
27021
27022 @node Overflow Checking Modes in GNAT
27023 @section Overflow Checking Modes in GNAT
27024
27025 @noindent
27026 To deal with the portability issue, and with the problem of
27027 mathematical versus run-time interpretation of the expressions in
27028 assertions, GNAT provides comprehensive control over the handling
27029 of intermediate overflow. GNAT can operate in three modes, and
27030 furthemore, permits separate selection of operating modes for
27031 the expressions within assertions (here the term ``assertions''
27032 is used in the technical sense, which includes preconditions and so forth)
27033 and for expressions appearing outside assertions.
27034
27035 The three modes are:
27036
27037 @itemize @bullet
27038 @item @i{Use base type for intermediate operations} (@code{STRICT})
27039
27040 In this mode, all intermediate results for predefined arithmetic
27041 operators are computed using the base type, and the result must
27042 be in range of the base type. If this is not the
27043 case then either an exception is raised (if overflow checks are
27044 enabled) or the execution is erroneous (if overflow checks are suppressed).
27045 This is the normal default mode.
27046
27047 @item @i{Most intermediate overflows avoided} (@code{MINIMIZED})
27048
27049 In this mode, the compiler attempts to avoid intermediate overflows by
27050 using a larger integer type, typically @code{Long_Long_Integer},
27051 as the type in which arithmetic is
27052 performed for predefined arithmetic operators. This may be slightly more
27053 expensive at
27054 run time (compared to suppressing intermediate overflow checks), though
27055 the cost is negligible on modern 64-bit machines. For the examples given
27056 earlier, no intermediate overflows would have resulted in exceptions,
27057 since the intermediate results are all in the range of
27058 @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
27059 of GNAT). In addition, if checks are enabled, this reduces the number of
27060 checks that must be made, so this choice may actually result in an
27061 improvement in space and time behavior.
27062
27063 However, there are cases where @code{Long_Long_Integer} is not large
27064 enough, consider the following example:
27065
27066 @smallexample @c ada
27067 procedure R (A, B, C, D : Integer) with
27068 Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
27069 @end smallexample
27070
27071 where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
27072 Now the intermediate results are
27073 out of the range of @code{Long_Long_Integer} even though the final result
27074 is in range and the precondition is True (from a mathematical point
27075 of view). In such a case, operating in this mode, an overflow occurs
27076 for the intermediate computation (which is why this mode
27077 says @i{most} intermediate overflows are avoided). In this case,
27078 an exception is raised if overflow checks are enabled, and the
27079 execution is erroneous if overflow checks are suppressed.
27080
27081 @item @i{All intermediate overflows avoided} (@code{ELIMINATED})
27082
27083 In this mode, the compiler avoids all intermediate overflows
27084 by using arbitrary precision arithmetic as required. In this
27085 mode, the above example with @code{A**2 * B**2} would
27086 not cause intermediate overflow, because the intermediate result
27087 would be evaluated using sufficient precision, and the result
27088 of evaluating the precondition would be True.
27089
27090 This mode has the advantage of avoiding any intermediate
27091 overflows, but at the expense of significant run-time overhead,
27092 including the use of a library (included automatically in this
27093 mode) for multiple-precision arithmetic.
27094
27095 This mode provides cleaner semantics for assertions, since now
27096 the run-time behavior emulates true arithmetic behavior for the
27097 predefined arithmetic operators, meaning that there is never a
27098 conflict between the mathematical view of the assertion, and its
27099 run-time behavior.
27100
27101 Note that in this mode, the behavior is unaffected by whether or
27102 not overflow checks are suppressed, since overflow does not occur.
27103 It is possible for gigantic intermediate expressions to raise
27104 @code{Storage_Error} as a result of attempting to compute the
27105 results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
27106 but overflow is impossible.
27107
27108
27109 @end itemize
27110
27111 @noindent
27112 Note that these modes apply only to the evaluation of predefined
27113 arithmetic, membership, and comparison operators for signed integer
27114 aritmetic.
27115
27116 For fixed-point arithmetic, checks can be suppressed. But if checks
27117 are enabled
27118 then fixed-point values are always checked for overflow against the
27119 base type for intermediate expressions (that is such checks always
27120 operate in the equivalent of @code{STRICT} mode).
27121
27122 For floating-point, on nearly all architectures, @code{Machine_Overflows}
27123 is False, and IEEE infinities are generated, so overflow exceptions
27124 are never raised. If you want to avoid infinities, and check that
27125 final results of expressions are in range, then you can declare a
27126 constrained floating-point type, and range checks will be carried
27127 out in the normal manner (with infinite values always failing all
27128 range checks).
27129
27130
27131 @c -------------------------
27132 @node Specifying the Desired Mode
27133 @section Specifying the Desired Mode
27134
27135 @noindent
27136 The desired mode of for handling intermediate overflow can be specified using
27137 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
27138 The pragma has the form
27139 @cindex pragma @code{Overflow_Mode}
27140
27141 @smallexample @c ada
27142 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
27143 @end smallexample
27144
27145 @noindent
27146 where @code{MODE} is one of
27147
27148 @itemize @bullet
27149 @item @code{STRICT}: intermediate overflows checked (using base type)
27150 @item @code{MINIMIZED}: minimize intermediate overflows
27151 @item @code{ELIMINATED}: eliminate intermediate overflows
27152 @end itemize
27153
27154 @noindent
27155 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
27156 @code{minimized} all have the same effect.
27157
27158 If only the @code{General} parameter is present, then the given @code{MODE}
27159 applies
27160 to expressions both within and outside assertions. If both arguments
27161 are present, then @code{General} applies to expressions outside assertions,
27162 and @code{Assertions} applies to expressions within assertions. For example:
27163
27164 @smallexample @c ada
27165 pragma Overflow_Mode
27166 (General => Minimized, Assertions => Eliminated);
27167 @end smallexample
27168
27169 @noindent
27170 specifies that general expressions outside assertions be evaluated
27171 in ``minimize intermediate overflows'' mode, and expressions within
27172 assertions be evaluated in ``eliminate intermediate overflows'' mode.
27173 This is often a reasonable choice, avoiding excessive overhead
27174 outside assertions, but assuring a high degree of portability
27175 when importing code from another compiler, while incurring
27176 the extra overhead for assertion expressions to ensure that
27177 the behavior at run time matches the expected mathematical
27178 behavior.
27179
27180 The @code{Overflow_Mode} pragma has the same scoping and placement
27181 rules as pragma @code{Suppress}, so it can occur either as a
27182 configuration pragma, specifying a default for the whole
27183 program, or in a declarative scope, where it applies to the
27184 remaining declarations and statements in that scope.
27185
27186 Note that pragma @code{Overflow_Mode} does not affect whether
27187 overflow checks are enabled or suppressed. It only controls the
27188 method used to compute intermediate values. To control whether
27189 overflow checking is enabled or suppressed, use pragma @code{Suppress}
27190 or @code{Unsuppress} in the usual manner
27191
27192 Additionally, a compiler switch @option{-gnato?} or @option{-gnato??}
27193 can be used to control the checking mode default (which can be subsequently
27194 overridden using pragmas).
27195 @cindex @option{-gnato?} (gcc)
27196 @cindex @option{-gnato??} (gcc)
27197
27198 Here `@code{?}' is one of the digits `@code{1}' through `@code{3}':
27199
27200 @itemize @bullet
27201 @item @code{1}:
27202 use base type for intermediate operations (@code{STRICT})
27203 @item @code{2}:
27204 minimize intermediate overflows (@code{MINIMIZED})
27205 @item @code{3}:
27206 eliminate intermediate overflows (@code{ELIMINATED})
27207 @end itemize
27208
27209 @noindent
27210 As with the pragma, if only one digit appears then it applies to all
27211 cases; if two digits are given, then the first applies outside
27212 assertions, and the second within assertions. Thus the equivalent
27213 of the example pragma above would be
27214 @option{^-gnato23^/OVERFLOW_CHECKS=23^}.
27215
27216 If no digits follow the @option{-gnato}, then it is equivalent to
27217 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
27218 causing all intermediate operations to be computed using the base
27219 type (@code{STRICT} mode).
27220
27221 In addition to setting the mode used for computation of intermediate
27222 results, the @code{-gnato} switch also enables overflow checking (which
27223 is suppressed by default). It thus combines the effect of using
27224 a pragma @code{Overflow_Mode} and pragma @code{Unsuppress}.
27225
27226
27227 @c -------------------------
27228 @node Default Settings
27229 @section Default Settings
27230
27231 The default mode for overflow checks is
27232
27233 @smallexample
27234 General => Strict
27235 @end smallexample
27236
27237 @noindent
27238 which causes all computations both inside and outside assertions to use
27239 the base type. In addition overflow checks are suppressed.
27240
27241 This retains compatibility with previous versions of
27242 GNAT which suppressed overflow checks by default and always
27243 used the base type for computation of intermediate results.
27244
27245 The switch @option{-gnato} (with no digits following) is equivalent to
27246 @cindex @option{-gnato} (gcc)
27247
27248 @smallexample
27249 General => Strict
27250 @end smallexample
27251
27252 @noindent
27253 which causes overflow checking of all intermediate overflows
27254 both inside and outside assertions against the base type.
27255 This provides compatibility
27256 with this switch as implemented in previous versions of GNAT.
27257
27258 The pragma @code{Suppress (Overflow_Check)} disables overflow
27259 checking, but it has no effect on the method used for computing
27260 intermediate results.
27261
27262 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
27263 checking, but it has no effect on the method used for computing
27264 intermediate results.
27265
27266 @c -------------------------
27267 @node Implementation Notes
27268 @section Implementation Notes
27269
27270 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
27271 reasonably efficient, and can be generally used. It also helps
27272 to ensure compatibility with code imported from some other
27273 compiler to GNAT.
27274
27275 Setting all intermediate overflows checking (@code{CHECKED} mode)
27276 makes sense if you want to
27277 make sure that your code is compatible with any other possible
27278 Ada implementation. This may be useful in ensuring portability
27279 for code that is to be exported to some other compiler than GNAT.
27280
27281
27282 The Ada standard allows the reassociation of expressions at
27283 the same precedence level if no parentheses are present. For
27284 example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but
27285 the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly
27286 introducing or eliminating an overflow exception. The GNAT
27287 compiler never takes advantage of this freedom, and the
27288 expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}.
27289 If you need the other order, you can write the parentheses
27290 explicitly @w{@code{A+(B+C)}} and GNAT will respect this order.
27291
27292 The use of @code{ELIMINATED} mode will cause the compiler to
27293 automatically include an appropriate arbitrary precision
27294 integer arithmetic package. The compiler will make calls
27295 to this package, though only in cases where it cannot be
27296 sure that @code{Long_Long_Integer} is sufficient to guard against
27297 intermediate overflows. This package does not use dynamic
27298 alllocation, but it does use the secondary stack, so an
27299 appropriate secondary stack package must be present (this
27300 is always true for standard full Ada, but may require
27301 specific steps for restricted run times such as ZFP).
27302
27303 Although @code{ELIMINATED} mode causes expressions to use arbitrary
27304 precision arithmetic, avoiding overflow, the final result
27305 must be in an appropriate range. This is true even if the
27306 final result is of type @code{[Long_[Long_]]Integer'Base}, which
27307 still has the same bounds as its associated constrained
27308 type at run-time.
27309
27310 Currently, the @code{ELIMINATED} mode is only available on target
27311 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
27312 platforms).
27313
27314 @c *******************************
27315 @node Conditional Compilation
27316 @appendix Conditional Compilation
27317 @c *******************************
27318 @cindex Conditional compilation
27319
27320 @noindent
27321 It is often necessary to arrange for a single source program
27322 to serve multiple purposes, where it is compiled in different
27323 ways to achieve these different goals. Some examples of the
27324 need for this feature are
27325
27326 @itemize @bullet
27327 @item Adapting a program to a different hardware environment
27328 @item Adapting a program to a different target architecture
27329 @item Turning debugging features on and off
27330 @item Arranging for a program to compile with different compilers
27331 @end itemize
27332
27333 @noindent
27334 In C, or C++, the typical approach would be to use the preprocessor
27335 that is defined as part of the language. The Ada language does not
27336 contain such a feature. This is not an oversight, but rather a very
27337 deliberate design decision, based on the experience that overuse of
27338 the preprocessing features in C and C++ can result in programs that
27339 are extremely difficult to maintain. For example, if we have ten
27340 switches that can be on or off, this means that there are a thousand
27341 separate programs, any one of which might not even be syntactically
27342 correct, and even if syntactically correct, the resulting program
27343 might not work correctly. Testing all combinations can quickly become
27344 impossible.
27345
27346 Nevertheless, the need to tailor programs certainly exists, and in
27347 this Appendix we will discuss how this can
27348 be achieved using Ada in general, and GNAT in particular.
27349
27350 @menu
27351 * Use of Boolean Constants::
27352 * Debugging - A Special Case::
27353 * Conditionalizing Declarations::
27354 * Use of Alternative Implementations::
27355 * Preprocessing::
27356 @end menu
27357
27358 @node Use of Boolean Constants
27359 @section Use of Boolean Constants
27360
27361 @noindent
27362 In the case where the difference is simply which code
27363 sequence is executed, the cleanest solution is to use Boolean
27364 constants to control which code is executed.
27365
27366 @smallexample @c ada
27367 @group
27368 FP_Initialize_Required : constant Boolean := True;
27369 @dots{}
27370 if FP_Initialize_Required then
27371 @dots{}
27372 end if;
27373 @end group
27374 @end smallexample
27375
27376 @noindent
27377 Not only will the code inside the @code{if} statement not be executed if
27378 the constant Boolean is @code{False}, but it will also be completely
27379 deleted from the program.
27380 However, the code is only deleted after the @code{if} statement
27381 has been checked for syntactic and semantic correctness.
27382 (In contrast, with preprocessors the code is deleted before the
27383 compiler ever gets to see it, so it is not checked until the switch
27384 is turned on.)
27385 @cindex Preprocessors (contrasted with conditional compilation)
27386
27387 Typically the Boolean constants will be in a separate package,
27388 something like:
27389
27390 @smallexample @c ada
27391 @group
27392 package Config is
27393 FP_Initialize_Required : constant Boolean := True;
27394 Reset_Available : constant Boolean := False;
27395 @dots{}
27396 end Config;
27397 @end group
27398 @end smallexample
27399
27400 @noindent
27401 The @code{Config} package exists in multiple forms for the various targets,
27402 with an appropriate script selecting the version of @code{Config} needed.
27403 Then any other unit requiring conditional compilation can do a @code{with}
27404 of @code{Config} to make the constants visible.
27405
27406
27407 @node Debugging - A Special Case
27408 @section Debugging - A Special Case
27409
27410 @noindent
27411 A common use of conditional code is to execute statements (for example
27412 dynamic checks, or output of intermediate results) under control of a
27413 debug switch, so that the debugging behavior can be turned on and off.
27414 This can be done using a Boolean constant to control whether the code
27415 is active:
27416
27417 @smallexample @c ada
27418 @group
27419 if Debugging then
27420 Put_Line ("got to the first stage!");
27421 end if;
27422 @end group
27423 @end smallexample
27424
27425 @noindent
27426 or
27427
27428 @smallexample @c ada
27429 @group
27430 if Debugging and then Temperature > 999.0 then
27431 raise Temperature_Crazy;
27432 end if;
27433 @end group
27434 @end smallexample
27435
27436 @noindent
27437 Since this is a common case, there are special features to deal with
27438 this in a convenient manner. For the case of tests, Ada 2005 has added
27439 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
27440 @cindex pragma @code{Assert}
27441 on the @code{Assert} pragma that has always been available in GNAT, so this
27442 feature may be used with GNAT even if you are not using Ada 2005 features.
27443 The use of pragma @code{Assert} is described in
27444 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
27445 example, the last test could be written:
27446
27447 @smallexample @c ada
27448 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
27449 @end smallexample
27450
27451 @noindent
27452 or simply
27453
27454 @smallexample @c ada
27455 pragma Assert (Temperature <= 999.0);
27456 @end smallexample
27457
27458 @noindent
27459 In both cases, if assertions are active and the temperature is excessive,
27460 the exception @code{Assert_Failure} will be raised, with the given string in
27461 the first case or a string indicating the location of the pragma in the second
27462 case used as the exception message.
27463
27464 You can turn assertions on and off by using the @code{Assertion_Policy}
27465 pragma.
27466 @cindex pragma @code{Assertion_Policy}
27467 This is an Ada 2005 pragma which is implemented in all modes by
27468 GNAT, but only in the latest versions of GNAT which include Ada 2005
27469 capability. Alternatively, you can use the @option{-gnata} switch
27470 @cindex @option{-gnata} switch
27471 to enable assertions from the command line (this is recognized by all versions
27472 of GNAT).
27473
27474 For the example above with the @code{Put_Line}, the GNAT-specific pragma
27475 @code{Debug} can be used:
27476 @cindex pragma @code{Debug}
27477
27478 @smallexample @c ada
27479 pragma Debug (Put_Line ("got to the first stage!"));
27480 @end smallexample
27481
27482 @noindent
27483 If debug pragmas are enabled, the argument, which must be of the form of
27484 a procedure call, is executed (in this case, @code{Put_Line} will be called).
27485 Only one call can be present, but of course a special debugging procedure
27486 containing any code you like can be included in the program and then
27487 called in a pragma @code{Debug} argument as needed.
27488
27489 One advantage of pragma @code{Debug} over the @code{if Debugging then}
27490 construct is that pragma @code{Debug} can appear in declarative contexts,
27491 such as at the very beginning of a procedure, before local declarations have
27492 been elaborated.
27493
27494 Debug pragmas are enabled using either the @option{-gnata} switch that also
27495 controls assertions, or with a separate Debug_Policy pragma.
27496 @cindex pragma @code{Debug_Policy}
27497 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
27498 in Ada 95 and Ada 83 programs as well), and is analogous to
27499 pragma @code{Assertion_Policy} to control assertions.
27500
27501 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
27502 and thus they can appear in @file{gnat.adc} if you are not using a
27503 project file, or in the file designated to contain configuration pragmas
27504 in a project file.
27505 They then apply to all subsequent compilations. In practice the use of
27506 the @option{-gnata} switch is often the most convenient method of controlling
27507 the status of these pragmas.
27508
27509 Note that a pragma is not a statement, so in contexts where a statement
27510 sequence is required, you can't just write a pragma on its own. You have
27511 to add a @code{null} statement.
27512
27513 @smallexample @c ada
27514 @group
27515 if @dots{} then
27516 @dots{} -- some statements
27517 else
27518 pragma Assert (Num_Cases < 10);
27519 null;
27520 end if;
27521 @end group
27522 @end smallexample
27523
27524
27525 @node Conditionalizing Declarations
27526 @section Conditionalizing Declarations
27527
27528 @noindent
27529 In some cases, it may be necessary to conditionalize declarations to meet
27530 different requirements. For example we might want a bit string whose length
27531 is set to meet some hardware message requirement.
27532
27533 In some cases, it may be possible to do this using declare blocks controlled
27534 by conditional constants:
27535
27536 @smallexample @c ada
27537 @group
27538 if Small_Machine then
27539 declare
27540 X : Bit_String (1 .. 10);
27541 begin
27542 @dots{}
27543 end;
27544 else
27545 declare
27546 X : Large_Bit_String (1 .. 1000);
27547 begin
27548 @dots{}
27549 end;
27550 end if;
27551 @end group
27552 @end smallexample
27553
27554 @noindent
27555 Note that in this approach, both declarations are analyzed by the
27556 compiler so this can only be used where both declarations are legal,
27557 even though one of them will not be used.
27558
27559 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
27560 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
27561 that are parameterized by these constants. For example
27562
27563 @smallexample @c ada
27564 @group
27565 for Rec use
27566 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
27567 end record;
27568 @end group
27569 @end smallexample
27570
27571 @noindent
27572 If @code{Bits_Per_Word} is set to 32, this generates either
27573
27574 @smallexample @c ada
27575 @group
27576 for Rec use
27577 Field1 at 0 range 0 .. 32;
27578 end record;
27579 @end group
27580 @end smallexample
27581
27582 @noindent
27583 for the big endian case, or
27584
27585 @smallexample @c ada
27586 @group
27587 for Rec use record
27588 Field1 at 0 range 10 .. 32;
27589 end record;
27590 @end group
27591 @end smallexample
27592
27593 @noindent
27594 for the little endian case. Since a powerful subset of Ada expression
27595 notation is usable for creating static constants, clever use of this
27596 feature can often solve quite difficult problems in conditionalizing
27597 compilation (note incidentally that in Ada 95, the little endian
27598 constant was introduced as @code{System.Default_Bit_Order}, so you do not
27599 need to define this one yourself).
27600
27601
27602 @node Use of Alternative Implementations
27603 @section Use of Alternative Implementations
27604
27605 @noindent
27606 In some cases, none of the approaches described above are adequate. This
27607 can occur for example if the set of declarations required is radically
27608 different for two different configurations.
27609
27610 In this situation, the official Ada way of dealing with conditionalizing
27611 such code is to write separate units for the different cases. As long as
27612 this does not result in excessive duplication of code, this can be done
27613 without creating maintenance problems. The approach is to share common
27614 code as far as possible, and then isolate the code and declarations
27615 that are different. Subunits are often a convenient method for breaking
27616 out a piece of a unit that is to be conditionalized, with separate files
27617 for different versions of the subunit for different targets, where the
27618 build script selects the right one to give to the compiler.
27619 @cindex Subunits (and conditional compilation)
27620
27621 As an example, consider a situation where a new feature in Ada 2005
27622 allows something to be done in a really nice way. But your code must be able
27623 to compile with an Ada 95 compiler. Conceptually you want to say:
27624
27625 @smallexample @c ada
27626 @group
27627 if Ada_2005 then
27628 @dots{} neat Ada 2005 code
27629 else
27630 @dots{} not quite as neat Ada 95 code
27631 end if;
27632 @end group
27633 @end smallexample
27634
27635 @noindent
27636 where @code{Ada_2005} is a Boolean constant.
27637
27638 But this won't work when @code{Ada_2005} is set to @code{False},
27639 since the @code{then} clause will be illegal for an Ada 95 compiler.
27640 (Recall that although such unreachable code would eventually be deleted
27641 by the compiler, it still needs to be legal. If it uses features
27642 introduced in Ada 2005, it will be illegal in Ada 95.)
27643
27644 So instead we write
27645
27646 @smallexample @c ada
27647 procedure Insert is separate;
27648 @end smallexample
27649
27650 @noindent
27651 Then we have two files for the subunit @code{Insert}, with the two sets of
27652 code.
27653 If the package containing this is called @code{File_Queries}, then we might
27654 have two files
27655
27656 @itemize @bullet
27657 @item @file{file_queries-insert-2005.adb}
27658 @item @file{file_queries-insert-95.adb}
27659 @end itemize
27660
27661 @noindent
27662 and the build script renames the appropriate file to
27663
27664 @smallexample
27665 file_queries-insert.adb
27666 @end smallexample
27667
27668 @noindent
27669 and then carries out the compilation.
27670
27671 This can also be done with project files' naming schemes. For example:
27672
27673 @smallexample @c project
27674 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
27675 @end smallexample
27676
27677 @noindent
27678 Note also that with project files it is desirable to use a different extension
27679 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
27680 conflict may arise through another commonly used feature: to declare as part
27681 of the project a set of directories containing all the sources obeying the
27682 default naming scheme.
27683
27684 The use of alternative units is certainly feasible in all situations,
27685 and for example the Ada part of the GNAT run-time is conditionalized
27686 based on the target architecture using this approach. As a specific example,
27687 consider the implementation of the AST feature in VMS. There is one
27688 spec:
27689
27690 @smallexample
27691 s-asthan.ads
27692 @end smallexample
27693
27694 @noindent
27695 which is the same for all architectures, and three bodies:
27696
27697 @table @file
27698 @item s-asthan.adb
27699 used for all non-VMS operating systems
27700 @item s-asthan-vms-alpha.adb
27701 used for VMS on the Alpha
27702 @item s-asthan-vms-ia64.adb
27703 used for VMS on the ia64
27704 @end table
27705
27706 @noindent
27707 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
27708 this operating system feature is not available, and the two remaining
27709 versions interface with the corresponding versions of VMS to provide
27710 VMS-compatible AST handling. The GNAT build script knows the architecture
27711 and operating system, and automatically selects the right version,
27712 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
27713
27714 Another style for arranging alternative implementations is through Ada's
27715 access-to-subprogram facility.
27716 In case some functionality is to be conditionally included,
27717 you can declare an access-to-procedure variable @code{Ref} that is initialized
27718 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
27719 when appropriate.
27720 In some library package, set @code{Ref} to @code{Proc'Access} for some
27721 procedure @code{Proc} that performs the relevant processing.
27722 The initialization only occurs if the library package is included in the
27723 program.
27724 The same idea can also be implemented using tagged types and dispatching
27725 calls.
27726
27727
27728 @node Preprocessing
27729 @section Preprocessing
27730 @cindex Preprocessing
27731
27732 @noindent
27733 Although it is quite possible to conditionalize code without the use of
27734 C-style preprocessing, as described earlier in this section, it is
27735 nevertheless convenient in some cases to use the C approach. Moreover,
27736 older Ada compilers have often provided some preprocessing capability,
27737 so legacy code may depend on this approach, even though it is not
27738 standard.
27739
27740 To accommodate such use, GNAT provides a preprocessor (modeled to a large
27741 extent on the various preprocessors that have been used
27742 with legacy code on other compilers, to enable easier transition).
27743
27744 The preprocessor may be used in two separate modes. It can be used quite
27745 separately from the compiler, to generate a separate output source file
27746 that is then fed to the compiler as a separate step. This is the
27747 @code{gnatprep} utility, whose use is fully described in
27748 @ref{Preprocessing with gnatprep}.
27749 @cindex @code{gnatprep}
27750
27751 The preprocessing language allows such constructs as
27752
27753 @smallexample
27754 @group
27755 #if DEBUG or else (PRIORITY > 4) then
27756 bunch of declarations
27757 #else
27758 completely different bunch of declarations
27759 #end if;
27760 @end group
27761 @end smallexample
27762
27763 @noindent
27764 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
27765 defined either on the command line or in a separate file.
27766
27767 The other way of running the preprocessor is even closer to the C style and
27768 often more convenient. In this approach the preprocessing is integrated into
27769 the compilation process. The compiler is fed the preprocessor input which
27770 includes @code{#if} lines etc, and then the compiler carries out the
27771 preprocessing internally and processes the resulting output.
27772 For more details on this approach, see @ref{Integrated Preprocessing}.
27773
27774
27775 @c *******************************
27776 @node Inline Assembler
27777 @appendix Inline Assembler
27778 @c *******************************
27779
27780 @noindent
27781 If you need to write low-level software that interacts directly
27782 with the hardware, Ada provides two ways to incorporate assembly
27783 language code into your program. First, you can import and invoke
27784 external routines written in assembly language, an Ada feature fully
27785 supported by GNAT@. However, for small sections of code it may be simpler
27786 or more efficient to include assembly language statements directly
27787 in your Ada source program, using the facilities of the implementation-defined
27788 package @code{System.Machine_Code}, which incorporates the gcc
27789 Inline Assembler. The Inline Assembler approach offers a number of advantages,
27790 including the following:
27791
27792 @itemize @bullet
27793 @item No need to use non-Ada tools
27794 @item Consistent interface over different targets
27795 @item Automatic usage of the proper calling conventions
27796 @item Access to Ada constants and variables
27797 @item Definition of intrinsic routines
27798 @item Possibility of inlining a subprogram comprising assembler code
27799 @item Code optimizer can take Inline Assembler code into account
27800 @end itemize
27801
27802 This chapter presents a series of examples to show you how to use
27803 the Inline Assembler. Although it focuses on the Intel x86,
27804 the general approach applies also to other processors.
27805 It is assumed that you are familiar with Ada
27806 and with assembly language programming.
27807
27808 @menu
27809 * Basic Assembler Syntax::
27810 * A Simple Example of Inline Assembler::
27811 * Output Variables in Inline Assembler::
27812 * Input Variables in Inline Assembler::
27813 * Inlining Inline Assembler Code::
27814 * Other Asm Functionality::
27815 @end menu
27816
27817 @c ---------------------------------------------------------------------------
27818 @node Basic Assembler Syntax
27819 @section Basic Assembler Syntax
27820
27821 @noindent
27822 The assembler used by GNAT and gcc is based not on the Intel assembly
27823 language, but rather on a language that descends from the AT&T Unix
27824 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
27825 The following table summarizes the main features of @emph{as} syntax
27826 and points out the differences from the Intel conventions.
27827 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
27828 pre-processor) documentation for further information.
27829
27830 @table @asis
27831 @item Register names
27832 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
27833 @*
27834 Intel: No extra punctuation; for example @code{eax}
27835
27836 @item Immediate operand
27837 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
27838 @*
27839 Intel: No extra punctuation; for example @code{4}
27840
27841 @item Address
27842 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
27843 @*
27844 Intel: No extra punctuation; for example @code{loc}
27845
27846 @item Memory contents
27847 gcc / @emph{as}: No extra punctuation; for example @code{loc}
27848 @*
27849 Intel: Square brackets; for example @code{[loc]}
27850
27851 @item Register contents
27852 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
27853 @*
27854 Intel: Square brackets; for example @code{[eax]}
27855
27856 @item Hexadecimal numbers
27857 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
27858 @*
27859 Intel: Trailing ``h''; for example @code{A0h}
27860
27861 @item Operand size
27862 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
27863 a 16-bit word
27864 @*
27865 Intel: Implicit, deduced by assembler; for example @code{mov}
27866
27867 @item Instruction repetition
27868 gcc / @emph{as}: Split into two lines; for example
27869 @*
27870 @code{rep}
27871 @*
27872 @code{stosl}
27873 @*
27874 Intel: Keep on one line; for example @code{rep stosl}
27875
27876 @item Order of operands
27877 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
27878 @*
27879 Intel: Destination first; for example @code{mov eax, 4}
27880 @end table
27881
27882 @c ---------------------------------------------------------------------------
27883 @node A Simple Example of Inline Assembler
27884 @section A Simple Example of Inline Assembler
27885
27886 @noindent
27887 The following example will generate a single assembly language statement,
27888 @code{nop}, which does nothing. Despite its lack of run-time effect,
27889 the example will be useful in illustrating the basics of
27890 the Inline Assembler facility.
27891
27892 @smallexample @c ada
27893 @group
27894 with System.Machine_Code; use System.Machine_Code;
27895 procedure Nothing is
27896 begin
27897 Asm ("nop");
27898 end Nothing;
27899 @end group
27900 @end smallexample
27901
27902 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
27903 here it takes one parameter, a @emph{template string} that must be a static
27904 expression and that will form the generated instruction.
27905 @code{Asm} may be regarded as a compile-time procedure that parses
27906 the template string and additional parameters (none here),
27907 from which it generates a sequence of assembly language instructions.
27908
27909 The examples in this chapter will illustrate several of the forms
27910 for invoking @code{Asm}; a complete specification of the syntax
27911 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
27912 Manual}.
27913
27914 Under the standard GNAT conventions, the @code{Nothing} procedure
27915 should be in a file named @file{nothing.adb}.
27916 You can build the executable in the usual way:
27917 @smallexample
27918 gnatmake nothing
27919 @end smallexample
27920 However, the interesting aspect of this example is not its run-time behavior
27921 but rather the generated assembly code.
27922 To see this output, invoke the compiler as follows:
27923 @smallexample
27924 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
27925 @end smallexample
27926 where the options are:
27927
27928 @table @code
27929 @item -c
27930 compile only (no bind or link)
27931 @item -S
27932 generate assembler listing
27933 @item -fomit-frame-pointer
27934 do not set up separate stack frames
27935 @item -gnatp
27936 do not add runtime checks
27937 @end table
27938
27939 This gives a human-readable assembler version of the code. The resulting
27940 file will have the same name as the Ada source file, but with a @code{.s}
27941 extension. In our example, the file @file{nothing.s} has the following
27942 contents:
27943
27944 @smallexample
27945 @group
27946 .file "nothing.adb"
27947 gcc2_compiled.:
27948 ___gnu_compiled_ada:
27949 .text
27950 .align 4
27951 .globl __ada_nothing
27952 __ada_nothing:
27953 #APP
27954 nop
27955 #NO_APP
27956 jmp L1
27957 .align 2,0x90
27958 L1:
27959 ret
27960 @end group
27961 @end smallexample
27962
27963 The assembly code you included is clearly indicated by
27964 the compiler, between the @code{#APP} and @code{#NO_APP}
27965 delimiters. The character before the 'APP' and 'NOAPP'
27966 can differ on different targets. For example, GNU/Linux uses '#APP' while
27967 on NT you will see '/APP'.
27968
27969 If you make a mistake in your assembler code (such as using the
27970 wrong size modifier, or using a wrong operand for the instruction) GNAT
27971 will report this error in a temporary file, which will be deleted when
27972 the compilation is finished. Generating an assembler file will help
27973 in such cases, since you can assemble this file separately using the
27974 @emph{as} assembler that comes with gcc.
27975
27976 Assembling the file using the command
27977
27978 @smallexample
27979 as @file{nothing.s}
27980 @end smallexample
27981 @noindent
27982 will give you error messages whose lines correspond to the assembler
27983 input file, so you can easily find and correct any mistakes you made.
27984 If there are no errors, @emph{as} will generate an object file
27985 @file{nothing.out}.
27986
27987 @c ---------------------------------------------------------------------------
27988 @node Output Variables in Inline Assembler
27989 @section Output Variables in Inline Assembler
27990
27991 @noindent
27992 The examples in this section, showing how to access the processor flags,
27993 illustrate how to specify the destination operands for assembly language
27994 statements.
27995
27996 @smallexample @c ada
27997 @group
27998 with Interfaces; use Interfaces;
27999 with Ada.Text_IO; use Ada.Text_IO;
28000 with System.Machine_Code; use System.Machine_Code;
28001 procedure Get_Flags is
28002 Flags : Unsigned_32;
28003 use ASCII;
28004 begin
28005 Asm ("pushfl" & LF & HT & -- push flags on stack
28006 "popl %%eax" & LF & HT & -- load eax with flags
28007 "movl %%eax, %0", -- store flags in variable
28008 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28009 Put_Line ("Flags register:" & Flags'Img);
28010 end Get_Flags;
28011 @end group
28012 @end smallexample
28013
28014 In order to have a nicely aligned assembly listing, we have separated
28015 multiple assembler statements in the Asm template string with linefeed
28016 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
28017 The resulting section of the assembly output file is:
28018
28019 @smallexample
28020 @group
28021 #APP
28022 pushfl
28023 popl %eax
28024 movl %eax, -40(%ebp)
28025 #NO_APP
28026 @end group
28027 @end smallexample
28028
28029 It would have been legal to write the Asm invocation as:
28030
28031 @smallexample
28032 Asm ("pushfl popl %%eax movl %%eax, %0")
28033 @end smallexample
28034
28035 but in the generated assembler file, this would come out as:
28036
28037 @smallexample
28038 #APP
28039 pushfl popl %eax movl %eax, -40(%ebp)
28040 #NO_APP
28041 @end smallexample
28042
28043 which is not so convenient for the human reader.
28044
28045 We use Ada comments
28046 at the end of each line to explain what the assembler instructions
28047 actually do. This is a useful convention.
28048
28049 When writing Inline Assembler instructions, you need to precede each register
28050 and variable name with a percent sign. Since the assembler already requires
28051 a percent sign at the beginning of a register name, you need two consecutive
28052 percent signs for such names in the Asm template string, thus @code{%%eax}.
28053 In the generated assembly code, one of the percent signs will be stripped off.
28054
28055 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
28056 variables: operands you later define using @code{Input} or @code{Output}
28057 parameters to @code{Asm}.
28058 An output variable is illustrated in
28059 the third statement in the Asm template string:
28060 @smallexample
28061 movl %%eax, %0
28062 @end smallexample
28063 The intent is to store the contents of the eax register in a variable that can
28064 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
28065 necessarily work, since the compiler might optimize by using a register
28066 to hold Flags, and the expansion of the @code{movl} instruction would not be
28067 aware of this optimization. The solution is not to store the result directly
28068 but rather to advise the compiler to choose the correct operand form;
28069 that is the purpose of the @code{%0} output variable.
28070
28071 Information about the output variable is supplied in the @code{Outputs}
28072 parameter to @code{Asm}:
28073 @smallexample
28074 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28075 @end smallexample
28076
28077 The output is defined by the @code{Asm_Output} attribute of the target type;
28078 the general format is
28079 @smallexample
28080 Type'Asm_Output (constraint_string, variable_name)
28081 @end smallexample
28082
28083 The constraint string directs the compiler how
28084 to store/access the associated variable. In the example
28085 @smallexample
28086 Unsigned_32'Asm_Output ("=m", Flags);
28087 @end smallexample
28088 the @code{"m"} (memory) constraint tells the compiler that the variable
28089 @code{Flags} should be stored in a memory variable, thus preventing
28090 the optimizer from keeping it in a register. In contrast,
28091 @smallexample
28092 Unsigned_32'Asm_Output ("=r", Flags);
28093 @end smallexample
28094 uses the @code{"r"} (register) constraint, telling the compiler to
28095 store the variable in a register.
28096
28097 If the constraint is preceded by the equal character (@strong{=}), it tells
28098 the compiler that the variable will be used to store data into it.
28099
28100 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
28101 allowing the optimizer to choose whatever it deems best.
28102
28103 There are a fairly large number of constraints, but the ones that are
28104 most useful (for the Intel x86 processor) are the following:
28105
28106 @table @code
28107 @item =
28108 output constraint
28109 @item g
28110 global (i.e.@: can be stored anywhere)
28111 @item m
28112 in memory
28113 @item I
28114 a constant
28115 @item a
28116 use eax
28117 @item b
28118 use ebx
28119 @item c
28120 use ecx
28121 @item d
28122 use edx
28123 @item S
28124 use esi
28125 @item D
28126 use edi
28127 @item r
28128 use one of eax, ebx, ecx or edx
28129 @item q
28130 use one of eax, ebx, ecx, edx, esi or edi
28131 @end table
28132
28133 The full set of constraints is described in the gcc and @emph{as}
28134 documentation; note that it is possible to combine certain constraints
28135 in one constraint string.
28136
28137 You specify the association of an output variable with an assembler operand
28138 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
28139 integer. Thus in
28140 @smallexample @c ada
28141 @group
28142 Asm ("pushfl" & LF & HT & -- push flags on stack
28143 "popl %%eax" & LF & HT & -- load eax with flags
28144 "movl %%eax, %0", -- store flags in variable
28145 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28146 @end group
28147 @end smallexample
28148 @noindent
28149 @code{%0} will be replaced in the expanded code by the appropriate operand,
28150 whatever
28151 the compiler decided for the @code{Flags} variable.
28152
28153 In general, you may have any number of output variables:
28154 @itemize @bullet
28155 @item
28156 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
28157 @item
28158 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
28159 of @code{Asm_Output} attributes
28160 @end itemize
28161
28162 For example:
28163 @smallexample @c ada
28164 @group
28165 Asm ("movl %%eax, %0" & LF & HT &
28166 "movl %%ebx, %1" & LF & HT &
28167 "movl %%ecx, %2",
28168 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
28169 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
28170 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
28171 @end group
28172 @end smallexample
28173 @noindent
28174 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
28175 in the Ada program.
28176
28177 As a variation on the @code{Get_Flags} example, we can use the constraints
28178 string to direct the compiler to store the eax register into the @code{Flags}
28179 variable, instead of including the store instruction explicitly in the
28180 @code{Asm} template string:
28181
28182 @smallexample @c ada
28183 @group
28184 with Interfaces; use Interfaces;
28185 with Ada.Text_IO; use Ada.Text_IO;
28186 with System.Machine_Code; use System.Machine_Code;
28187 procedure Get_Flags_2 is
28188 Flags : Unsigned_32;
28189 use ASCII;
28190 begin
28191 Asm ("pushfl" & LF & HT & -- push flags on stack
28192 "popl %%eax", -- save flags in eax
28193 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
28194 Put_Line ("Flags register:" & Flags'Img);
28195 end Get_Flags_2;
28196 @end group
28197 @end smallexample
28198
28199 @noindent
28200 The @code{"a"} constraint tells the compiler that the @code{Flags}
28201 variable will come from the eax register. Here is the resulting code:
28202
28203 @smallexample
28204 @group
28205 #APP
28206 pushfl
28207 popl %eax
28208 #NO_APP
28209 movl %eax,-40(%ebp)
28210 @end group
28211 @end smallexample
28212
28213 @noindent
28214 The compiler generated the store of eax into Flags after
28215 expanding the assembler code.
28216
28217 Actually, there was no need to pop the flags into the eax register;
28218 more simply, we could just pop the flags directly into the program variable:
28219
28220 @smallexample @c ada
28221 @group
28222 with Interfaces; use Interfaces;
28223 with Ada.Text_IO; use Ada.Text_IO;
28224 with System.Machine_Code; use System.Machine_Code;
28225 procedure Get_Flags_3 is
28226 Flags : Unsigned_32;
28227 use ASCII;
28228 begin
28229 Asm ("pushfl" & LF & HT & -- push flags on stack
28230 "pop %0", -- save flags in Flags
28231 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28232 Put_Line ("Flags register:" & Flags'Img);
28233 end Get_Flags_3;
28234 @end group
28235 @end smallexample
28236
28237 @c ---------------------------------------------------------------------------
28238 @node Input Variables in Inline Assembler
28239 @section Input Variables in Inline Assembler
28240
28241 @noindent
28242 The example in this section illustrates how to specify the source operands
28243 for assembly language statements.
28244 The program simply increments its input value by 1:
28245
28246 @smallexample @c ada
28247 @group
28248 with Interfaces; use Interfaces;
28249 with Ada.Text_IO; use Ada.Text_IO;
28250 with System.Machine_Code; use System.Machine_Code;
28251 procedure Increment is
28252
28253 function Incr (Value : Unsigned_32) return Unsigned_32 is
28254 Result : Unsigned_32;
28255 begin
28256 Asm ("incl %0",
28257 Outputs => Unsigned_32'Asm_Output ("=a", Result),
28258 Inputs => Unsigned_32'Asm_Input ("a", Value));
28259 return Result;
28260 end Incr;
28261
28262 Value : Unsigned_32;
28263
28264 begin
28265 Value := 5;
28266 Put_Line ("Value before is" & Value'Img);
28267 Value := Incr (Value);
28268 Put_Line ("Value after is" & Value'Img);
28269 end Increment;
28270 @end group
28271 @end smallexample
28272
28273 The @code{Outputs} parameter to @code{Asm} specifies
28274 that the result will be in the eax register and that it is to be stored
28275 in the @code{Result} variable.
28276
28277 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
28278 but with an @code{Asm_Input} attribute.
28279 The @code{"="} constraint, indicating an output value, is not present.
28280
28281 You can have multiple input variables, in the same way that you can have more
28282 than one output variable.
28283
28284 The parameter count (%0, %1) etc, still starts at the first output statement,
28285 and continues with the input statements.
28286
28287 Just as the @code{Outputs} parameter causes the register to be stored into the
28288 target variable after execution of the assembler statements, so does the
28289 @code{Inputs} parameter cause its variable to be loaded into the register
28290 before execution of the assembler statements.
28291
28292 Thus the effect of the @code{Asm} invocation is:
28293 @enumerate
28294 @item load the 32-bit value of @code{Value} into eax
28295 @item execute the @code{incl %eax} instruction
28296 @item store the contents of eax into the @code{Result} variable
28297 @end enumerate
28298
28299 The resulting assembler file (with @option{-O2} optimization) contains:
28300 @smallexample
28301 @group
28302 _increment__incr.1:
28303 subl $4,%esp
28304 movl 8(%esp),%eax
28305 #APP
28306 incl %eax
28307 #NO_APP
28308 movl %eax,%edx
28309 movl %ecx,(%esp)
28310 addl $4,%esp
28311 ret
28312 @end group
28313 @end smallexample
28314
28315 @c ---------------------------------------------------------------------------
28316 @node Inlining Inline Assembler Code
28317 @section Inlining Inline Assembler Code
28318
28319 @noindent
28320 For a short subprogram such as the @code{Incr} function in the previous
28321 section, the overhead of the call and return (creating / deleting the stack
28322 frame) can be significant, compared to the amount of code in the subprogram
28323 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
28324 which directs the compiler to expand invocations of the subprogram at the
28325 point(s) of call, instead of setting up a stack frame for out-of-line calls.
28326 Here is the resulting program:
28327
28328 @smallexample @c ada
28329 @group
28330 with Interfaces; use Interfaces;
28331 with Ada.Text_IO; use Ada.Text_IO;
28332 with System.Machine_Code; use System.Machine_Code;
28333 procedure Increment_2 is
28334
28335 function Incr (Value : Unsigned_32) return Unsigned_32 is
28336 Result : Unsigned_32;
28337 begin
28338 Asm ("incl %0",
28339 Outputs => Unsigned_32'Asm_Output ("=a", Result),
28340 Inputs => Unsigned_32'Asm_Input ("a", Value));
28341 return Result;
28342 end Incr;
28343 pragma Inline (Increment);
28344
28345 Value : Unsigned_32;
28346
28347 begin
28348 Value := 5;
28349 Put_Line ("Value before is" & Value'Img);
28350 Value := Increment (Value);
28351 Put_Line ("Value after is" & Value'Img);
28352 end Increment_2;
28353 @end group
28354 @end smallexample
28355
28356 Compile the program with both optimization (@option{-O2}) and inlining
28357 (@option{-gnatn}) enabled.
28358
28359 The @code{Incr} function is still compiled as usual, but at the
28360 point in @code{Increment} where our function used to be called:
28361
28362 @smallexample
28363 @group
28364 pushl %edi
28365 call _increment__incr.1
28366 @end group
28367 @end smallexample
28368
28369 @noindent
28370 the code for the function body directly appears:
28371
28372 @smallexample
28373 @group
28374 movl %esi,%eax
28375 #APP
28376 incl %eax
28377 #NO_APP
28378 movl %eax,%edx
28379 @end group
28380 @end smallexample
28381
28382 @noindent
28383 thus saving the overhead of stack frame setup and an out-of-line call.
28384
28385 @c ---------------------------------------------------------------------------
28386 @node Other Asm Functionality
28387 @section Other @code{Asm} Functionality
28388
28389 @noindent
28390 This section describes two important parameters to the @code{Asm}
28391 procedure: @code{Clobber}, which identifies register usage;
28392 and @code{Volatile}, which inhibits unwanted optimizations.
28393
28394 @menu
28395 * The Clobber Parameter::
28396 * The Volatile Parameter::
28397 @end menu
28398
28399 @c ---------------------------------------------------------------------------
28400 @node The Clobber Parameter
28401 @subsection The @code{Clobber} Parameter
28402
28403 @noindent
28404 One of the dangers of intermixing assembly language and a compiled language
28405 such as Ada is that the compiler needs to be aware of which registers are
28406 being used by the assembly code. In some cases, such as the earlier examples,
28407 the constraint string is sufficient to indicate register usage (e.g.,
28408 @code{"a"} for
28409 the eax register). But more generally, the compiler needs an explicit
28410 identification of the registers that are used by the Inline Assembly
28411 statements.
28412
28413 Using a register that the compiler doesn't know about
28414 could be a side effect of an instruction (like @code{mull}
28415 storing its result in both eax and edx).
28416 It can also arise from explicit register usage in your
28417 assembly code; for example:
28418 @smallexample
28419 @group
28420 Asm ("movl %0, %%ebx" & LF & HT &
28421 "movl %%ebx, %1",
28422 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28423 Inputs => Unsigned_32'Asm_Input ("g", Var_In));
28424 @end group
28425 @end smallexample
28426 @noindent
28427 where the compiler (since it does not analyze the @code{Asm} template string)
28428 does not know you are using the ebx register.
28429
28430 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
28431 to identify the registers that will be used by your assembly code:
28432
28433 @smallexample
28434 @group
28435 Asm ("movl %0, %%ebx" & LF & HT &
28436 "movl %%ebx, %1",
28437 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28438 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28439 Clobber => "ebx");
28440 @end group
28441 @end smallexample
28442
28443 The Clobber parameter is a static string expression specifying the
28444 register(s) you are using. Note that register names are @emph{not} prefixed
28445 by a percent sign. Also, if more than one register is used then their names
28446 are separated by commas; e.g., @code{"eax, ebx"}
28447
28448 The @code{Clobber} parameter has several additional uses:
28449 @enumerate
28450 @item Use ``register'' name @code{cc} to indicate that flags might have changed
28451 @item Use ``register'' name @code{memory} if you changed a memory location
28452 @end enumerate
28453
28454 @c ---------------------------------------------------------------------------
28455 @node The Volatile Parameter
28456 @subsection The @code{Volatile} Parameter
28457 @cindex Volatile parameter
28458
28459 @noindent
28460 Compiler optimizations in the presence of Inline Assembler may sometimes have
28461 unwanted effects. For example, when an @code{Asm} invocation with an input
28462 variable is inside a loop, the compiler might move the loading of the input
28463 variable outside the loop, regarding it as a one-time initialization.
28464
28465 If this effect is not desired, you can disable such optimizations by setting
28466 the @code{Volatile} parameter to @code{True}; for example:
28467
28468 @smallexample @c ada
28469 @group
28470 Asm ("movl %0, %%ebx" & LF & HT &
28471 "movl %%ebx, %1",
28472 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28473 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28474 Clobber => "ebx",
28475 Volatile => True);
28476 @end group
28477 @end smallexample
28478
28479 By default, @code{Volatile} is set to @code{False} unless there is no
28480 @code{Outputs} parameter.
28481
28482 Although setting @code{Volatile} to @code{True} prevents unwanted
28483 optimizations, it will also disable other optimizations that might be
28484 important for efficiency. In general, you should set @code{Volatile}
28485 to @code{True} only if the compiler's optimizations have created
28486 problems.
28487 @c END OF INLINE ASSEMBLER CHAPTER
28488 @c ===============================
28489
28490 @c ***********************************
28491 @c * Compatibility and Porting Guide *
28492 @c ***********************************
28493 @node Compatibility and Porting Guide
28494 @appendix Compatibility and Porting Guide
28495
28496 @noindent
28497 This chapter describes the compatibility issues that may arise between
28498 GNAT and other Ada compilation systems (including those for Ada 83),
28499 and shows how GNAT can expedite porting
28500 applications developed in other Ada environments.
28501
28502 @menu
28503 * Compatibility with Ada 83::
28504 * Compatibility between Ada 95 and Ada 2005::
28505 * Implementation-dependent characteristics::
28506 * Compatibility with Other Ada Systems::
28507 * Representation Clauses::
28508 @ifclear vms
28509 @c Brief section is only in non-VMS version
28510 @c Full chapter is in VMS version
28511 * Compatibility with HP Ada 83::
28512 @end ifclear
28513 @ifset vms
28514 * Transitioning to 64-Bit GNAT for OpenVMS::
28515 @end ifset
28516 @end menu
28517
28518 @node Compatibility with Ada 83
28519 @section Compatibility with Ada 83
28520 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
28521
28522 @noindent
28523 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
28524 particular, the design intention was that the difficulties associated
28525 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
28526 that occur when moving from one Ada 83 system to another.
28527
28528 However, there are a number of points at which there are minor
28529 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
28530 full details of these issues,
28531 and should be consulted for a complete treatment.
28532 In practice the
28533 following subsections treat the most likely issues to be encountered.
28534
28535 @menu
28536 * Legal Ada 83 programs that are illegal in Ada 95::
28537 * More deterministic semantics::
28538 * Changed semantics::
28539 * Other language compatibility issues::
28540 @end menu
28541
28542 @node Legal Ada 83 programs that are illegal in Ada 95
28543 @subsection Legal Ada 83 programs that are illegal in Ada 95
28544
28545 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
28546 Ada 95 and thus also in Ada 2005:
28547
28548 @table @emph
28549 @item Character literals
28550 Some uses of character literals are ambiguous. Since Ada 95 has introduced
28551 @code{Wide_Character} as a new predefined character type, some uses of
28552 character literals that were legal in Ada 83 are illegal in Ada 95.
28553 For example:
28554 @smallexample @c ada
28555 for Char in 'A' .. 'Z' loop @dots{} end loop;
28556 @end smallexample
28557
28558 @noindent
28559 The problem is that @code{'A'} and @code{'Z'} could be from either
28560 @code{Character} or @code{Wide_Character}. The simplest correction
28561 is to make the type explicit; e.g.:
28562 @smallexample @c ada
28563 for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
28564 @end smallexample
28565
28566 @item New reserved words
28567 The identifiers @code{abstract}, @code{aliased}, @code{protected},
28568 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
28569 Existing Ada 83 code using any of these identifiers must be edited to
28570 use some alternative name.
28571
28572 @item Freezing rules
28573 The rules in Ada 95 are slightly different with regard to the point at
28574 which entities are frozen, and representation pragmas and clauses are
28575 not permitted past the freeze point. This shows up most typically in
28576 the form of an error message complaining that a representation item
28577 appears too late, and the appropriate corrective action is to move
28578 the item nearer to the declaration of the entity to which it refers.
28579
28580 A particular case is that representation pragmas
28581 @ifset vms
28582 (including the
28583 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
28584 @end ifset
28585 cannot be applied to a subprogram body. If necessary, a separate subprogram
28586 declaration must be introduced to which the pragma can be applied.
28587
28588 @item Optional bodies for library packages
28589 In Ada 83, a package that did not require a package body was nevertheless
28590 allowed to have one. This lead to certain surprises in compiling large
28591 systems (situations in which the body could be unexpectedly ignored by the
28592 binder). In Ada 95, if a package does not require a body then it is not
28593 permitted to have a body. To fix this problem, simply remove a redundant
28594 body if it is empty, or, if it is non-empty, introduce a dummy declaration
28595 into the spec that makes the body required. One approach is to add a private
28596 part to the package declaration (if necessary), and define a parameterless
28597 procedure called @code{Requires_Body}, which must then be given a dummy
28598 procedure body in the package body, which then becomes required.
28599 Another approach (assuming that this does not introduce elaboration
28600 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
28601 since one effect of this pragma is to require the presence of a package body.
28602
28603 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
28604 In Ada 95, the exception @code{Numeric_Error} is a renaming of
28605 @code{Constraint_Error}.
28606 This means that it is illegal to have separate exception handlers for
28607 the two exceptions. The fix is simply to remove the handler for the
28608 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
28609 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
28610
28611 @item Indefinite subtypes in generics
28612 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
28613 as the actual for a generic formal private type, but then the instantiation
28614 would be illegal if there were any instances of declarations of variables
28615 of this type in the generic body. In Ada 95, to avoid this clear violation
28616 of the methodological principle known as the ``contract model'',
28617 the generic declaration explicitly indicates whether
28618 or not such instantiations are permitted. If a generic formal parameter
28619 has explicit unknown discriminants, indicated by using @code{(<>)} after the
28620 subtype name, then it can be instantiated with indefinite types, but no
28621 stand-alone variables can be declared of this type. Any attempt to declare
28622 such a variable will result in an illegality at the time the generic is
28623 declared. If the @code{(<>)} notation is not used, then it is illegal
28624 to instantiate the generic with an indefinite type.
28625 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
28626 It will show up as a compile time error, and
28627 the fix is usually simply to add the @code{(<>)} to the generic declaration.
28628 @end table
28629
28630 @node More deterministic semantics
28631 @subsection More deterministic semantics
28632
28633 @table @emph
28634 @item Conversions
28635 Conversions from real types to integer types round away from 0. In Ada 83
28636 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
28637 implementation freedom was intended to support unbiased rounding in
28638 statistical applications, but in practice it interfered with portability.
28639 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
28640 is required. Numeric code may be affected by this change in semantics.
28641 Note, though, that this issue is no worse than already existed in Ada 83
28642 when porting code from one vendor to another.
28643
28644 @item Tasking
28645 The Real-Time Annex introduces a set of policies that define the behavior of
28646 features that were implementation dependent in Ada 83, such as the order in
28647 which open select branches are executed.
28648 @end table
28649
28650 @node Changed semantics
28651 @subsection Changed semantics
28652
28653 @noindent
28654 The worst kind of incompatibility is one where a program that is legal in
28655 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
28656 possible in Ada 83. Fortunately this is extremely rare, but the one
28657 situation that you should be alert to is the change in the predefined type
28658 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
28659
28660 @table @emph
28661 @item Range of type @code{Character}
28662 The range of @code{Standard.Character} is now the full 256 characters
28663 of Latin-1, whereas in most Ada 83 implementations it was restricted
28664 to 128 characters. Although some of the effects of
28665 this change will be manifest in compile-time rejection of legal
28666 Ada 83 programs it is possible for a working Ada 83 program to have
28667 a different effect in Ada 95, one that was not permitted in Ada 83.
28668 As an example, the expression
28669 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
28670 delivers @code{255} as its value.
28671 In general, you should look at the logic of any
28672 character-processing Ada 83 program and see whether it needs to be adapted
28673 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
28674 character handling package that may be relevant if code needs to be adapted
28675 to account for the additional Latin-1 elements.
28676 The desirable fix is to
28677 modify the program to accommodate the full character set, but in some cases
28678 it may be convenient to define a subtype or derived type of Character that
28679 covers only the restricted range.
28680 @cindex Latin-1
28681 @end table
28682
28683 @node Other language compatibility issues
28684 @subsection Other language compatibility issues
28685
28686 @table @emph
28687 @item @option{-gnat83} switch
28688 All implementations of GNAT provide a switch that causes GNAT to operate
28689 in Ada 83 mode. In this mode, some but not all compatibility problems
28690 of the type described above are handled automatically. For example, the
28691 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
28692 as identifiers as in Ada 83.
28693 However,
28694 in practice, it is usually advisable to make the necessary modifications
28695 to the program to remove the need for using this switch.
28696 See @ref{Compiling Different Versions of Ada}.
28697
28698 @item Support for removed Ada 83 pragmas and attributes
28699 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
28700 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
28701 compilers are allowed, but not required, to implement these missing
28702 elements. In contrast with some other compilers, GNAT implements all
28703 such pragmas and attributes, eliminating this compatibility concern. These
28704 include @code{pragma Interface} and the floating point type attributes
28705 (@code{Emax}, @code{Mantissa}, etc.), among other items.
28706 @end table
28707
28708
28709 @node Compatibility between Ada 95 and Ada 2005
28710 @section Compatibility between Ada 95 and Ada 2005
28711 @cindex Compatibility between Ada 95 and Ada 2005
28712
28713 @noindent
28714 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
28715 a number of incompatibilities. Several are enumerated below;
28716 for a complete description please see the
28717 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
28718 @cite{Rationale for Ada 2005}.
28719
28720 @table @emph
28721 @item New reserved words.
28722 The words @code{interface}, @code{overriding} and @code{synchronized} are
28723 reserved in Ada 2005.
28724 A pre-Ada 2005 program that uses any of these as an identifier will be
28725 illegal.
28726
28727 @item New declarations in predefined packages.
28728 A number of packages in the predefined environment contain new declarations:
28729 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
28730 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
28731 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
28732 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
28733 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
28734 If an Ada 95 program does a @code{with} and @code{use} of any of these
28735 packages, the new declarations may cause name clashes.
28736
28737 @item Access parameters.
28738 A nondispatching subprogram with an access parameter cannot be renamed
28739 as a dispatching operation. This was permitted in Ada 95.
28740
28741 @item Access types, discriminants, and constraints.
28742 Rule changes in this area have led to some incompatibilities; for example,
28743 constrained subtypes of some access types are not permitted in Ada 2005.
28744
28745 @item Aggregates for limited types.
28746 The allowance of aggregates for limited types in Ada 2005 raises the
28747 possibility of ambiguities in legal Ada 95 programs, since additional types
28748 now need to be considered in expression resolution.
28749
28750 @item Fixed-point multiplication and division.
28751 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
28752 were legal in Ada 95 and invoked the predefined versions of these operations,
28753 are now ambiguous.
28754 The ambiguity may be resolved either by applying a type conversion to the
28755 expression, or by explicitly invoking the operation from package
28756 @code{Standard}.
28757
28758 @item Return-by-reference types.
28759 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
28760 can declare a function returning a value from an anonymous access type.
28761 @end table
28762
28763
28764 @node Implementation-dependent characteristics
28765 @section Implementation-dependent characteristics
28766 @noindent
28767 Although the Ada language defines the semantics of each construct as
28768 precisely as practical, in some situations (for example for reasons of
28769 efficiency, or where the effect is heavily dependent on the host or target
28770 platform) the implementation is allowed some freedom. In porting Ada 83
28771 code to GNAT, you need to be aware of whether / how the existing code
28772 exercised such implementation dependencies. Such characteristics fall into
28773 several categories, and GNAT offers specific support in assisting the
28774 transition from certain Ada 83 compilers.
28775
28776 @menu
28777 * Implementation-defined pragmas::
28778 * Implementation-defined attributes::
28779 * Libraries::
28780 * Elaboration order::
28781 * Target-specific aspects::
28782 @end menu
28783
28784 @node Implementation-defined pragmas
28785 @subsection Implementation-defined pragmas
28786
28787 @noindent
28788 Ada compilers are allowed to supplement the language-defined pragmas, and
28789 these are a potential source of non-portability. All GNAT-defined pragmas
28790 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
28791 Reference Manual}, and these include several that are specifically
28792 intended to correspond to other vendors' Ada 83 pragmas.
28793 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
28794 For compatibility with HP Ada 83, GNAT supplies the pragmas
28795 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
28796 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
28797 and @code{Volatile}.
28798 Other relevant pragmas include @code{External} and @code{Link_With}.
28799 Some vendor-specific
28800 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
28801 recognized, thus
28802 avoiding compiler rejection of units that contain such pragmas; they are not
28803 relevant in a GNAT context and hence are not otherwise implemented.
28804
28805 @node Implementation-defined attributes
28806 @subsection Implementation-defined attributes
28807
28808 Analogous to pragmas, the set of attributes may be extended by an
28809 implementation. All GNAT-defined attributes are described in
28810 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
28811 Manual}, and these include several that are specifically intended
28812 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
28813 the attribute @code{VADS_Size} may be useful. For compatibility with HP
28814 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
28815 @code{Type_Class}.
28816
28817 @node Libraries
28818 @subsection Libraries
28819 @noindent
28820 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
28821 code uses vendor-specific libraries then there are several ways to manage
28822 this in Ada 95 or Ada 2005:
28823 @enumerate
28824 @item
28825 If the source code for the libraries (specs and bodies) are
28826 available, then the libraries can be migrated in the same way as the
28827 application.
28828 @item
28829 If the source code for the specs but not the bodies are
28830 available, then you can reimplement the bodies.
28831 @item
28832 Some features introduced by Ada 95 obviate the need for library support. For
28833 example most Ada 83 vendors supplied a package for unsigned integers. The
28834 Ada 95 modular type feature is the preferred way to handle this need, so
28835 instead of migrating or reimplementing the unsigned integer package it may
28836 be preferable to retrofit the application using modular types.
28837 @end enumerate
28838
28839 @node Elaboration order
28840 @subsection Elaboration order
28841 @noindent
28842 The implementation can choose any elaboration order consistent with the unit
28843 dependency relationship. This freedom means that some orders can result in
28844 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
28845 to invoke a subprogram its body has been elaborated, or to instantiate a
28846 generic before the generic body has been elaborated. By default GNAT
28847 attempts to choose a safe order (one that will not encounter access before
28848 elaboration problems) by implicitly inserting @code{Elaborate} or
28849 @code{Elaborate_All} pragmas where
28850 needed. However, this can lead to the creation of elaboration circularities
28851 and a resulting rejection of the program by gnatbind. This issue is
28852 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
28853 In brief, there are several
28854 ways to deal with this situation:
28855
28856 @itemize @bullet
28857 @item
28858 Modify the program to eliminate the circularities, e.g.@: by moving
28859 elaboration-time code into explicitly-invoked procedures
28860 @item
28861 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
28862 @code{Elaborate} pragmas, and then inhibit the generation of implicit
28863 @code{Elaborate_All}
28864 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
28865 (by selectively suppressing elaboration checks via pragma
28866 @code{Suppress(Elaboration_Check)} when it is safe to do so).
28867 @end itemize
28868
28869 @node Target-specific aspects
28870 @subsection Target-specific aspects
28871 @noindent
28872 Low-level applications need to deal with machine addresses, data
28873 representations, interfacing with assembler code, and similar issues. If
28874 such an Ada 83 application is being ported to different target hardware (for
28875 example where the byte endianness has changed) then you will need to
28876 carefully examine the program logic; the porting effort will heavily depend
28877 on the robustness of the original design. Moreover, Ada 95 (and thus
28878 Ada 2005) are sometimes
28879 incompatible with typical Ada 83 compiler practices regarding implicit
28880 packing, the meaning of the Size attribute, and the size of access values.
28881 GNAT's approach to these issues is described in @ref{Representation Clauses}.
28882
28883 @node Compatibility with Other Ada Systems
28884 @section Compatibility with Other Ada Systems
28885
28886 @noindent
28887 If programs avoid the use of implementation dependent and
28888 implementation defined features, as documented in the @cite{Ada
28889 Reference Manual}, there should be a high degree of portability between
28890 GNAT and other Ada systems. The following are specific items which
28891 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
28892 compilers, but do not affect porting code to GNAT@.
28893 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
28894 the following issues may or may not arise for Ada 2005 programs
28895 when other compilers appear.)
28896
28897 @table @emph
28898 @item Ada 83 Pragmas and Attributes
28899 Ada 95 compilers are allowed, but not required, to implement the missing
28900 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
28901 GNAT implements all such pragmas and attributes, eliminating this as
28902 a compatibility concern, but some other Ada 95 compilers reject these
28903 pragmas and attributes.
28904
28905 @item Specialized Needs Annexes
28906 GNAT implements the full set of special needs annexes. At the
28907 current time, it is the only Ada 95 compiler to do so. This means that
28908 programs making use of these features may not be portable to other Ada
28909 95 compilation systems.
28910
28911 @item Representation Clauses
28912 Some other Ada 95 compilers implement only the minimal set of
28913 representation clauses required by the Ada 95 reference manual. GNAT goes
28914 far beyond this minimal set, as described in the next section.
28915 @end table
28916
28917 @node Representation Clauses
28918 @section Representation Clauses
28919
28920 @noindent
28921 The Ada 83 reference manual was quite vague in describing both the minimal
28922 required implementation of representation clauses, and also their precise
28923 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
28924 minimal set of capabilities required is still quite limited.
28925
28926 GNAT implements the full required set of capabilities in
28927 Ada 95 and Ada 2005, but also goes much further, and in particular
28928 an effort has been made to be compatible with existing Ada 83 usage to the
28929 greatest extent possible.
28930
28931 A few cases exist in which Ada 83 compiler behavior is incompatible with
28932 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
28933 intentional or accidental dependence on specific implementation dependent
28934 characteristics of these Ada 83 compilers. The following is a list of
28935 the cases most likely to arise in existing Ada 83 code.
28936
28937 @table @emph
28938 @item Implicit Packing
28939 Some Ada 83 compilers allowed a Size specification to cause implicit
28940 packing of an array or record. This could cause expensive implicit
28941 conversions for change of representation in the presence of derived
28942 types, and the Ada design intends to avoid this possibility.
28943 Subsequent AI's were issued to make it clear that such implicit
28944 change of representation in response to a Size clause is inadvisable,
28945 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
28946 Reference Manuals as implementation advice that is followed by GNAT@.
28947 The problem will show up as an error
28948 message rejecting the size clause. The fix is simply to provide
28949 the explicit pragma @code{Pack}, or for more fine tuned control, provide
28950 a Component_Size clause.
28951
28952 @item Meaning of Size Attribute
28953 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
28954 the minimal number of bits required to hold values of the type. For example,
28955 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
28956 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
28957 some 32 in this situation. This problem will usually show up as a compile
28958 time error, but not always. It is a good idea to check all uses of the
28959 'Size attribute when porting Ada 83 code. The GNAT specific attribute
28960 Object_Size can provide a useful way of duplicating the behavior of
28961 some Ada 83 compiler systems.
28962
28963 @item Size of Access Types
28964 A common assumption in Ada 83 code is that an access type is in fact a pointer,
28965 and that therefore it will be the same size as a System.Address value. This
28966 assumption is true for GNAT in most cases with one exception. For the case of
28967 a pointer to an unconstrained array type (where the bounds may vary from one
28968 value of the access type to another), the default is to use a ``fat pointer'',
28969 which is represented as two separate pointers, one to the bounds, and one to
28970 the array. This representation has a number of advantages, including improved
28971 efficiency. However, it may cause some difficulties in porting existing Ada 83
28972 code which makes the assumption that, for example, pointers fit in 32 bits on
28973 a machine with 32-bit addressing.
28974
28975 To get around this problem, GNAT also permits the use of ``thin pointers'' for
28976 access types in this case (where the designated type is an unconstrained array
28977 type). These thin pointers are indeed the same size as a System.Address value.
28978 To specify a thin pointer, use a size clause for the type, for example:
28979
28980 @smallexample @c ada
28981 type X is access all String;
28982 for X'Size use Standard'Address_Size;
28983 @end smallexample
28984
28985 @noindent
28986 which will cause the type X to be represented using a single pointer.
28987 When using this representation, the bounds are right behind the array.
28988 This representation is slightly less efficient, and does not allow quite
28989 such flexibility in the use of foreign pointers or in using the
28990 Unrestricted_Access attribute to create pointers to non-aliased objects.
28991 But for any standard portable use of the access type it will work in
28992 a functionally correct manner and allow porting of existing code.
28993 Note that another way of forcing a thin pointer representation
28994 is to use a component size clause for the element size in an array,
28995 or a record representation clause for an access field in a record.
28996 @end table
28997
28998 @ifclear vms
28999 @c This brief section is only in the non-VMS version
29000 @c The complete chapter on HP Ada is in the VMS version
29001 @node Compatibility with HP Ada 83
29002 @section Compatibility with HP Ada 83
29003
29004 @noindent
29005 The VMS version of GNAT fully implements all the pragmas and attributes
29006 provided by HP Ada 83, as well as providing the standard HP Ada 83
29007 libraries, including Starlet. In addition, data layouts and parameter
29008 passing conventions are highly compatible. This means that porting
29009 existing HP Ada 83 code to GNAT in VMS systems should be easier than
29010 most other porting efforts. The following are some of the most
29011 significant differences between GNAT and HP Ada 83.
29012
29013 @table @emph
29014 @item Default floating-point representation
29015 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
29016 it is VMS format. GNAT does implement the necessary pragmas
29017 (Long_Float, Float_Representation) for changing this default.
29018
29019 @item System
29020 The package System in GNAT exactly corresponds to the definition in the
29021 Ada 95 reference manual, which means that it excludes many of the
29022 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
29023 that contains the additional definitions, and a special pragma,
29024 Extend_System allows this package to be treated transparently as an
29025 extension of package System.
29026
29027 @item To_Address
29028 The definitions provided by Aux_DEC are exactly compatible with those
29029 in the HP Ada 83 version of System, with one exception.
29030 HP Ada provides the following declarations:
29031
29032 @smallexample @c ada
29033 TO_ADDRESS (INTEGER)
29034 TO_ADDRESS (UNSIGNED_LONGWORD)
29035 TO_ADDRESS (@i{universal_integer})
29036 @end smallexample
29037
29038 @noindent
29039 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
29040 an extension to Ada 83 not strictly compatible with the reference manual.
29041 In GNAT, we are constrained to be exactly compatible with the standard,
29042 and this means we cannot provide this capability. In HP Ada 83, the
29043 point of this definition is to deal with a call like:
29044
29045 @smallexample @c ada
29046 TO_ADDRESS (16#12777#);
29047 @end smallexample
29048
29049 @noindent
29050 Normally, according to the Ada 83 standard, one would expect this to be
29051 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
29052 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
29053 definition using @i{universal_integer} takes precedence.
29054
29055 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
29056 is not possible to be 100% compatible. Since there are many programs using
29057 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
29058 to change the name of the function in the UNSIGNED_LONGWORD case, so the
29059 declarations provided in the GNAT version of AUX_Dec are:
29060
29061 @smallexample @c ada
29062 function To_Address (X : Integer) return Address;
29063 pragma Pure_Function (To_Address);
29064
29065 function To_Address_Long (X : Unsigned_Longword)
29066 return Address;
29067 pragma Pure_Function (To_Address_Long);
29068 @end smallexample
29069
29070 @noindent
29071 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
29072 change the name to TO_ADDRESS_LONG@.
29073
29074 @item Task_Id values
29075 The Task_Id values assigned will be different in the two systems, and GNAT
29076 does not provide a specified value for the Task_Id of the environment task,
29077 which in GNAT is treated like any other declared task.
29078 @end table
29079
29080 @noindent
29081 For full details on these and other less significant compatibility issues,
29082 see appendix E of the HP publication entitled @cite{HP Ada, Technical
29083 Overview and Comparison on HP Platforms}.
29084
29085 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
29086 attributes are recognized, although only a subset of them can sensibly
29087 be implemented. The description of pragmas in @ref{Implementation
29088 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
29089 indicates whether or not they are applicable to non-VMS systems.
29090 @end ifclear
29091
29092 @ifset vms
29093 @node Transitioning to 64-Bit GNAT for OpenVMS
29094 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
29095
29096 @noindent
29097 This section is meant to assist users of pre-2006 @value{EDITION}
29098 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
29099 the version of the GNAT technology supplied in 2006 and later for
29100 OpenVMS on both Alpha and I64.
29101
29102 @menu
29103 * Introduction to transitioning::
29104 * Migration of 32 bit code::
29105 * Taking advantage of 64 bit addressing::
29106 * Technical details::
29107 @end menu
29108
29109 @node Introduction to transitioning
29110 @subsection Introduction
29111
29112 @noindent
29113 64-bit @value{EDITION} for Open VMS has been designed to meet
29114 three main goals:
29115
29116 @enumerate
29117 @item
29118 Providing a full conforming implementation of Ada 95 and Ada 2005
29119
29120 @item
29121 Allowing maximum backward compatibility, thus easing migration of existing
29122 Ada source code
29123
29124 @item
29125 Supplying a path for exploiting the full 64-bit address range
29126 @end enumerate
29127
29128 @noindent
29129 Ada's strong typing semantics has made it
29130 impractical to have different 32-bit and 64-bit modes. As soon as
29131 one object could possibly be outside the 32-bit address space, this
29132 would make it necessary for the @code{System.Address} type to be 64 bits.
29133 In particular, this would cause inconsistencies if 32-bit code is
29134 called from 64-bit code that raises an exception.
29135
29136 This issue has been resolved by always using 64-bit addressing
29137 at the system level, but allowing for automatic conversions between
29138 32-bit and 64-bit addresses where required. Thus users who
29139 do not currently require 64-bit addressing capabilities, can
29140 recompile their code with only minimal changes (and indeed
29141 if the code is written in portable Ada, with no assumptions about
29142 the size of the @code{Address} type, then no changes at all are necessary).
29143 At the same time,
29144 this approach provides a simple, gradual upgrade path to future
29145 use of larger memories than available for 32-bit systems.
29146 Also, newly written applications or libraries will by default
29147 be fully compatible with future systems exploiting 64-bit
29148 addressing capabilities.
29149
29150 @ref{Migration of 32 bit code}, will focus on porting applications
29151 that do not require more than 2 GB of
29152 addressable memory. This code will be referred to as
29153 @emph{32-bit code}.
29154 For applications intending to exploit the full 64-bit address space,
29155 @ref{Taking advantage of 64 bit addressing},
29156 will consider further changes that may be required.
29157 Such code will be referred to below as @emph{64-bit code}.
29158
29159 @node Migration of 32 bit code
29160 @subsection Migration of 32-bit code
29161
29162 @menu
29163 * Address types::
29164 * Access types and 32/64-bit allocation::
29165 * Unchecked conversions::
29166 * Predefined constants::
29167 * Interfacing with C::
29168 * 32/64-bit descriptors::
29169 * Experience with source compatibility::
29170 @end menu
29171
29172 @node Address types
29173 @subsubsection Address types
29174
29175 @noindent
29176 To solve the problem of mixing 64-bit and 32-bit addressing,
29177 while maintaining maximum backward compatibility, the following
29178 approach has been taken:
29179
29180 @itemize @bullet
29181 @item
29182 @code{System.Address} always has a size of 64 bits
29183 @cindex @code{System.Address} size
29184 @cindex @code{Address} size
29185
29186 @item
29187 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
29188 @cindex @code{System.Short_Address} size
29189 @cindex @code{Short_Address} size
29190 @end itemize
29191
29192 @noindent
29193 Since @code{System.Short_Address} is a subtype of @code{System.Address},
29194 a @code{Short_Address}
29195 may be used where an @code{Address} is required, and vice versa, without
29196 needing explicit type conversions.
29197 By virtue of the Open VMS parameter passing conventions,
29198 even imported
29199 and exported subprograms that have 32-bit address parameters are
29200 compatible with those that have 64-bit address parameters.
29201 (See @ref{Making code 64 bit clean} for details.)
29202
29203 The areas that may need attention are those where record types have
29204 been defined that contain components of the type @code{System.Address}, and
29205 where objects of this type are passed to code expecting a record layout with
29206 32-bit addresses.
29207
29208 Different compilers on different platforms cannot be
29209 expected to represent the same type in the same way,
29210 since alignment constraints
29211 and other system-dependent properties affect the compiler's decision.
29212 For that reason, Ada code
29213 generally uses representation clauses to specify the expected
29214 layout where required.
29215
29216 If such a representation clause uses 32 bits for a component having
29217 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
29218 will detect that error and produce a specific diagnostic message.
29219 The developer should then determine whether the representation
29220 should be 64 bits or not and make either of two changes:
29221 change the size to 64 bits and leave the type as @code{System.Address}, or
29222 leave the size as 32 bits and change the type to @code{System.Short_Address}.
29223 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
29224 required in any code setting or accessing the field; the compiler will
29225 automatically perform any needed conversions between address
29226 formats.
29227
29228 @node Access types and 32/64-bit allocation
29229 @subsubsection Access types and 32/64-bit allocation
29230 @cindex 32-bit allocation
29231 @cindex 64-bit allocation
29232
29233 @noindent
29234 By default, objects designated by access values are always allocated in
29235 the 64-bit address space, and access values themselves are represented
29236 in 64 bits. If these defaults are not appropriate, and 32-bit allocation
29237 is required (for example if the address of an allocated object is assigned
29238 to a @code{Short_Address} variable), then several alternatives are available:
29239
29240 @itemize @bullet
29241 @item
29242 A pool-specific access type (ie, an @w{Ada 83} access type, whose
29243 definition is @code{access T} versus @code{access all T} or
29244 @code{access constant T}), may be declared with a @code{'Size} representation
29245 clause that establishes the size as 32 bits.
29246 In such circumstances allocations for that type will
29247 be from the 32-bit heap. Such a clause is not permitted
29248 for a general access type (declared with @code{access all} or
29249 @code{access constant}) as values of such types must be able to refer
29250 to any object of the designated type, including objects residing outside
29251 the 32-bit address range. Existing @w{Ada 83} code will not contain such
29252 type definitions, however, since general access types were introduced
29253 in @w{Ada 95}.
29254
29255 @item
29256 Switches for @command{GNAT BIND} control whether the internal GNAT
29257 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
29258 @cindex @code{__gnat_malloc}
29259 The switches are respectively @option{-H64} (the default) and
29260 @option{-H32}.
29261 @cindex @option{-H32} (@command{gnatbind})
29262 @cindex @option{-H64} (@command{gnatbind})
29263
29264 @item
29265 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
29266 @cindex @code{GNAT$NO_MALLOC_64} environment variable
29267 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
29268 If this variable is left
29269 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
29270 then the default (64-bit) allocation is used.
29271 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
29272 then 32-bit allocation is used. The gnatbind qualifiers described above
29273 override this logical name.
29274
29275 @item
29276 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
29277 @cindex @option{-mno-malloc64} (^gcc^gcc^)
29278 at a low level to convert explicit calls to @code{malloc} and related
29279 functions from the C run-time library so that they perform allocations
29280 in the 32-bit heap.
29281 Since all internal allocations from GNAT use @code{__gnat_malloc},
29282 this switch is not required unless the program makes explicit calls on
29283 @code{malloc} (or related functions) from interfaced C code.
29284 @end itemize
29285
29286
29287 @node Unchecked conversions
29288 @subsubsection Unchecked conversions
29289
29290 @noindent
29291 In the case of an @code{Unchecked_Conversion} where the source type is a
29292 64-bit access type or the type @code{System.Address}, and the target
29293 type is a 32-bit type, the compiler will generate a warning.
29294 Even though the generated code will still perform the required
29295 conversions, it is highly recommended in these cases to use
29296 respectively a 32-bit access type or @code{System.Short_Address}
29297 as the source type.
29298
29299 @node Predefined constants
29300 @subsubsection Predefined constants
29301
29302 @noindent
29303 The following table shows the correspondence between pre-2006 versions of
29304 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
29305 (``New''):
29306
29307 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
29308 @item @b{Constant} @tab @b{Old} @tab @b{New}
29309 @item @code{System.Word_Size} @tab 32 @tab 64
29310 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
29311 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
29312 @item @code{System.Address_Size} @tab 32 @tab 64
29313 @end multitable
29314
29315 @noindent
29316 If you need to refer to the specific
29317 memory size of a 32-bit implementation, instead of the
29318 actual memory size, use @code{System.Short_Memory_Size}
29319 rather than @code{System.Memory_Size}.
29320 Similarly, references to @code{System.Address_Size} may need
29321 to be replaced by @code{System.Short_Address'Size}.
29322 The program @command{gnatfind} may be useful for locating
29323 references to the above constants, so that you can verify that they
29324 are still correct.
29325
29326 @node Interfacing with C
29327 @subsubsection Interfacing with C
29328
29329 @noindent
29330 In order to minimize the impact of the transition to 64-bit addresses on
29331 legacy programs, some fundamental types in the @code{Interfaces.C}
29332 package hierarchy continue to be represented in 32 bits.
29333 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
29334 This eases integration with the default HP C layout choices, for example
29335 as found in the system routines in @code{DECC$SHR.EXE}.
29336 Because of this implementation choice, the type fully compatible with
29337 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
29338 Depending on the context the compiler will issue a
29339 warning or an error when type @code{Address} is used, alerting the user to a
29340 potential problem. Otherwise 32-bit programs that use
29341 @code{Interfaces.C} should normally not require code modifications
29342
29343 The other issue arising with C interfacing concerns pragma @code{Convention}.
29344 For VMS 64-bit systems, there is an issue of the appropriate default size
29345 of C convention pointers in the absence of an explicit size clause. The HP
29346 C compiler can choose either 32 or 64 bits depending on compiler options.
29347 GNAT chooses 32-bits rather than 64-bits in the default case where no size
29348 clause is given. This proves a better choice for porting 32-bit legacy
29349 applications. In order to have a 64-bit representation, it is necessary to
29350 specify a size representation clause. For example:
29351
29352 @smallexample @c ada
29353 type int_star is access Interfaces.C.int;
29354 pragma Convention(C, int_star);
29355 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
29356 @end smallexample
29357
29358 @node 32/64-bit descriptors
29359 @subsubsection 32/64-bit descriptors
29360
29361 @noindent
29362 By default, GNAT uses a 64-bit descriptor mechanism. For an imported
29363 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
29364 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
29365 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
29366 @cindex @code{Short_Descriptor} mechanism for imported subprograms
29367
29368 If the configuration pragma @code{Short_Descriptors} is supplied, then
29369 all descriptors will be 32 bits.
29370 @cindex pragma @code{Short_Descriptors}
29371
29372 @node Experience with source compatibility
29373 @subsubsection Experience with source compatibility
29374
29375 @noindent
29376 The Security Server and STARLET on I64 provide an interesting ``test case''
29377 for source compatibility issues, since it is in such system code
29378 where assumptions about @code{Address} size might be expected to occur.
29379 Indeed, there were a small number of occasions in the Security Server
29380 file @file{jibdef.ads}
29381 where a representation clause for a record type specified
29382 32 bits for a component of type @code{Address}.
29383 All of these errors were detected by the compiler.
29384 The repair was obvious and immediate; to simply replace @code{Address} by
29385 @code{Short_Address}.
29386
29387 In the case of STARLET, there were several record types that should
29388 have had representation clauses but did not. In these record types
29389 there was an implicit assumption that an @code{Address} value occupied
29390 32 bits.
29391 These compiled without error, but their usage resulted in run-time error
29392 returns from STARLET system calls.
29393 Future GNAT technology enhancements may include a tool that detects and flags
29394 these sorts of potential source code porting problems.
29395
29396 @c ****************************************
29397 @node Taking advantage of 64 bit addressing
29398 @subsection Taking advantage of 64-bit addressing
29399
29400 @menu
29401 * Making code 64 bit clean::
29402 * Allocating memory from the 64 bit storage pool::
29403 * Restrictions on use of 64 bit objects::
29404 * STARLET and other predefined libraries::
29405 @end menu
29406
29407 @node Making code 64 bit clean
29408 @subsubsection Making code 64-bit clean
29409
29410 @noindent
29411 In order to prevent problems that may occur when (parts of) a
29412 system start using memory outside the 32-bit address range,
29413 we recommend some additional guidelines:
29414
29415 @itemize @bullet
29416 @item
29417 For imported subprograms that take parameters of the
29418 type @code{System.Address}, ensure that these subprograms can
29419 indeed handle 64-bit addresses. If not, or when in doubt,
29420 change the subprogram declaration to specify
29421 @code{System.Short_Address} instead.
29422
29423 @item
29424 Resolve all warnings related to size mismatches in
29425 unchecked conversions. Failing to do so causes
29426 erroneous execution if the source object is outside
29427 the 32-bit address space.
29428
29429 @item
29430 (optional) Explicitly use the 32-bit storage pool
29431 for access types used in a 32-bit context, or use
29432 generic access types where possible
29433 (@pxref{Restrictions on use of 64 bit objects}).
29434 @end itemize
29435
29436 @noindent
29437 If these rules are followed, the compiler will automatically insert
29438 any necessary checks to ensure that no addresses or access values
29439 passed to 32-bit code ever refer to objects outside the 32-bit
29440 address range.
29441 Any attempt to do this will raise @code{Constraint_Error}.
29442
29443 @node Allocating memory from the 64 bit storage pool
29444 @subsubsection Allocating memory from the 64-bit storage pool
29445
29446 @noindent
29447 By default, all allocations -- for both pool-specific and general
29448 access types -- use the 64-bit storage pool. To override
29449 this default, for an individual access type or globally, see
29450 @ref{Access types and 32/64-bit allocation}.
29451
29452 @node Restrictions on use of 64 bit objects
29453 @subsubsection Restrictions on use of 64-bit objects
29454
29455 @noindent
29456 Taking the address of an object allocated from a 64-bit storage pool,
29457 and then passing this address to a subprogram expecting
29458 @code{System.Short_Address},
29459 or assigning it to a variable of type @code{Short_Address}, will cause
29460 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
29461 (@pxref{Making code 64 bit clean}), or checks are suppressed,
29462 no exception is raised and execution
29463 will become erroneous.
29464
29465 @node STARLET and other predefined libraries
29466 @subsubsection STARLET and other predefined libraries
29467
29468 @noindent
29469 All code that comes as part of GNAT is 64-bit clean, but the
29470 restrictions given in @ref{Restrictions on use of 64 bit objects},
29471 still apply. Look at the package
29472 specs to see in which contexts objects allocated
29473 in 64-bit address space are acceptable.
29474
29475 @node Technical details
29476 @subsection Technical details
29477
29478 @noindent
29479 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
29480 Ada standard with respect to the type of @code{System.Address}. Previous
29481 versions of @value{EDITION} have defined this type as private and implemented it as a
29482 modular type.
29483
29484 In order to allow defining @code{System.Short_Address} as a proper subtype,
29485 and to match the implicit sign extension in parameter passing,
29486 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
29487 visible (i.e., non-private) integer type.
29488 Standard operations on the type, such as the binary operators ``+'', ``-'',
29489 etc., that take @code{Address} operands and return an @code{Address} result,
29490 have been hidden by declaring these
29491 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
29492 ambiguities that would otherwise result from overloading.
29493 (Note that, although @code{Address} is a visible integer type,
29494 good programming practice dictates against exploiting the type's
29495 integer properties such as literals, since this will compromise
29496 code portability.)
29497
29498 Defining @code{Address} as a visible integer type helps achieve
29499 maximum compatibility for existing Ada code,
29500 without sacrificing the capabilities of the 64-bit architecture.
29501 @end ifset
29502
29503 @c ************************************************
29504 @node Microsoft Windows Topics
29505 @appendix Microsoft Windows Topics
29506 @cindex Windows NT
29507 @cindex Windows 95
29508 @cindex Windows 98
29509
29510 @noindent
29511 This chapter describes topics that are specific to the Microsoft Windows
29512 platforms (NT, 2000, and XP Professional).
29513
29514 @menu
29515 @ifclear FSFEDITION
29516 * Installing from the Command Line::
29517 @end ifclear
29518 * Using GNAT on Windows::
29519 * Using a network installation of GNAT::
29520 * CONSOLE and WINDOWS subsystems::
29521 * Temporary Files::
29522 * Mixed-Language Programming on Windows::
29523 * Windows Calling Conventions::
29524 * Introduction to Dynamic Link Libraries (DLLs)::
29525 * Using DLLs with GNAT::
29526 * Building DLLs with GNAT Project files::
29527 * Building DLLs with GNAT::
29528 * Building DLLs with gnatdll::
29529 * GNAT and Windows Resources::
29530 * Debugging a DLL::
29531 * Setting Stack Size from gnatlink::
29532 * Setting Heap Size from gnatlink::
29533 @end menu
29534
29535 @ifclear FSFEDITION
29536 @node Installing from the Command Line
29537 @section Installing from the Command Line
29538 @cindex Batch installation
29539 @cindex Silent installation
29540 @cindex Unassisted installation
29541
29542 @noindent
29543 By default the @value{EDITION} installers display a GUI that prompts the user
29544 to enter installation path and similar information, and guide him through the
29545 installation process. It is also possible to perform silent installations
29546 using the command-line interface.
29547
29548 In order to install one of the @value{EDITION} installers from the command
29549 line you should pass parameter @code{/S} (and, optionally,
29550 @code{/D=<directory>}) as command-line arguments.
29551
29552 @ifset PROEDITION
29553 For example, for an unattended installation of
29554 @value{EDITION} 7.0.2 into the default directory
29555 @code{C:\GNATPRO\7.0.2} you would run:
29556
29557 @smallexample
29558 gnatpro-7.0.2-i686-pc-mingw32-bin.exe /S
29559 @end smallexample
29560
29561 To install into a custom directory, say, @code{C:\TOOLS\GNATPRO\7.0.2}:
29562
29563 @smallexample
29564 gnatpro-7.0.2-i686-pc-mingw32-bin /S /D=C:\TOOLS\GNATPRO\7.0.2
29565 @end smallexample
29566 @end ifset
29567
29568 @ifset GPLEDITION
29569 For example, for an unattended installation of
29570 @value{EDITION} 2012 into @code{C:\GNAT\2012}:
29571
29572 @smallexample
29573 gnat-gpl-2012-i686-pc-mingw32-bin /S /D=C:\GNAT\2012
29574 @end smallexample
29575 @end ifset
29576
29577 You can use the same syntax for all installers.
29578
29579 Note that unattended installations don't modify system path, nor create file
29580 associations, so such activities need to be done by hand.
29581 @end ifclear
29582
29583 @node Using GNAT on Windows
29584 @section Using GNAT on Windows
29585
29586 @noindent
29587 One of the strengths of the GNAT technology is that its tool set
29588 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
29589 @code{gdb} debugger, etc.) is used in the same way regardless of the
29590 platform.
29591
29592 On Windows this tool set is complemented by a number of Microsoft-specific
29593 tools that have been provided to facilitate interoperability with Windows
29594 when this is required. With these tools:
29595
29596 @itemize @bullet
29597
29598 @item
29599 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
29600 subsystems.
29601
29602 @item
29603 You can use any Dynamically Linked Library (DLL) in your Ada code (both
29604 relocatable and non-relocatable DLLs are supported).
29605
29606 @item
29607 You can build Ada DLLs for use in other applications. These applications
29608 can be written in a language other than Ada (e.g., C, C++, etc). Again both
29609 relocatable and non-relocatable Ada DLLs are supported.
29610
29611 @item
29612 You can include Windows resources in your Ada application.
29613
29614 @item
29615 You can use or create COM/DCOM objects.
29616 @end itemize
29617
29618 @noindent
29619 Immediately below are listed all known general GNAT-for-Windows restrictions.
29620 Other restrictions about specific features like Windows Resources and DLLs
29621 are listed in separate sections below.
29622
29623 @itemize @bullet
29624
29625 @item
29626 It is not possible to use @code{GetLastError} and @code{SetLastError}
29627 when tasking, protected records, or exceptions are used. In these
29628 cases, in order to implement Ada semantics, the GNAT run-time system
29629 calls certain Win32 routines that set the last error variable to 0 upon
29630 success. It should be possible to use @code{GetLastError} and
29631 @code{SetLastError} when tasking, protected record, and exception
29632 features are not used, but it is not guaranteed to work.
29633
29634 @item
29635 It is not possible to link against Microsoft C++ libraries except for
29636 import libraries. Interfacing must be done by the mean of DLLs.
29637
29638 @item
29639 It is possible to link against Microsoft C libraries. Yet the preferred
29640 solution is to use C/C++ compiler that comes with @value{EDITION}, since it
29641 doesn't require having two different development environments and makes the
29642 inter-language debugging experience smoother.
29643
29644 @item
29645 When the compilation environment is located on FAT32 drives, users may
29646 experience recompilations of the source files that have not changed if
29647 Daylight Saving Time (DST) state has changed since the last time files
29648 were compiled. NTFS drives do not have this problem.
29649
29650 @item
29651 No components of the GNAT toolset use any entries in the Windows
29652 registry. The only entries that can be created are file associations and
29653 PATH settings, provided the user has chosen to create them at installation
29654 time, as well as some minimal book-keeping information needed to correctly
29655 uninstall or integrate different GNAT products.
29656 @end itemize
29657
29658 @node Using a network installation of GNAT
29659 @section Using a network installation of GNAT
29660
29661 @noindent
29662 Make sure the system on which GNAT is installed is accessible from the
29663 current machine, i.e., the install location is shared over the network.
29664 Shared resources are accessed on Windows by means of UNC paths, which
29665 have the format @code{\\server\sharename\path}
29666
29667 In order to use such a network installation, simply add the UNC path of the
29668 @file{bin} directory of your GNAT installation in front of your PATH. For
29669 example, if GNAT is installed in @file{\GNAT} directory of a share location
29670 called @file{c-drive} on a machine @file{LOKI}, the following command will
29671 make it available:
29672
29673 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
29674
29675 Be aware that every compilation using the network installation results in the
29676 transfer of large amounts of data across the network and will likely cause
29677 serious performance penalty.
29678
29679 @node CONSOLE and WINDOWS subsystems
29680 @section CONSOLE and WINDOWS subsystems
29681 @cindex CONSOLE Subsystem
29682 @cindex WINDOWS Subsystem
29683 @cindex -mwindows
29684
29685 @noindent
29686 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
29687 (which is the default subsystem) will always create a console when
29688 launching the application. This is not something desirable when the
29689 application has a Windows GUI. To get rid of this console the
29690 application must be using the @code{WINDOWS} subsystem. To do so
29691 the @option{-mwindows} linker option must be specified.
29692
29693 @smallexample
29694 $ gnatmake winprog -largs -mwindows
29695 @end smallexample
29696
29697 @node Temporary Files
29698 @section Temporary Files
29699 @cindex Temporary files
29700
29701 @noindent
29702 It is possible to control where temporary files gets created by setting
29703 the @env{TMP} environment variable. The file will be created:
29704
29705 @itemize
29706 @item Under the directory pointed to by the @env{TMP} environment variable if
29707 this directory exists.
29708
29709 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
29710 set (or not pointing to a directory) and if this directory exists.
29711
29712 @item Under the current working directory otherwise.
29713 @end itemize
29714
29715 @noindent
29716 This allows you to determine exactly where the temporary
29717 file will be created. This is particularly useful in networked
29718 environments where you may not have write access to some
29719 directories.
29720
29721 @node Mixed-Language Programming on Windows
29722 @section Mixed-Language Programming on Windows
29723
29724 @noindent
29725 Developing pure Ada applications on Windows is no different than on
29726 other GNAT-supported platforms. However, when developing or porting an
29727 application that contains a mix of Ada and C/C++, the choice of your
29728 Windows C/C++ development environment conditions your overall
29729 interoperability strategy.
29730
29731 If you use @command{gcc} or Microsoft C to compile the non-Ada part of
29732 your application, there are no Windows-specific restrictions that
29733 affect the overall interoperability with your Ada code. If you do want
29734 to use the Microsoft tools for your C++ code, you have two choices:
29735
29736 @enumerate
29737 @item
29738 Encapsulate your C++ code in a DLL to be linked with your Ada
29739 application. In this case, use the Microsoft or whatever environment to
29740 build the DLL and use GNAT to build your executable
29741 (@pxref{Using DLLs with GNAT}).
29742
29743 @item
29744 Or you can encapsulate your Ada code in a DLL to be linked with the
29745 other part of your application. In this case, use GNAT to build the DLL
29746 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
29747 or whatever environment to build your executable.
29748 @end enumerate
29749
29750 In addition to the description about C main in
29751 @pxref{Mixed Language Programming} section, if the C main uses a
29752 stand-alone library it is required on x86-windows to
29753 setup the SEH context. For this the C main must looks like this:
29754
29755 @smallexample
29756 /* main.c */
29757 extern void adainit (void);
29758 extern void adafinal (void);
29759 extern void __gnat_initialize(void*);
29760 extern void call_to_ada (void);
29761
29762 int main (int argc, char *argv[])
29763 @{
29764 int SEH [2];
29765
29766 /* Initialize the SEH context */
29767 __gnat_initialize (&SEH);
29768
29769 adainit();
29770
29771 /* Then call Ada services in the stand-alone library */
29772
29773 call_to_ada();
29774
29775 adafinal();
29776 @}
29777 @end smallexample
29778
29779 Note that this is not needed on x86_64-windows where the Windows
29780 native SEH support is used.
29781
29782 @node Windows Calling Conventions
29783 @section Windows Calling Conventions
29784 @findex Stdcall
29785 @findex APIENTRY
29786
29787 This section pertain only to Win32. On Win64 there is a single native
29788 calling convention. All convention specifiers are ignored on this
29789 platform.
29790
29791 @menu
29792 * C Calling Convention::
29793 * Stdcall Calling Convention::
29794 * Win32 Calling Convention::
29795 * DLL Calling Convention::
29796 @end menu
29797
29798 @noindent
29799 When a subprogram @code{F} (caller) calls a subprogram @code{G}
29800 (callee), there are several ways to push @code{G}'s parameters on the
29801 stack and there are several possible scenarios to clean up the stack
29802 upon @code{G}'s return. A calling convention is an agreed upon software
29803 protocol whereby the responsibilities between the caller (@code{F}) and
29804 the callee (@code{G}) are clearly defined. Several calling conventions
29805 are available for Windows:
29806
29807 @itemize @bullet
29808 @item
29809 @code{C} (Microsoft defined)
29810
29811 @item
29812 @code{Stdcall} (Microsoft defined)
29813
29814 @item
29815 @code{Win32} (GNAT specific)
29816
29817 @item
29818 @code{DLL} (GNAT specific)
29819 @end itemize
29820
29821 @node C Calling Convention
29822 @subsection @code{C} Calling Convention
29823
29824 @noindent
29825 This is the default calling convention used when interfacing to C/C++
29826 routines compiled with either @command{gcc} or Microsoft Visual C++.
29827
29828 In the @code{C} calling convention subprogram parameters are pushed on the
29829 stack by the caller from right to left. The caller itself is in charge of
29830 cleaning up the stack after the call. In addition, the name of a routine
29831 with @code{C} calling convention is mangled by adding a leading underscore.
29832
29833 The name to use on the Ada side when importing (or exporting) a routine
29834 with @code{C} calling convention is the name of the routine. For
29835 instance the C function:
29836
29837 @smallexample
29838 int get_val (long);
29839 @end smallexample
29840
29841 @noindent
29842 should be imported from Ada as follows:
29843
29844 @smallexample @c ada
29845 @group
29846 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29847 pragma Import (C, Get_Val, External_Name => "get_val");
29848 @end group
29849 @end smallexample
29850
29851 @noindent
29852 Note that in this particular case the @code{External_Name} parameter could
29853 have been omitted since, when missing, this parameter is taken to be the
29854 name of the Ada entity in lower case. When the @code{Link_Name} parameter
29855 is missing, as in the above example, this parameter is set to be the
29856 @code{External_Name} with a leading underscore.
29857
29858 When importing a variable defined in C, you should always use the @code{C}
29859 calling convention unless the object containing the variable is part of a
29860 DLL (in which case you should use the @code{Stdcall} calling
29861 convention, @pxref{Stdcall Calling Convention}).
29862
29863 @node Stdcall Calling Convention
29864 @subsection @code{Stdcall} Calling Convention
29865
29866 @noindent
29867 This convention, which was the calling convention used for Pascal
29868 programs, is used by Microsoft for all the routines in the Win32 API for
29869 efficiency reasons. It must be used to import any routine for which this
29870 convention was specified.
29871
29872 In the @code{Stdcall} calling convention subprogram parameters are pushed
29873 on the stack by the caller from right to left. The callee (and not the
29874 caller) is in charge of cleaning the stack on routine exit. In addition,
29875 the name of a routine with @code{Stdcall} calling convention is mangled by
29876 adding a leading underscore (as for the @code{C} calling convention) and a
29877 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
29878 bytes) of the parameters passed to the routine.
29879
29880 The name to use on the Ada side when importing a C routine with a
29881 @code{Stdcall} calling convention is the name of the C routine. The leading
29882 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
29883 the compiler. For instance the Win32 function:
29884
29885 @smallexample
29886 @b{APIENTRY} int get_val (long);
29887 @end smallexample
29888
29889 @noindent
29890 should be imported from Ada as follows:
29891
29892 @smallexample @c ada
29893 @group
29894 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29895 pragma Import (Stdcall, Get_Val);
29896 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
29897 @end group
29898 @end smallexample
29899
29900 @noindent
29901 As for the @code{C} calling convention, when the @code{External_Name}
29902 parameter is missing, it is taken to be the name of the Ada entity in lower
29903 case. If instead of writing the above import pragma you write:
29904
29905 @smallexample @c ada
29906 @group
29907 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29908 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
29909 @end group
29910 @end smallexample
29911
29912 @noindent
29913 then the imported routine is @code{_retrieve_val@@4}. However, if instead
29914 of specifying the @code{External_Name} parameter you specify the
29915 @code{Link_Name} as in the following example:
29916
29917 @smallexample @c ada
29918 @group
29919 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29920 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
29921 @end group
29922 @end smallexample
29923
29924 @noindent
29925 then the imported routine is @code{retrieve_val}, that is, there is no
29926 decoration at all. No leading underscore and no Stdcall suffix
29927 @code{@@}@code{@var{nn}}.
29928
29929 @noindent
29930 This is especially important as in some special cases a DLL's entry
29931 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
29932 name generated for a call has it.
29933
29934 @noindent
29935 It is also possible to import variables defined in a DLL by using an
29936 import pragma for a variable. As an example, if a DLL contains a
29937 variable defined as:
29938
29939 @smallexample
29940 int my_var;
29941 @end smallexample
29942
29943 @noindent
29944 then, to access this variable from Ada you should write:
29945
29946 @smallexample @c ada
29947 @group
29948 My_Var : Interfaces.C.int;
29949 pragma Import (Stdcall, My_Var);
29950 @end group
29951 @end smallexample
29952
29953 @noindent
29954 Note that to ease building cross-platform bindings this convention
29955 will be handled as a @code{C} calling convention on non-Windows platforms.
29956
29957 @node Win32 Calling Convention
29958 @subsection @code{Win32} Calling Convention
29959
29960 @noindent
29961 This convention, which is GNAT-specific is fully equivalent to the
29962 @code{Stdcall} calling convention described above.
29963
29964 @node DLL Calling Convention
29965 @subsection @code{DLL} Calling Convention
29966
29967 @noindent
29968 This convention, which is GNAT-specific is fully equivalent to the
29969 @code{Stdcall} calling convention described above.
29970
29971 @node Introduction to Dynamic Link Libraries (DLLs)
29972 @section Introduction to Dynamic Link Libraries (DLLs)
29973 @findex DLL
29974
29975 @noindent
29976 A Dynamically Linked Library (DLL) is a library that can be shared by
29977 several applications running under Windows. A DLL can contain any number of
29978 routines and variables.
29979
29980 One advantage of DLLs is that you can change and enhance them without
29981 forcing all the applications that depend on them to be relinked or
29982 recompiled. However, you should be aware than all calls to DLL routines are
29983 slower since, as you will understand below, such calls are indirect.
29984
29985 To illustrate the remainder of this section, suppose that an application
29986 wants to use the services of a DLL @file{API.dll}. To use the services
29987 provided by @file{API.dll} you must statically link against the DLL or
29988 an import library which contains a jump table with an entry for each
29989 routine and variable exported by the DLL. In the Microsoft world this
29990 import library is called @file{API.lib}. When using GNAT this import
29991 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
29992 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
29993
29994 After you have linked your application with the DLL or the import library
29995 and you run your application, here is what happens:
29996
29997 @enumerate
29998 @item
29999 Your application is loaded into memory.
30000
30001 @item
30002 The DLL @file{API.dll} is mapped into the address space of your
30003 application. This means that:
30004
30005 @itemize @bullet
30006 @item
30007 The DLL will use the stack of the calling thread.
30008
30009 @item
30010 The DLL will use the virtual address space of the calling process.
30011
30012 @item
30013 The DLL will allocate memory from the virtual address space of the calling
30014 process.
30015
30016 @item
30017 Handles (pointers) can be safely exchanged between routines in the DLL
30018 routines and routines in the application using the DLL.
30019 @end itemize
30020
30021 @item
30022 The entries in the jump table (from the import library @file{libAPI.dll.a}
30023 or @file{API.lib} or automatically created when linking against a DLL)
30024 which is part of your application are initialized with the addresses
30025 of the routines and variables in @file{API.dll}.
30026
30027 @item
30028 If present in @file{API.dll}, routines @code{DllMain} or
30029 @code{DllMainCRTStartup} are invoked. These routines typically contain
30030 the initialization code needed for the well-being of the routines and
30031 variables exported by the DLL.
30032 @end enumerate
30033
30034 @noindent
30035 There is an additional point which is worth mentioning. In the Windows
30036 world there are two kind of DLLs: relocatable and non-relocatable
30037 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
30038 in the target application address space. If the addresses of two
30039 non-relocatable DLLs overlap and these happen to be used by the same
30040 application, a conflict will occur and the application will run
30041 incorrectly. Hence, when possible, it is always preferable to use and
30042 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
30043 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
30044 User's Guide) removes the debugging symbols from the DLL but the DLL can
30045 still be relocated.
30046
30047 As a side note, an interesting difference between Microsoft DLLs and
30048 Unix shared libraries, is the fact that on most Unix systems all public
30049 routines are exported by default in a Unix shared library, while under
30050 Windows it is possible (but not required) to list exported routines in
30051 a definition file (@pxref{The Definition File}).
30052
30053 @node Using DLLs with GNAT
30054 @section Using DLLs with GNAT
30055
30056 @menu
30057 * Creating an Ada Spec for the DLL Services::
30058 * Creating an Import Library::
30059 @end menu
30060
30061 @noindent
30062 To use the services of a DLL, say @file{API.dll}, in your Ada application
30063 you must have:
30064
30065 @enumerate
30066 @item
30067 The Ada spec for the routines and/or variables you want to access in
30068 @file{API.dll}. If not available this Ada spec must be built from the C/C++
30069 header files provided with the DLL.
30070
30071 @item
30072 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
30073 mentioned an import library is a statically linked library containing the
30074 import table which will be filled at load time to point to the actual
30075 @file{API.dll} routines. Sometimes you don't have an import library for the
30076 DLL you want to use. The following sections will explain how to build
30077 one. Note that this is optional.
30078
30079 @item
30080 The actual DLL, @file{API.dll}.
30081 @end enumerate
30082
30083 @noindent
30084 Once you have all the above, to compile an Ada application that uses the
30085 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
30086 you simply issue the command
30087
30088 @smallexample
30089 $ gnatmake my_ada_app -largs -lAPI
30090 @end smallexample
30091
30092 @noindent
30093 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
30094 tells the GNAT linker to look for an import library. The linker will
30095 look for a library name in this specific order:
30096
30097 @enumerate
30098 @item @file{libAPI.dll.a}
30099 @item @file{API.dll.a}
30100 @item @file{libAPI.a}
30101 @item @file{API.lib}
30102 @item @file{libAPI.dll}
30103 @item @file{API.dll}
30104 @end enumerate
30105
30106 The first three are the GNU style import libraries. The third is the
30107 Microsoft style import libraries. The last two are the actual DLL names.
30108
30109 Note that if the Ada package spec for @file{API.dll} contains the
30110 following pragma
30111
30112 @smallexample @c ada
30113 pragma Linker_Options ("-lAPI");
30114 @end smallexample
30115
30116 @noindent
30117 you do not have to add @option{-largs -lAPI} at the end of the
30118 @command{gnatmake} command.
30119
30120 If any one of the items above is missing you will have to create it
30121 yourself. The following sections explain how to do so using as an
30122 example a fictitious DLL called @file{API.dll}.
30123
30124 @node Creating an Ada Spec for the DLL Services
30125 @subsection Creating an Ada Spec for the DLL Services
30126
30127 @noindent
30128 A DLL typically comes with a C/C++ header file which provides the
30129 definitions of the routines and variables exported by the DLL. The Ada
30130 equivalent of this header file is a package spec that contains definitions
30131 for the imported entities. If the DLL you intend to use does not come with
30132 an Ada spec you have to generate one such spec yourself. For example if
30133 the header file of @file{API.dll} is a file @file{api.h} containing the
30134 following two definitions:
30135
30136 @smallexample
30137 @group
30138 @cartouche
30139 int some_var;
30140 int get (char *);
30141 @end cartouche
30142 @end group
30143 @end smallexample
30144
30145 @noindent
30146 then the equivalent Ada spec could be:
30147
30148 @smallexample @c ada
30149 @group
30150 @cartouche
30151 with Interfaces.C.Strings;
30152 package API is
30153 use Interfaces;
30154
30155 Some_Var : C.int;
30156 function Get (Str : C.Strings.Chars_Ptr) return C.int;
30157
30158 private
30159 pragma Import (C, Get);
30160 pragma Import (DLL, Some_Var);
30161 end API;
30162 @end cartouche
30163 @end group
30164 @end smallexample
30165
30166 @node Creating an Import Library
30167 @subsection Creating an Import Library
30168 @cindex Import library
30169
30170 @menu
30171 * The Definition File::
30172 * GNAT-Style Import Library::
30173 * Microsoft-Style Import Library::
30174 @end menu
30175
30176 @noindent
30177 If a Microsoft-style import library @file{API.lib} or a GNAT-style
30178 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
30179 with @file{API.dll} you can skip this section. You can also skip this
30180 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
30181 as in this case it is possible to link directly against the
30182 DLL. Otherwise read on.
30183
30184 @node The Definition File
30185 @subsubsection The Definition File
30186 @cindex Definition file
30187 @findex .def
30188
30189 @noindent
30190 As previously mentioned, and unlike Unix systems, the list of symbols
30191 that are exported from a DLL must be provided explicitly in Windows.
30192 The main goal of a definition file is precisely that: list the symbols
30193 exported by a DLL. A definition file (usually a file with a @code{.def}
30194 suffix) has the following structure:
30195
30196 @smallexample
30197 @group
30198 @cartouche
30199 @r{[}LIBRARY @var{name}@r{]}
30200 @r{[}DESCRIPTION @var{string}@r{]}
30201 EXPORTS
30202 @var{symbol1}
30203 @var{symbol2}
30204 @dots{}
30205 @end cartouche
30206 @end group
30207 @end smallexample
30208
30209 @table @code
30210 @item LIBRARY @var{name}
30211 This section, which is optional, gives the name of the DLL.
30212
30213 @item DESCRIPTION @var{string}
30214 This section, which is optional, gives a description string that will be
30215 embedded in the import library.
30216
30217 @item EXPORTS
30218 This section gives the list of exported symbols (procedures, functions or
30219 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
30220 section of @file{API.def} looks like:
30221
30222 @smallexample
30223 @group
30224 @cartouche
30225 EXPORTS
30226 some_var
30227 get
30228 @end cartouche
30229 @end group
30230 @end smallexample
30231 @end table
30232
30233 @noindent
30234 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
30235 (@pxref{Windows Calling Conventions}) for a Stdcall
30236 calling convention function in the exported symbols list.
30237
30238 @noindent
30239 There can actually be other sections in a definition file, but these
30240 sections are not relevant to the discussion at hand.
30241
30242 @node GNAT-Style Import Library
30243 @subsubsection GNAT-Style Import Library
30244
30245 @noindent
30246 To create a static import library from @file{API.dll} with the GNAT tools
30247 you should proceed as follows:
30248
30249 @enumerate
30250 @item
30251 Create the definition file @file{API.def} (@pxref{The Definition File}).
30252 For that use the @code{dll2def} tool as follows:
30253
30254 @smallexample
30255 $ dll2def API.dll > API.def
30256 @end smallexample
30257
30258 @noindent
30259 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
30260 to standard output the list of entry points in the DLL. Note that if
30261 some routines in the DLL have the @code{Stdcall} convention
30262 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
30263 suffix then you'll have to edit @file{api.def} to add it, and specify
30264 @option{-k} to @command{gnatdll} when creating the import library.
30265
30266 @noindent
30267 Here are some hints to find the right @code{@@}@var{nn} suffix.
30268
30269 @enumerate
30270 @item
30271 If you have the Microsoft import library (.lib), it is possible to get
30272 the right symbols by using Microsoft @code{dumpbin} tool (see the
30273 corresponding Microsoft documentation for further details).
30274
30275 @smallexample
30276 $ dumpbin /exports api.lib
30277 @end smallexample
30278
30279 @item
30280 If you have a message about a missing symbol at link time the compiler
30281 tells you what symbol is expected. You just have to go back to the
30282 definition file and add the right suffix.
30283 @end enumerate
30284
30285 @item
30286 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
30287 (@pxref{Using gnatdll}) as follows:
30288
30289 @smallexample
30290 $ gnatdll -e API.def -d API.dll
30291 @end smallexample
30292
30293 @noindent
30294 @code{gnatdll} takes as input a definition file @file{API.def} and the
30295 name of the DLL containing the services listed in the definition file
30296 @file{API.dll}. The name of the static import library generated is
30297 computed from the name of the definition file as follows: if the
30298 definition file name is @var{xyz}@code{.def}, the import library name will
30299 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
30300 @option{-e} could have been removed because the name of the definition
30301 file (before the ``@code{.def}'' suffix) is the same as the name of the
30302 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
30303 @end enumerate
30304
30305 @node Microsoft-Style Import Library
30306 @subsubsection Microsoft-Style Import Library
30307
30308 @noindent
30309 With GNAT you can either use a GNAT-style or Microsoft-style import
30310 library. A Microsoft import library is needed only if you plan to make an
30311 Ada DLL available to applications developed with Microsoft
30312 tools (@pxref{Mixed-Language Programming on Windows}).
30313
30314 To create a Microsoft-style import library for @file{API.dll} you
30315 should proceed as follows:
30316
30317 @enumerate
30318 @item
30319 Create the definition file @file{API.def} from the DLL. For this use either
30320 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
30321 tool (see the corresponding Microsoft documentation for further details).
30322
30323 @item
30324 Build the actual import library using Microsoft's @code{lib} utility:
30325
30326 @smallexample
30327 $ lib -machine:IX86 -def:API.def -out:API.lib
30328 @end smallexample
30329
30330 @noindent
30331 If you use the above command the definition file @file{API.def} must
30332 contain a line giving the name of the DLL:
30333
30334 @smallexample
30335 LIBRARY "API"
30336 @end smallexample
30337
30338 @noindent
30339 See the Microsoft documentation for further details about the usage of
30340 @code{lib}.
30341 @end enumerate
30342
30343 @node Building DLLs with GNAT Project files
30344 @section Building DLLs with GNAT Project files
30345 @cindex DLLs, building
30346
30347 @noindent
30348 There is nothing specific to Windows in the build process.
30349 @pxref{Library Projects}.
30350
30351 @noindent
30352 Due to a system limitation, it is not possible under Windows to create threads
30353 when inside the @code{DllMain} routine which is used for auto-initialization
30354 of shared libraries, so it is not possible to have library level tasks in SALs.
30355
30356 @node Building DLLs with GNAT
30357 @section Building DLLs with GNAT
30358 @cindex DLLs, building
30359
30360 @noindent
30361 This section explain how to build DLLs using the GNAT built-in DLL
30362 support. With the following procedure it is straight forward to build
30363 and use DLLs with GNAT.
30364
30365 @enumerate
30366
30367 @item building object files
30368
30369 The first step is to build all objects files that are to be included
30370 into the DLL. This is done by using the standard @command{gnatmake} tool.
30371
30372 @item building the DLL
30373
30374 To build the DLL you must use @command{gcc}'s @option{-shared} and
30375 @option{-shared-libgcc} options. It is quite simple to use this method:
30376
30377 @smallexample
30378 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
30379 @end smallexample
30380
30381 It is important to note that in this case all symbols found in the
30382 object files are automatically exported. It is possible to restrict
30383 the set of symbols to export by passing to @command{gcc} a definition
30384 file, @pxref{The Definition File}. For example:
30385
30386 @smallexample
30387 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
30388 @end smallexample
30389
30390 If you use a definition file you must export the elaboration procedures
30391 for every package that required one. Elaboration procedures are named
30392 using the package name followed by "_E".
30393
30394 @item preparing DLL to be used
30395
30396 For the DLL to be used by client programs the bodies must be hidden
30397 from it and the .ali set with read-only attribute. This is very important
30398 otherwise GNAT will recompile all packages and will not actually use
30399 the code in the DLL. For example:
30400
30401 @smallexample
30402 $ mkdir apilib
30403 $ copy *.ads *.ali api.dll apilib
30404 $ attrib +R apilib\*.ali
30405 @end smallexample
30406
30407 @end enumerate
30408
30409 At this point it is possible to use the DLL by directly linking
30410 against it. Note that you must use the GNAT shared runtime when using
30411 GNAT shared libraries. This is achieved by using @option{-shared} binder's
30412 option.
30413
30414 @smallexample
30415 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
30416 @end smallexample
30417
30418 @node Building DLLs with gnatdll
30419 @section Building DLLs with gnatdll
30420 @cindex DLLs, building
30421
30422 @menu
30423 * Limitations When Using Ada DLLs from Ada::
30424 * Exporting Ada Entities::
30425 * Ada DLLs and Elaboration::
30426 * Ada DLLs and Finalization::
30427 * Creating a Spec for Ada DLLs::
30428 * Creating the Definition File::
30429 * Using gnatdll::
30430 @end menu
30431
30432 @noindent
30433 Note that it is preferred to use GNAT Project files
30434 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
30435 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
30436
30437 This section explains how to build DLLs containing Ada code using
30438 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
30439 remainder of this section.
30440
30441 The steps required to build an Ada DLL that is to be used by Ada as well as
30442 non-Ada applications are as follows:
30443
30444 @enumerate
30445 @item
30446 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
30447 @code{Stdcall} calling convention to avoid any Ada name mangling for the
30448 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
30449 skip this step if you plan to use the Ada DLL only from Ada applications.
30450
30451 @item
30452 Your Ada code must export an initialization routine which calls the routine
30453 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
30454 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
30455 routine exported by the Ada DLL must be invoked by the clients of the DLL
30456 to initialize the DLL.
30457
30458 @item
30459 When useful, the DLL should also export a finalization routine which calls
30460 routine @code{adafinal} generated by @command{gnatbind} to perform the
30461 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
30462 The finalization routine exported by the Ada DLL must be invoked by the
30463 clients of the DLL when the DLL services are no further needed.
30464
30465 @item
30466 You must provide a spec for the services exported by the Ada DLL in each
30467 of the programming languages to which you plan to make the DLL available.
30468
30469 @item
30470 You must provide a definition file listing the exported entities
30471 (@pxref{The Definition File}).
30472
30473 @item
30474 Finally you must use @code{gnatdll} to produce the DLL and the import
30475 library (@pxref{Using gnatdll}).
30476 @end enumerate
30477
30478 @noindent
30479 Note that a relocatable DLL stripped using the @code{strip}
30480 binutils tool will not be relocatable anymore. To build a DLL without
30481 debug information pass @code{-largs -s} to @code{gnatdll}. This
30482 restriction does not apply to a DLL built using a Library Project.
30483 @pxref{Library Projects}.
30484
30485 @node Limitations When Using Ada DLLs from Ada
30486 @subsection Limitations When Using Ada DLLs from Ada
30487
30488 @noindent
30489 When using Ada DLLs from Ada applications there is a limitation users
30490 should be aware of. Because on Windows the GNAT run time is not in a DLL of
30491 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
30492 each Ada DLL includes the services of the GNAT run time that are necessary
30493 to the Ada code inside the DLL. As a result, when an Ada program uses an
30494 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
30495 one in the main program.
30496
30497 It is therefore not possible to exchange GNAT run-time objects between the
30498 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
30499 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
30500 types, etc.
30501
30502 It is completely safe to exchange plain elementary, array or record types,
30503 Windows object handles, etc.
30504
30505 @node Exporting Ada Entities
30506 @subsection Exporting Ada Entities
30507 @cindex Export table
30508
30509 @noindent
30510 Building a DLL is a way to encapsulate a set of services usable from any
30511 application. As a result, the Ada entities exported by a DLL should be
30512 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
30513 any Ada name mangling. As an example here is an Ada package
30514 @code{API}, spec and body, exporting two procedures, a function, and a
30515 variable:
30516
30517 @smallexample @c ada
30518 @group
30519 @cartouche
30520 with Interfaces.C; use Interfaces;
30521 package API is
30522 Count : C.int := 0;
30523 function Factorial (Val : C.int) return C.int;
30524
30525 procedure Initialize_API;
30526 procedure Finalize_API;
30527 -- Initialization & Finalization routines. More in the next section.
30528 private
30529 pragma Export (C, Initialize_API);
30530 pragma Export (C, Finalize_API);
30531 pragma Export (C, Count);
30532 pragma Export (C, Factorial);
30533 end API;
30534 @end cartouche
30535 @end group
30536 @end smallexample
30537
30538 @smallexample @c ada
30539 @group
30540 @cartouche
30541 package body API is
30542 function Factorial (Val : C.int) return C.int is
30543 Fact : C.int := 1;
30544 begin
30545 Count := Count + 1;
30546 for K in 1 .. Val loop
30547 Fact := Fact * K;
30548 end loop;
30549 return Fact;
30550 end Factorial;
30551
30552 procedure Initialize_API is
30553 procedure Adainit;
30554 pragma Import (C, Adainit);
30555 begin
30556 Adainit;
30557 end Initialize_API;
30558
30559 procedure Finalize_API is
30560 procedure Adafinal;
30561 pragma Import (C, Adafinal);
30562 begin
30563 Adafinal;
30564 end Finalize_API;
30565 end API;
30566 @end cartouche
30567 @end group
30568 @end smallexample
30569
30570 @noindent
30571 If the Ada DLL you are building will only be used by Ada applications
30572 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
30573 convention. As an example, the previous package could be written as
30574 follows:
30575
30576 @smallexample @c ada
30577 @group
30578 @cartouche
30579 package API is
30580 Count : Integer := 0;
30581 function Factorial (Val : Integer) return Integer;
30582
30583 procedure Initialize_API;
30584 procedure Finalize_API;
30585 -- Initialization and Finalization routines.
30586 end API;
30587 @end cartouche
30588 @end group
30589 @end smallexample
30590
30591 @smallexample @c ada
30592 @group
30593 @cartouche
30594 package body API is
30595 function Factorial (Val : Integer) return Integer is
30596 Fact : Integer := 1;
30597 begin
30598 Count := Count + 1;
30599 for K in 1 .. Val loop
30600 Fact := Fact * K;
30601 end loop;
30602 return Fact;
30603 end Factorial;
30604
30605 @dots{}
30606 -- The remainder of this package body is unchanged.
30607 end API;
30608 @end cartouche
30609 @end group
30610 @end smallexample
30611
30612 @noindent
30613 Note that if you do not export the Ada entities with a @code{C} or
30614 @code{Stdcall} convention you will have to provide the mangled Ada names
30615 in the definition file of the Ada DLL
30616 (@pxref{Creating the Definition File}).
30617
30618 @node Ada DLLs and Elaboration
30619 @subsection Ada DLLs and Elaboration
30620 @cindex DLLs and elaboration
30621
30622 @noindent
30623 The DLL that you are building contains your Ada code as well as all the
30624 routines in the Ada library that are needed by it. The first thing a
30625 user of your DLL must do is elaborate the Ada code
30626 (@pxref{Elaboration Order Handling in GNAT}).
30627
30628 To achieve this you must export an initialization routine
30629 (@code{Initialize_API} in the previous example), which must be invoked
30630 before using any of the DLL services. This elaboration routine must call
30631 the Ada elaboration routine @code{adainit} generated by the GNAT binder
30632 (@pxref{Binding with Non-Ada Main Programs}). See the body of
30633 @code{Initialize_Api} for an example. Note that the GNAT binder is
30634 automatically invoked during the DLL build process by the @code{gnatdll}
30635 tool (@pxref{Using gnatdll}).
30636
30637 When a DLL is loaded, Windows systematically invokes a routine called
30638 @code{DllMain}. It would therefore be possible to call @code{adainit}
30639 directly from @code{DllMain} without having to provide an explicit
30640 initialization routine. Unfortunately, it is not possible to call
30641 @code{adainit} from the @code{DllMain} if your program has library level
30642 tasks because access to the @code{DllMain} entry point is serialized by
30643 the system (that is, only a single thread can execute ``through'' it at a
30644 time), which means that the GNAT run time will deadlock waiting for the
30645 newly created task to complete its initialization.
30646
30647 @node Ada DLLs and Finalization
30648 @subsection Ada DLLs and Finalization
30649 @cindex DLLs and finalization
30650
30651 @noindent
30652 When the services of an Ada DLL are no longer needed, the client code should
30653 invoke the DLL finalization routine, if available. The DLL finalization
30654 routine is in charge of releasing all resources acquired by the DLL. In the
30655 case of the Ada code contained in the DLL, this is achieved by calling
30656 routine @code{adafinal} generated by the GNAT binder
30657 (@pxref{Binding with Non-Ada Main Programs}).
30658 See the body of @code{Finalize_Api} for an
30659 example. As already pointed out the GNAT binder is automatically invoked
30660 during the DLL build process by the @code{gnatdll} tool
30661 (@pxref{Using gnatdll}).
30662
30663 @node Creating a Spec for Ada DLLs
30664 @subsection Creating a Spec for Ada DLLs
30665
30666 @noindent
30667 To use the services exported by the Ada DLL from another programming
30668 language (e.g.@: C), you have to translate the specs of the exported Ada
30669 entities in that language. For instance in the case of @code{API.dll},
30670 the corresponding C header file could look like:
30671
30672 @smallexample
30673 @group
30674 @cartouche
30675 extern int *_imp__count;
30676 #define count (*_imp__count)
30677 int factorial (int);
30678 @end cartouche
30679 @end group
30680 @end smallexample
30681
30682 @noindent
30683 It is important to understand that when building an Ada DLL to be used by
30684 other Ada applications, you need two different specs for the packages
30685 contained in the DLL: one for building the DLL and the other for using
30686 the DLL. This is because the @code{DLL} calling convention is needed to
30687 use a variable defined in a DLL, but when building the DLL, the variable
30688 must have either the @code{Ada} or @code{C} calling convention. As an
30689 example consider a DLL comprising the following package @code{API}:
30690
30691 @smallexample @c ada
30692 @group
30693 @cartouche
30694 package API is
30695 Count : Integer := 0;
30696 @dots{}
30697 -- Remainder of the package omitted.
30698 end API;
30699 @end cartouche
30700 @end group
30701 @end smallexample
30702
30703 @noindent
30704 After producing a DLL containing package @code{API}, the spec that
30705 must be used to import @code{API.Count} from Ada code outside of the
30706 DLL is:
30707
30708 @smallexample @c ada
30709 @group
30710 @cartouche
30711 package API is
30712 Count : Integer;
30713 pragma Import (DLL, Count);
30714 end API;
30715 @end cartouche
30716 @end group
30717 @end smallexample
30718
30719 @node Creating the Definition File
30720 @subsection Creating the Definition File
30721
30722 @noindent
30723 The definition file is the last file needed to build the DLL. It lists
30724 the exported symbols. As an example, the definition file for a DLL
30725 containing only package @code{API} (where all the entities are exported
30726 with a @code{C} calling convention) is:
30727
30728 @smallexample
30729 @group
30730 @cartouche
30731 EXPORTS
30732 count
30733 factorial
30734 finalize_api
30735 initialize_api
30736 @end cartouche
30737 @end group
30738 @end smallexample
30739
30740 @noindent
30741 If the @code{C} calling convention is missing from package @code{API},
30742 then the definition file contains the mangled Ada names of the above
30743 entities, which in this case are:
30744
30745 @smallexample
30746 @group
30747 @cartouche
30748 EXPORTS
30749 api__count
30750 api__factorial
30751 api__finalize_api
30752 api__initialize_api
30753 @end cartouche
30754 @end group
30755 @end smallexample
30756
30757 @node Using gnatdll
30758 @subsection Using @code{gnatdll}
30759 @findex gnatdll
30760
30761 @menu
30762 * gnatdll Example::
30763 * gnatdll behind the Scenes::
30764 * Using dlltool::
30765 @end menu
30766
30767 @noindent
30768 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
30769 and non-Ada sources that make up your DLL have been compiled.
30770 @code{gnatdll} is actually in charge of two distinct tasks: build the
30771 static import library for the DLL and the actual DLL. The form of the
30772 @code{gnatdll} command is
30773
30774 @smallexample
30775 @cartouche
30776 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
30777 @c Expanding @ovar macro inline (explanation in macro def comments)
30778 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
30779 @end cartouche
30780 @end smallexample
30781
30782 @noindent
30783 where @var{list-of-files} is a list of ALI and object files. The object
30784 file list must be the exact list of objects corresponding to the non-Ada
30785 sources whose services are to be included in the DLL. The ALI file list
30786 must be the exact list of ALI files for the corresponding Ada sources
30787 whose services are to be included in the DLL. If @var{list-of-files} is
30788 missing, only the static import library is generated.
30789
30790 @noindent
30791 You may specify any of the following switches to @code{gnatdll}:
30792
30793 @table @code
30794 @c @item -a@ovar{address}
30795 @c Expanding @ovar macro inline (explanation in macro def comments)
30796 @item -a@r{[}@var{address}@r{]}
30797 @cindex @option{-a} (@code{gnatdll})
30798 Build a non-relocatable DLL at @var{address}. If @var{address} is not
30799 specified the default address @var{0x11000000} will be used. By default,
30800 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
30801 advise the reader to build relocatable DLL.
30802
30803 @item -b @var{address}
30804 @cindex @option{-b} (@code{gnatdll})
30805 Set the relocatable DLL base address. By default the address is
30806 @code{0x11000000}.
30807
30808 @item -bargs @var{opts}
30809 @cindex @option{-bargs} (@code{gnatdll})
30810 Binder options. Pass @var{opts} to the binder.
30811
30812 @item -d @var{dllfile}
30813 @cindex @option{-d} (@code{gnatdll})
30814 @var{dllfile} is the name of the DLL. This switch must be present for
30815 @code{gnatdll} to do anything. The name of the generated import library is
30816 obtained algorithmically from @var{dllfile} as shown in the following
30817 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
30818 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
30819 by option @option{-e}) is obtained algorithmically from @var{dllfile}
30820 as shown in the following example:
30821 if @var{dllfile} is @code{xyz.dll}, the definition
30822 file used is @code{xyz.def}.
30823
30824 @item -e @var{deffile}
30825 @cindex @option{-e} (@code{gnatdll})
30826 @var{deffile} is the name of the definition file.
30827
30828 @item -g
30829 @cindex @option{-g} (@code{gnatdll})
30830 Generate debugging information. This information is stored in the object
30831 file and copied from there to the final DLL file by the linker,
30832 where it can be read by the debugger. You must use the
30833 @option{-g} switch if you plan on using the debugger or the symbolic
30834 stack traceback.
30835
30836 @item -h
30837 @cindex @option{-h} (@code{gnatdll})
30838 Help mode. Displays @code{gnatdll} switch usage information.
30839
30840 @item -Idir
30841 @cindex @option{-I} (@code{gnatdll})
30842 Direct @code{gnatdll} to search the @var{dir} directory for source and
30843 object files needed to build the DLL.
30844 (@pxref{Search Paths and the Run-Time Library (RTL)}).
30845
30846 @item -k
30847 @cindex @option{-k} (@code{gnatdll})
30848 Removes the @code{@@}@var{nn} suffix from the import library's exported
30849 names, but keeps them for the link names. You must specify this
30850 option if you want to use a @code{Stdcall} function in a DLL for which
30851 the @code{@@}@var{nn} suffix has been removed. This is the case for most
30852 of the Windows NT DLL for example. This option has no effect when
30853 @option{-n} option is specified.
30854
30855 @item -l @var{file}
30856 @cindex @option{-l} (@code{gnatdll})
30857 The list of ALI and object files used to build the DLL are listed in
30858 @var{file}, instead of being given in the command line. Each line in
30859 @var{file} contains the name of an ALI or object file.
30860
30861 @item -n
30862 @cindex @option{-n} (@code{gnatdll})
30863 No Import. Do not create the import library.
30864
30865 @item -q
30866 @cindex @option{-q} (@code{gnatdll})
30867 Quiet mode. Do not display unnecessary messages.
30868
30869 @item -v
30870 @cindex @option{-v} (@code{gnatdll})
30871 Verbose mode. Display extra information.
30872
30873 @item -largs @var{opts}
30874 @cindex @option{-largs} (@code{gnatdll})
30875 Linker options. Pass @var{opts} to the linker.
30876 @end table
30877
30878 @node gnatdll Example
30879 @subsubsection @code{gnatdll} Example
30880
30881 @noindent
30882 As an example the command to build a relocatable DLL from @file{api.adb}
30883 once @file{api.adb} has been compiled and @file{api.def} created is
30884
30885 @smallexample
30886 $ gnatdll -d api.dll api.ali
30887 @end smallexample
30888
30889 @noindent
30890 The above command creates two files: @file{libapi.dll.a} (the import
30891 library) and @file{api.dll} (the actual DLL). If you want to create
30892 only the DLL, just type:
30893
30894 @smallexample
30895 $ gnatdll -d api.dll -n api.ali
30896 @end smallexample
30897
30898 @noindent
30899 Alternatively if you want to create just the import library, type:
30900
30901 @smallexample
30902 $ gnatdll -d api.dll
30903 @end smallexample
30904
30905 @node gnatdll behind the Scenes
30906 @subsubsection @code{gnatdll} behind the Scenes
30907
30908 @noindent
30909 This section details the steps involved in creating a DLL. @code{gnatdll}
30910 does these steps for you. Unless you are interested in understanding what
30911 goes on behind the scenes, you should skip this section.
30912
30913 We use the previous example of a DLL containing the Ada package @code{API},
30914 to illustrate the steps necessary to build a DLL. The starting point is a
30915 set of objects that will make up the DLL and the corresponding ALI
30916 files. In the case of this example this means that @file{api.o} and
30917 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
30918 the following:
30919
30920 @enumerate
30921 @item
30922 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
30923 the information necessary to generate relocation information for the
30924 DLL.
30925
30926 @smallexample
30927 @group
30928 $ gnatbind -n api
30929 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
30930 @end group
30931 @end smallexample
30932
30933 @noindent
30934 In addition to the base file, the @command{gnatlink} command generates an
30935 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
30936 asks @command{gnatlink} to generate the routines @code{DllMain} and
30937 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
30938 is loaded into memory.
30939
30940 @item
30941 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
30942 export table (@file{api.exp}). The export table contains the relocation
30943 information in a form which can be used during the final link to ensure
30944 that the Windows loader is able to place the DLL anywhere in memory.
30945
30946 @smallexample
30947 @group
30948 $ dlltool --dllname api.dll --def api.def --base-file api.base \
30949 --output-exp api.exp
30950 @end group
30951 @end smallexample
30952
30953 @item
30954 @code{gnatdll} builds the base file using the new export table. Note that
30955 @command{gnatbind} must be called once again since the binder generated file
30956 has been deleted during the previous call to @command{gnatlink}.
30957
30958 @smallexample
30959 @group
30960 $ gnatbind -n api
30961 $ gnatlink api -o api.jnk api.exp -mdll
30962 -Wl,--base-file,api.base
30963 @end group
30964 @end smallexample
30965
30966 @item
30967 @code{gnatdll} builds the new export table using the new base file and
30968 generates the DLL import library @file{libAPI.dll.a}.
30969
30970 @smallexample
30971 @group
30972 $ dlltool --dllname api.dll --def api.def --base-file api.base \
30973 --output-exp api.exp --output-lib libAPI.a
30974 @end group
30975 @end smallexample
30976
30977 @item
30978 Finally @code{gnatdll} builds the relocatable DLL using the final export
30979 table.
30980
30981 @smallexample
30982 @group
30983 $ gnatbind -n api
30984 $ gnatlink api api.exp -o api.dll -mdll
30985 @end group
30986 @end smallexample
30987 @end enumerate
30988
30989 @node Using dlltool
30990 @subsubsection Using @code{dlltool}
30991
30992 @noindent
30993 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
30994 DLLs and static import libraries. This section summarizes the most
30995 common @code{dlltool} switches. The form of the @code{dlltool} command
30996 is
30997
30998 @smallexample
30999 @c $ dlltool @ovar{switches}
31000 @c Expanding @ovar macro inline (explanation in macro def comments)
31001 $ dlltool @r{[}@var{switches}@r{]}
31002 @end smallexample
31003
31004 @noindent
31005 @code{dlltool} switches include:
31006
31007 @table @option
31008 @item --base-file @var{basefile}
31009 @cindex @option{--base-file} (@command{dlltool})
31010 Read the base file @var{basefile} generated by the linker. This switch
31011 is used to create a relocatable DLL.
31012
31013 @item --def @var{deffile}
31014 @cindex @option{--def} (@command{dlltool})
31015 Read the definition file.
31016
31017 @item --dllname @var{name}
31018 @cindex @option{--dllname} (@command{dlltool})
31019 Gives the name of the DLL. This switch is used to embed the name of the
31020 DLL in the static import library generated by @code{dlltool} with switch
31021 @option{--output-lib}.
31022
31023 @item -k
31024 @cindex @option{-k} (@command{dlltool})
31025 Kill @code{@@}@var{nn} from exported names
31026 (@pxref{Windows Calling Conventions}
31027 for a discussion about @code{Stdcall}-style symbols.
31028
31029 @item --help
31030 @cindex @option{--help} (@command{dlltool})
31031 Prints the @code{dlltool} switches with a concise description.
31032
31033 @item --output-exp @var{exportfile}
31034 @cindex @option{--output-exp} (@command{dlltool})
31035 Generate an export file @var{exportfile}. The export file contains the
31036 export table (list of symbols in the DLL) and is used to create the DLL.
31037
31038 @item --output-lib @var{libfile}
31039 @cindex @option{--output-lib} (@command{dlltool})
31040 Generate a static import library @var{libfile}.
31041
31042 @item -v
31043 @cindex @option{-v} (@command{dlltool})
31044 Verbose mode.
31045
31046 @item --as @var{assembler-name}
31047 @cindex @option{--as} (@command{dlltool})
31048 Use @var{assembler-name} as the assembler. The default is @code{as}.
31049 @end table
31050
31051 @node GNAT and Windows Resources
31052 @section GNAT and Windows Resources
31053 @cindex Resources, windows
31054
31055 @menu
31056 * Building Resources::
31057 * Compiling Resources::
31058 * Using Resources::
31059 @end menu
31060
31061 @noindent
31062 Resources are an easy way to add Windows specific objects to your
31063 application. The objects that can be added as resources include:
31064
31065 @itemize @bullet
31066 @item menus
31067
31068 @item accelerators
31069
31070 @item dialog boxes
31071
31072 @item string tables
31073
31074 @item bitmaps
31075
31076 @item cursors
31077
31078 @item icons
31079
31080 @item fonts
31081
31082 @item version information
31083 @end itemize
31084
31085 For example, a version information resource can be defined as follow and
31086 embedded into an executable or DLL:
31087
31088 A version information resource can be used to embed information into an
31089 executable or a DLL. These information can be viewed using the file properties
31090 from the Windows Explorer. Here is an example of a version information
31091 resource:
31092
31093 @smallexample
31094 @group
31095 1 VERSIONINFO
31096 FILEVERSION 1,0,0,0
31097 PRODUCTVERSION 1,0,0,0
31098 BEGIN
31099 BLOCK "StringFileInfo"
31100 BEGIN
31101 BLOCK "080904E4"
31102 BEGIN
31103 VALUE "CompanyName", "My Company Name"
31104 VALUE "FileDescription", "My application"
31105 VALUE "FileVersion", "1.0"
31106 VALUE "InternalName", "my_app"
31107 VALUE "LegalCopyright", "My Name"
31108 VALUE "OriginalFilename", "my_app.exe"
31109 VALUE "ProductName", "My App"
31110 VALUE "ProductVersion", "1.0"
31111 END
31112 END
31113
31114 BLOCK "VarFileInfo"
31115 BEGIN
31116 VALUE "Translation", 0x809, 1252
31117 END
31118 END
31119 @end group
31120 @end smallexample
31121
31122 The value @code{0809} (langID) is for the U.K English language and
31123 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
31124 multilingual.
31125
31126 @noindent
31127 This section explains how to build, compile and use resources. Note that this
31128 section does not cover all resource objects, for a complete description see
31129 the corresponding Microsoft documentation.
31130
31131 @node Building Resources
31132 @subsection Building Resources
31133 @cindex Resources, building
31134
31135 @noindent
31136 A resource file is an ASCII file. By convention resource files have an
31137 @file{.rc} extension.
31138 The easiest way to build a resource file is to use Microsoft tools
31139 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
31140 @code{dlgedit.exe} to build dialogs.
31141 It is always possible to build an @file{.rc} file yourself by writing a
31142 resource script.
31143
31144 It is not our objective to explain how to write a resource file. A
31145 complete description of the resource script language can be found in the
31146 Microsoft documentation.
31147
31148 @node Compiling Resources
31149 @subsection Compiling Resources
31150 @findex rc
31151 @findex windres
31152 @cindex Resources, compiling
31153
31154 @noindent
31155 This section describes how to build a GNAT-compatible (COFF) object file
31156 containing the resources. This is done using the Resource Compiler
31157 @code{windres} as follows:
31158
31159 @smallexample
31160 $ windres -i myres.rc -o myres.o
31161 @end smallexample
31162
31163 @noindent
31164 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
31165 file. You can specify an alternate preprocessor (usually named
31166 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
31167 parameter. A list of all possible options may be obtained by entering
31168 the command @code{windres} @option{--help}.
31169
31170 It is also possible to use the Microsoft resource compiler @code{rc.exe}
31171 to produce a @file{.res} file (binary resource file). See the
31172 corresponding Microsoft documentation for further details. In this case
31173 you need to use @code{windres} to translate the @file{.res} file to a
31174 GNAT-compatible object file as follows:
31175
31176 @smallexample
31177 $ windres -i myres.res -o myres.o
31178 @end smallexample
31179
31180 @node Using Resources
31181 @subsection Using Resources
31182 @cindex Resources, using
31183
31184 @noindent
31185 To include the resource file in your program just add the
31186 GNAT-compatible object file for the resource(s) to the linker
31187 arguments. With @command{gnatmake} this is done by using the @option{-largs}
31188 option:
31189
31190 @smallexample
31191 $ gnatmake myprog -largs myres.o
31192 @end smallexample
31193
31194 @node Debugging a DLL
31195 @section Debugging a DLL
31196 @cindex DLL debugging
31197
31198 @menu
31199 * Program and DLL Both Built with GCC/GNAT::
31200 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
31201 @end menu
31202
31203 @noindent
31204 Debugging a DLL is similar to debugging a standard program. But
31205 we have to deal with two different executable parts: the DLL and the
31206 program that uses it. We have the following four possibilities:
31207
31208 @enumerate 1
31209 @item
31210 The program and the DLL are built with @code{GCC/GNAT}.
31211 @item
31212 The program is built with foreign tools and the DLL is built with
31213 @code{GCC/GNAT}.
31214 @item
31215 The program is built with @code{GCC/GNAT} and the DLL is built with
31216 foreign tools.
31217 @end enumerate
31218
31219 @noindent
31220 In this section we address only cases one and two above.
31221 There is no point in trying to debug
31222 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
31223 information in it. To do so you must use a debugger compatible with the
31224 tools suite used to build the DLL.
31225
31226 @node Program and DLL Both Built with GCC/GNAT
31227 @subsection Program and DLL Both Built with GCC/GNAT
31228
31229 @noindent
31230 This is the simplest case. Both the DLL and the program have @code{GDB}
31231 compatible debugging information. It is then possible to break anywhere in
31232 the process. Let's suppose here that the main procedure is named
31233 @code{ada_main} and that in the DLL there is an entry point named
31234 @code{ada_dll}.
31235
31236 @noindent
31237 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
31238 program must have been built with the debugging information (see GNAT -g
31239 switch). Here are the step-by-step instructions for debugging it:
31240
31241 @enumerate 1
31242 @item Launch @code{GDB} on the main program.
31243
31244 @smallexample
31245 $ gdb -nw ada_main
31246 @end smallexample
31247
31248 @item Start the program and stop at the beginning of the main procedure
31249
31250 @smallexample
31251 (gdb) start
31252 @end smallexample
31253
31254 @noindent
31255 This step is required to be able to set a breakpoint inside the DLL. As long
31256 as the program is not run, the DLL is not loaded. This has the
31257 consequence that the DLL debugging information is also not loaded, so it is not
31258 possible to set a breakpoint in the DLL.
31259
31260 @item Set a breakpoint inside the DLL
31261
31262 @smallexample
31263 (gdb) break ada_dll
31264 (gdb) cont
31265 @end smallexample
31266
31267 @end enumerate
31268
31269 @noindent
31270 At this stage a breakpoint is set inside the DLL. From there on
31271 you can use the standard approach to debug the whole program
31272 (@pxref{Running and Debugging Ada Programs}).
31273
31274 @ignore
31275 @c This used to work, probably because the DLLs were non-relocatable
31276 @c keep this section around until the problem is sorted out.
31277
31278 To break on the @code{DllMain} routine it is not possible to follow
31279 the procedure above. At the time the program stop on @code{ada_main}
31280 the @code{DllMain} routine as already been called. Either you can use
31281 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
31282
31283 @enumerate 1
31284 @item Launch @code{GDB} on the main program.
31285
31286 @smallexample
31287 $ gdb ada_main
31288 @end smallexample
31289
31290 @item Load DLL symbols
31291
31292 @smallexample
31293 (gdb) add-sym api.dll
31294 @end smallexample
31295
31296 @item Set a breakpoint inside the DLL
31297
31298 @smallexample
31299 (gdb) break ada_dll.adb:45
31300 @end smallexample
31301
31302 Note that at this point it is not possible to break using the routine symbol
31303 directly as the program is not yet running. The solution is to break
31304 on the proper line (break in @file{ada_dll.adb} line 45).
31305
31306 @item Start the program
31307
31308 @smallexample
31309 (gdb) run
31310 @end smallexample
31311
31312 @end enumerate
31313 @end ignore
31314
31315 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
31316 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
31317
31318 @menu
31319 * Debugging the DLL Directly::
31320 * Attaching to a Running Process::
31321 @end menu
31322
31323 @noindent
31324 In this case things are slightly more complex because it is not possible to
31325 start the main program and then break at the beginning to load the DLL and the
31326 associated DLL debugging information. It is not possible to break at the
31327 beginning of the program because there is no @code{GDB} debugging information,
31328 and therefore there is no direct way of getting initial control. This
31329 section addresses this issue by describing some methods that can be used
31330 to break somewhere in the DLL to debug it.
31331
31332 @noindent
31333 First suppose that the main procedure is named @code{main} (this is for
31334 example some C code built with Microsoft Visual C) and that there is a
31335 DLL named @code{test.dll} containing an Ada entry point named
31336 @code{ada_dll}.
31337
31338 @noindent
31339 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
31340 been built with debugging information (see GNAT -g option).
31341
31342 @node Debugging the DLL Directly
31343 @subsubsection Debugging the DLL Directly
31344
31345 @enumerate 1
31346 @item
31347 Find out the executable starting address
31348
31349 @smallexample
31350 $ objdump --file-header main.exe
31351 @end smallexample
31352
31353 The starting address is reported on the last line. For example:
31354
31355 @smallexample
31356 main.exe: file format pei-i386
31357 architecture: i386, flags 0x0000010a:
31358 EXEC_P, HAS_DEBUG, D_PAGED
31359 start address 0x00401010
31360 @end smallexample
31361
31362 @item
31363 Launch the debugger on the executable.
31364
31365 @smallexample
31366 $ gdb main.exe
31367 @end smallexample
31368
31369 @item
31370 Set a breakpoint at the starting address, and launch the program.
31371
31372 @smallexample
31373 $ (gdb) break *0x00401010
31374 $ (gdb) run
31375 @end smallexample
31376
31377 The program will stop at the given address.
31378
31379 @item
31380 Set a breakpoint on a DLL subroutine.
31381
31382 @smallexample
31383 (gdb) break ada_dll.adb:45
31384 @end smallexample
31385
31386 Or if you want to break using a symbol on the DLL, you need first to
31387 select the Ada language (language used by the DLL).
31388
31389 @smallexample
31390 (gdb) set language ada
31391 (gdb) break ada_dll
31392 @end smallexample
31393
31394 @item
31395 Continue the program.
31396
31397 @smallexample
31398 (gdb) cont
31399 @end smallexample
31400
31401 @noindent
31402 This will run the program until it reaches the breakpoint that has been
31403 set. From that point you can use the standard way to debug a program
31404 as described in (@pxref{Running and Debugging Ada Programs}).
31405
31406 @end enumerate
31407
31408 @noindent
31409 It is also possible to debug the DLL by attaching to a running process.
31410
31411 @node Attaching to a Running Process
31412 @subsubsection Attaching to a Running Process
31413 @cindex DLL debugging, attach to process
31414
31415 @noindent
31416 With @code{GDB} it is always possible to debug a running process by
31417 attaching to it. It is possible to debug a DLL this way. The limitation
31418 of this approach is that the DLL must run long enough to perform the
31419 attach operation. It may be useful for instance to insert a time wasting
31420 loop in the code of the DLL to meet this criterion.
31421
31422 @enumerate 1
31423
31424 @item Launch the main program @file{main.exe}.
31425
31426 @smallexample
31427 $ main
31428 @end smallexample
31429
31430 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
31431 that the process PID for @file{main.exe} is 208.
31432
31433 @item Launch gdb.
31434
31435 @smallexample
31436 $ gdb
31437 @end smallexample
31438
31439 @item Attach to the running process to be debugged.
31440
31441 @smallexample
31442 (gdb) attach 208
31443 @end smallexample
31444
31445 @item Load the process debugging information.
31446
31447 @smallexample
31448 (gdb) symbol-file main.exe
31449 @end smallexample
31450
31451 @item Break somewhere in the DLL.
31452
31453 @smallexample
31454 (gdb) break ada_dll
31455 @end smallexample
31456
31457 @item Continue process execution.
31458
31459 @smallexample
31460 (gdb) cont
31461 @end smallexample
31462
31463 @end enumerate
31464
31465 @noindent
31466 This last step will resume the process execution, and stop at
31467 the breakpoint we have set. From there you can use the standard
31468 approach to debug a program as described in
31469 (@pxref{Running and Debugging Ada Programs}).
31470
31471 @node Setting Stack Size from gnatlink
31472 @section Setting Stack Size from @command{gnatlink}
31473
31474 @noindent
31475 It is possible to specify the program stack size at link time. On modern
31476 versions of Windows, starting with XP, this is mostly useful to set the size of
31477 the main stack (environment task). The other task stacks are set with pragma
31478 Storage_Size or with the @command{gnatbind -d} command.
31479
31480 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
31481 reserve size of individual tasks, the link-time stack size applies to all
31482 tasks, and pragma Storage_Size has no effect.
31483 In particular, Stack Overflow checks are made against this
31484 link-time specified size.
31485
31486 This setting can be done with
31487 @command{gnatlink} using either:
31488
31489 @itemize @bullet
31490
31491 @item using @option{-Xlinker} linker option
31492
31493 @smallexample
31494 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
31495 @end smallexample
31496
31497 This sets the stack reserve size to 0x10000 bytes and the stack commit
31498 size to 0x1000 bytes.
31499
31500 @item using @option{-Wl} linker option
31501
31502 @smallexample
31503 $ gnatlink hello -Wl,--stack=0x1000000
31504 @end smallexample
31505
31506 This sets the stack reserve size to 0x1000000 bytes. Note that with
31507 @option{-Wl} option it is not possible to set the stack commit size
31508 because the coma is a separator for this option.
31509
31510 @end itemize
31511
31512 @node Setting Heap Size from gnatlink
31513 @section Setting Heap Size from @command{gnatlink}
31514
31515 @noindent
31516 Under Windows systems, it is possible to specify the program heap size from
31517 @command{gnatlink} using either:
31518
31519 @itemize @bullet
31520
31521 @item using @option{-Xlinker} linker option
31522
31523 @smallexample
31524 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
31525 @end smallexample
31526
31527 This sets the heap reserve size to 0x10000 bytes and the heap commit
31528 size to 0x1000 bytes.
31529
31530 @item using @option{-Wl} linker option
31531
31532 @smallexample
31533 $ gnatlink hello -Wl,--heap=0x1000000
31534 @end smallexample
31535
31536 This sets the heap reserve size to 0x1000000 bytes. Note that with
31537 @option{-Wl} option it is not possible to set the heap commit size
31538 because the coma is a separator for this option.
31539
31540 @end itemize
31541
31542 @node Mac OS Topics
31543 @appendix Mac OS Topics
31544 @cindex OS X
31545
31546 @noindent
31547 This chapter describes topics that are specific to Apple's OS X
31548 platform.
31549
31550 @menu
31551 * Codesigning the Debugger::
31552 @end menu
31553
31554 @node Codesigning the Debugger
31555 @section Codesigning the Debugger
31556
31557 @noindent
31558 The Darwin Kernel requires the debugger to have special permissions
31559 before it is allowed to control other processes. These permissions
31560 are granted by codesigning the GDB executable. Without these
31561 permissions, the debugger will report error messages such as:
31562
31563 @smallexample
31564 Starting program: /x/y/foo
31565 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
31566 (please check gdb is codesigned - see taskgated(8))
31567 @end smallexample
31568
31569 Codesigning requires a certificate. The following procedure explains
31570 how to create one:
31571
31572 @itemize @bullet
31573 @item Start the Keychain Access application (in
31574 /Applications/Utilities/Keychain Access.app)
31575
31576 @item Select the Keychain Access -> Certificate Assistant ->
31577 Create a Certificate... menu
31578
31579 @item Then:
31580
31581 @itemize @bullet
31582 @item Choose a name for the new certificate (this procedure will use
31583 "gdb-cert" as an example)
31584
31585 @item Set "Identity Type" to "Self Signed Root"
31586
31587 @item Set "Certificate Type" to "Code Signing"
31588
31589 @item Activate the "Let me override defaults" option
31590
31591 @end itemize
31592
31593 @item Click several times on "Continue" until the "Specify a Location
31594 For The Certificate" screen appears, then set "Keychain" to "System"
31595
31596 @item Click on "Continue" until the certificate is created
31597
31598 @item Finally, in the view, double-click on the new certificate,
31599 and set "When using this certificate" to "Always Trust"
31600
31601 @item Exit the Keychain Access application and restart the computer
31602 (this is unfortunately required)
31603
31604 @end itemize
31605
31606 Once a certificate has been created, the debugger can be codesigned
31607 as follow. In a Terminal, run the following command...
31608
31609 @smallexample
31610 codesign -f -s "gdb-cert" <gnat_install_prefix>/bin/gdb
31611 @end smallexample
31612
31613 ... where "gdb-cert" should be replaced by the actual certificate
31614 name chosen above, and <gnat_install_prefix> should be replaced by
31615 the location where you installed GNAT.
31616
31617 @c **********************************
31618 @c * GNU Free Documentation License *
31619 @c **********************************
31620 @include fdl.texi
31621 @c GNU Free Documentation License
31622
31623 @node Index
31624 @unnumbered Index
31625
31626 @printindex cp
31627
31628 @contents
31629 @c Put table of contents at end, otherwise it precedes the "title page" in
31630 @c the .txt version
31631 @c Edit the pdf file to move the contents to the beginning, after the title
31632 @c page
31633
31634 @bye