[multiple changes]
[gcc.git] / gcc / ada / gnat_ugn.texi
1
2 \input texinfo @c -*-texinfo-*-
3 @c %**start of header
4
5 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
6 @c o
7 @c GNAT DOCUMENTATION o
8 @c o
9 @c G N A T _ U G N o
10 @c o
11 @c Copyright (C) 1992-2014, Free Software Foundation, Inc. o
12 @c o
13 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
14
15 @setfilename gnat_ugn.info
16
17 @copying
18 Copyright @copyright{} 1995-2014 Free Software Foundation,
19 Inc.
20
21 Permission is granted to copy, distribute and/or modify this document
22 under the terms of the GNU Free Documentation License, Version 1.3 or
23 any later version published by the Free Software Foundation; with no
24 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
25 Texts. A copy of the license is included in the section entitled
26 ``GNU Free Documentation License''.
27 @end copying
28
29 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
30 @c
31 @c GNAT_UGN Style Guide
32 @c
33 @c 1. Always put a @noindent on the line before the first paragraph
34 @c after any of these commands:
35 @c
36 @c @chapter
37 @c @section
38 @c @subsection
39 @c @subsubsection
40 @c @subsubsubsection
41 @c
42 @c @end smallexample
43 @c @end itemize
44 @c @end enumerate
45 @c
46 @c 2. DO NOT use @example. Use @smallexample instead.
47 @c a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
48 @c context. These can interfere with the readability of the texi
49 @c source file. Instead, use one of the following annotated
50 @c @smallexample commands, and preprocess the texi file with the
51 @c ada2texi tool (which generates appropriate highlighting):
52 @c @smallexample @c ada
53 @c @smallexample @c adanocomment
54 @c @smallexample @c projectfile
55 @c b) The "@c ada" markup will result in boldface for reserved words
56 @c and italics for comments
57 @c c) The "@c adanocomment" markup will result only in boldface for
58 @c reserved words (comments are left alone)
59 @c d) The "@c projectfile" markup is like "@c ada" except that the set
60 @c of reserved words include the new reserved words for project files
61 @c
62 @c 3. Each @chapter, @section, @subsection, @subsubsection, etc.
63 @c command must be preceded by two empty lines
64 @c
65 @c 4. The @item command should be on a line of its own if it is in an
66 @c @itemize or @enumerate command.
67 @c
68 @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
69 @c or "ali".
70 @c
71 @c 6. DO NOT put trailing spaces at the end of a line. Such spaces will
72 @c cause the document build to fail.
73 @c
74 @c 7. DO NOT use @cartouche for examples that are longer than around 10 lines.
75 @c This command inhibits page breaks, so long examples in a @cartouche can
76 @c lead to large, ugly patches of empty space on a page.
77 @c
78 @c NOTE: This file should be submitted to xgnatugn with either the vms flag
79 @c or the unw flag set. The unw flag covers topics for both Unix and
80 @c Windows.
81 @c
82 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
83
84 @set NOW January 2007
85 @c This flag is used where the text refers to conditions that exist when the
86 @c text was entered into the document but which may change over time.
87 @c Update the setting for the flag, and (if necessary) the text surrounding,
88 @c the references to the flag, on future doc revisions:
89 @c search for @value{NOW}.
90
91 @set FSFEDITION
92 @set EDITION GNAT
93
94 @ifset unw
95 @set PLATFORM
96 @set TITLESUFFIX
97 @end ifset
98
99 @ifset vms
100 @set PLATFORM OpenVMS
101 @set TITLESUFFIX for OpenVMS
102 @end ifset
103
104 @c @ovar(ARG)
105 @c ----------
106 @c The ARG is an optional argument. To be used for macro arguments in
107 @c their documentation (@defmac).
108 @macro ovar{varname}
109 @r{[}@var{\varname\}@r{]}@c
110 @end macro
111 @c Status as of November 2009:
112 @c Unfortunately texi2pdf and texi2html treat the trailing "@c"
113 @c differently, and faulty output is produced by one or the other
114 @c depending on whether the "@c" is present or absent.
115 @c As a result, the @ovar macro is not used, and all invocations
116 @c of the @ovar macro have been expanded inline.
117
118
119 @settitle @value{EDITION} User's Guide @value{TITLESUFFIX}
120 @dircategory GNU Ada tools
121 @direntry
122 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
123 @end direntry
124
125 @include gcc-common.texi
126
127 @setchapternewpage odd
128 @syncodeindex fn cp
129 @c %**end of header
130
131 @titlepage
132 @title @value{EDITION} User's Guide
133 @ifset vms
134 @sp 1
135 @flushright
136 @titlefont{@i{@value{PLATFORM}}}
137 @end flushright
138 @end ifset
139
140 @sp 2
141
142 @subtitle GNAT, The GNU Ada Development Environment
143 @versionsubtitle
144 @author AdaCore
145
146 @page
147 @vskip 0pt plus 1filll
148
149 @insertcopying
150
151 @end titlepage
152
153 @ifnottex
154 @node Top, About This Guide, (dir), (dir)
155 @top @value{EDITION} User's Guide
156
157 @noindent
158 @value{EDITION} User's Guide @value{PLATFORM}
159
160 @noindent
161 GNAT, The GNU Ada Development Environment@*
162 GCC version @value{version-GCC}@*
163
164 @noindent
165 AdaCore@*
166
167 @menu
168 * About This Guide::
169 * Getting Started with GNAT::
170 * The GNAT Compilation Model::
171 * Compiling with gcc::
172 * Binding with gnatbind::
173 * Linking with gnatlink::
174 * The GNAT Make Program gnatmake::
175 * Improving Performance::
176 * Renaming Files with gnatchop::
177 * Configuration Pragmas::
178 * Handling Arbitrary File Naming Conventions with gnatname::
179 * GNAT Project Manager::
180 * Tools Supporting Project Files::
181 * The Cross-Referencing Tools gnatxref and gnatfind::
182 @ifclear FSFEDITION
183 * The GNAT Pretty-Printer gnatpp::
184 @ifclear vms
185 * The Ada-to-XML converter gnat2xml::
186 @end ifclear
187 * The GNAT Metrics Tool gnatmetric::
188 @end ifclear
189 * File Name Krunching with gnatkr::
190 * Preprocessing with gnatprep::
191 * The GNAT Library Browser gnatls::
192 * Cleaning Up with gnatclean::
193 @ifclear vms
194 * GNAT and Libraries::
195 * Using the GNU make Utility::
196 @end ifclear
197 * Memory Management Issues::
198 * Stack Related Facilities::
199 @ifclear FSFEDITION
200 * Verifying Properties with gnatcheck::
201 * Creating Sample Bodies with gnatstub::
202 * Creating Unit Tests with gnattest::
203 @end ifclear
204 * Performing Dimensionality Analysis in GNAT::
205 * Generating Ada Bindings for C and C++ headers::
206 * Other Utility Programs::
207 @ifclear vms
208 * Code Coverage and Profiling::
209 @end ifclear
210 * Running and Debugging Ada Programs::
211 @ifset vms
212 * Compatibility with HP Ada::
213 @end ifset
214 * Platform-Specific Information for the Run-Time Libraries::
215 * Example of Binder Output File::
216 * Elaboration Order Handling in GNAT::
217 * Overflow Check Handling in GNAT::
218 * Conditional Compilation::
219 * Inline Assembler::
220 * Compatibility and Porting Guide::
221 * Microsoft Windows Topics::
222 * Mac OS Topics::
223 * GNU Free Documentation License::
224 * Index::
225 @end menu
226 @end ifnottex
227
228 @node About This Guide
229 @unnumbered About This Guide
230
231 @noindent
232 @ifset vms
233 This guide describes the use of @value{EDITION},
234 a compiler and software development toolset for the full Ada
235 programming language, implemented on OpenVMS for HP's Alpha and
236 Integrity server (I64) platforms.
237 @end ifset
238 @ifclear vms
239 This guide describes the use of @value{EDITION},
240 a compiler and software development
241 toolset for the full Ada programming language.
242 @end ifclear
243 It documents the features of the compiler and tools, and explains
244 how to use them to build Ada applications.
245
246 @value{EDITION} implements Ada 95, Ada 2005 and Ada 2012, and it may also be
247 invoked in Ada 83 compatibility mode.
248 By default, @value{EDITION} assumes Ada 2012, but you can override with a
249 compiler switch (@pxref{Compiling Different Versions of Ada})
250 to explicitly specify the language version.
251 Throughout this manual, references to ``Ada'' without a year suffix
252 apply to all Ada 95/2005/2012 versions of the language.
253
254 @ifclear FSFEDITION
255 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
256 ``GNAT'' in the remainder of this document.
257 @end ifclear
258
259
260 @menu
261 * What This Guide Contains::
262 * What You Should Know before Reading This Guide::
263 * Related Information::
264 * Conventions::
265 @end menu
266
267 @node What This Guide Contains
268 @unnumberedsec What This Guide Contains
269
270 @noindent
271 This guide contains the following chapters:
272 @itemize @bullet
273
274 @item
275 @ref{Getting Started with GNAT}, describes how to get started compiling
276 and running Ada programs with the GNAT Ada programming environment.
277 @item
278 @ref{The GNAT Compilation Model}, describes the compilation model used
279 by GNAT.
280
281 @item
282 @ref{Compiling with gcc}, describes how to compile
283 Ada programs with @command{gcc}, the Ada compiler.
284
285 @item
286 @ref{Binding with gnatbind}, describes how to
287 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
288 utility.
289
290 @item
291 @ref{Linking with gnatlink},
292 describes @command{gnatlink}, a
293 program that provides for linking using the GNAT run-time library to
294 construct a program. @command{gnatlink} can also incorporate foreign language
295 object units into the executable.
296
297 @item
298 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
299 utility that automatically determines the set of sources
300 needed by an Ada compilation unit, and executes the necessary compilations
301 binding and link.
302
303 @item
304 @ref{Improving Performance}, shows various techniques for making your
305 Ada program run faster or take less space and describes the effect of
306 the compiler's optimization switch.
307 It also describes
308 @ifclear FSFEDITION
309 the @command{gnatelim} tool and
310 @end ifclear
311 unused subprogram/data elimination.
312
313 @item
314 @ref{Renaming Files with gnatchop}, describes
315 @code{gnatchop}, a utility that allows you to preprocess a file that
316 contains Ada source code, and split it into one or more new files, one
317 for each compilation unit.
318
319 @item
320 @ref{Configuration Pragmas}, describes the configuration pragmas
321 handled by GNAT.
322
323 @item
324 @ref{Handling Arbitrary File Naming Conventions with gnatname},
325 shows how to override the default GNAT file naming conventions,
326 either for an individual unit or globally.
327
328 @item
329 @ref{GNAT Project Manager}, describes how to use project files
330 to organize large projects.
331
332 @item
333 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
334 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
335 way to navigate through sources.
336
337 @ifclear FSFEDITION
338 @item
339 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
340 version of an Ada source file with control over casing, indentation,
341 comment placement, and other elements of program presentation style.
342 @end ifclear
343
344 @ifclear FSFEDITION
345 @ifclear vms
346 @item
347 @ref{The Ada-to-XML converter gnat2xml}, shows how to convert Ada
348 source code into XML.
349 @end ifclear
350 @end ifclear
351
352 @ifclear FSFEDITION
353 @item
354 @ref{The GNAT Metrics Tool gnatmetric}, shows how to compute various
355 metrics for an Ada source file, such as the number of types and subprograms,
356 and assorted complexity measures.
357 @end ifclear
358
359 @item
360 @ref{File Name Krunching with gnatkr}, describes the @code{gnatkr}
361 file name krunching utility, used to handle shortened
362 file names on operating systems with a limit on the length of names.
363
364 @item
365 @ref{Preprocessing with gnatprep}, describes @code{gnatprep}, a
366 preprocessor utility that allows a single source file to be used to
367 generate multiple or parameterized source files by means of macro
368 substitution.
369
370 @item
371 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
372 utility that displays information about compiled units, including dependences
373 on the corresponding sources files, and consistency of compilations.
374
375 @item
376 @ref{Cleaning Up with gnatclean}, describes @code{gnatclean}, a utility
377 to delete files that are produced by the compiler, binder and linker.
378
379 @ifclear vms
380 @item
381 @ref{GNAT and Libraries}, describes the process of creating and using
382 Libraries with GNAT. It also describes how to recompile the GNAT run-time
383 library.
384
385 @item
386 @ref{Using the GNU make Utility}, describes some techniques for using
387 the GNAT toolset in Makefiles.
388 @end ifclear
389
390 @item
391 @ref{Memory Management Issues}, describes some useful predefined storage pools
392 and in particular the GNAT Debug Pool facility, which helps detect incorrect
393 memory references.
394 @ifclear vms
395 @ifclear FSFEDITION
396 It also describes @command{gnatmem}, a utility that monitors dynamic
397 allocation and deallocation and helps detect ``memory leaks''.
398 @end ifclear
399 @end ifclear
400
401 @item
402 @ref{Stack Related Facilities}, describes some useful tools associated with
403 stack checking and analysis.
404
405 @ifclear FSFEDITION
406 @item
407 @ref{Verifying Properties with gnatcheck}, discusses @code{gnatcheck},
408 a utility that checks Ada code against a set of rules.
409
410 @item
411 @ref{Creating Sample Bodies with gnatstub}, discusses @code{gnatstub},
412 a utility that generates empty but compilable bodies for library units.
413 @end ifclear
414
415 @ifclear FSFEDITION
416 @item
417 @ref{Creating Unit Tests with gnattest}, discusses @code{gnattest},
418 a utility that generates unit testing templates for library units.
419 @end ifclear
420
421 @item
422 @ref{Performing Dimensionality Analysis in GNAT}, describes the Ada 2012
423 facilities used in GNAT to declare dimensioned objects, and to verify that
424 uses of these objects are consistent with their given physical dimensions
425 (so that meters cannot be assigned to kilograms, and so on).
426
427 @item
428 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
429 generate automatically Ada bindings from C and C++ headers.
430
431 @item
432 @ref{Other Utility Programs}, discusses several other GNAT utilities,
433 including @code{gnathtml}.
434
435 @ifclear vms
436 @item
437 @ref{Code Coverage and Profiling}, describes how to perform a structural
438 coverage and profile the execution of Ada programs.
439 @end ifclear
440
441 @item
442 @ref{Running and Debugging Ada Programs}, describes how to run and debug
443 Ada programs.
444
445 @ifset vms
446 @item
447 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
448 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
449 developed by Digital Equipment Corporation and currently supported by HP.}
450 for OpenVMS Alpha. This product was formerly known as DEC Ada,
451 @cindex DEC Ada
452 and for
453 historical compatibility reasons, the relevant libraries still use the
454 DEC prefix.
455 @end ifset
456
457 @item
458 @ref{Platform-Specific Information for the Run-Time Libraries},
459 describes the various run-time
460 libraries supported by GNAT on various platforms and explains how to
461 choose a particular library.
462
463 @item
464 @ref{Example of Binder Output File}, shows the source code for the binder
465 output file for a sample program.
466
467 @item
468 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
469 you deal with elaboration order issues.
470
471 @item
472 @ref{Overflow Check Handling in GNAT}, describes how GNAT helps
473 you deal with arithmetic overflow issues.
474
475 @item
476 @ref{Conditional Compilation}, describes how to model conditional compilation,
477 both with Ada in general and with GNAT facilities in particular.
478
479 @item
480 @ref{Inline Assembler}, shows how to use the inline assembly facility
481 in an Ada program.
482
483 @item
484 @ref{Compatibility and Porting Guide}, contains sections on compatibility
485 of GNAT with other Ada development environments (including Ada 83 systems),
486 to assist in porting code from those environments.
487
488 @ifset unw
489 @item
490 @ref{Microsoft Windows Topics}, presents information relevant to the
491 Microsoft Windows platform.
492
493 @item
494 @ref{Mac OS Topics}, presents information relevant to Apple's OS X
495 platform.
496 @end ifset
497 @end itemize
498
499 @c *************************************************
500 @node What You Should Know before Reading This Guide
501 @c *************************************************
502 @unnumberedsec What You Should Know before Reading This Guide
503
504 @cindex Ada 95 Language Reference Manual
505 @cindex Ada 2005 Language Reference Manual
506 @noindent
507 This guide assumes a basic familiarity with the Ada 95 language, as
508 described in the International Standard ANSI/ISO/IEC-8652:1995, January
509 1995.
510 It does not require knowledge of the new features introduced by Ada 2005,
511 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
512 and Amendment 1).
513 Both reference manuals are included in the GNAT documentation
514 package.
515
516 @node Related Information
517 @unnumberedsec Related Information
518
519 @noindent
520 For further information about related tools, refer to the following
521 documents:
522
523 @itemize @bullet
524 @item
525 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
526 Reference Manual}, which contains all reference material for the GNAT
527 implementation of Ada.
528
529 @ifset unw
530 @item
531 @cite{Using the GNAT Programming Studio}, which describes the GPS
532 Integrated Development Environment.
533
534 @item
535 @cite{GNAT Programming Studio Tutorial}, which introduces the
536 main GPS features through examples.
537 @end ifset
538
539 @item
540 @cite{Ada 95 Reference Manual}, which contains reference
541 material for the Ada 95 programming language.
542
543 @item
544 @cite{Ada 2005 Reference Manual}, which contains reference
545 material for the Ada 2005 programming language.
546
547 @item
548 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
549 @ifset vms
550 in the GNU:[DOCS] directory,
551 @end ifset
552 for all details on the use of the GNU source-level debugger.
553
554 @item
555 @xref{Top,, The extensible self-documenting text editor, emacs,
556 GNU Emacs Manual},
557 @ifset vms
558 located in the GNU:[DOCS] directory if the EMACS kit is installed,
559 @end ifset
560 for full information on the extensible editor and programming
561 environment Emacs.
562
563 @end itemize
564
565 @c **************
566 @node Conventions
567 @unnumberedsec Conventions
568 @cindex Conventions
569 @cindex Typographical conventions
570
571 @noindent
572 Following are examples of the typographical and graphic conventions used
573 in this guide:
574
575 @itemize @bullet
576 @item
577 @code{Functions}, @command{utility program names}, @code{standard names},
578 and @code{classes}.
579
580 @item
581 @option{Option flags}
582
583 @item
584 @file{File names}, @samp{button names}, and @samp{field names}.
585
586 @item
587 @code{Variables}, @env{environment variables}, and @var{metasyntactic
588 variables}.
589
590 @item
591 @emph{Emphasis}.
592
593 @item
594 @r{[}optional information or parameters@r{]}
595
596 @item
597 Examples are described by text
598 @smallexample
599 and then shown this way.
600 @end smallexample
601 @end itemize
602
603 @noindent
604 Commands that are entered by the user are preceded in this manual by the
605 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
606 uses this sequence as a prompt, then the commands will appear exactly as
607 you see them in the manual. If your system uses some other prompt, then
608 the command will appear with the @code{$} replaced by whatever prompt
609 character you are using.
610
611 @ifset unw
612 Full file names are shown with the ``@code{/}'' character
613 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
614 If you are using GNAT on a Windows platform, please note that
615 the ``@code{\}'' character should be used instead.
616 @end ifset
617
618 @c ****************************
619 @node Getting Started with GNAT
620 @chapter Getting Started with GNAT
621
622 @noindent
623 This chapter describes some simple ways of using GNAT to build
624 executable Ada programs.
625 @ifset unw
626 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
627 show how to use the command line environment.
628 @ref{Introduction to GPS}, provides a brief
629 introduction to the GNAT Programming Studio, a visually-oriented
630 Integrated Development Environment for GNAT.
631 GPS offers a graphical ``look and feel'', support for development in
632 other programming languages, comprehensive browsing features, and
633 many other capabilities.
634 For information on GPS please refer to
635 @cite{Using the GNAT Programming Studio}.
636 @end ifset
637
638 @menu
639 * Running GNAT::
640 * Running a Simple Ada Program::
641 * Running a Program with Multiple Units::
642 * Using the gnatmake Utility::
643 @ifset vms
644 * Editing with Emacs::
645 @end ifset
646 @ifclear vms
647 * Introduction to GPS::
648 @end ifclear
649 @end menu
650
651 @node Running GNAT
652 @section Running GNAT
653
654 @noindent
655 Three steps are needed to create an executable file from an Ada source
656 file:
657
658 @enumerate
659 @item
660 The source file(s) must be compiled.
661 @item
662 The file(s) must be bound using the GNAT binder.
663 @item
664 All appropriate object files must be linked to produce an executable.
665 @end enumerate
666
667 @noindent
668 All three steps are most commonly handled by using the @command{gnatmake}
669 utility program that, given the name of the main program, automatically
670 performs the necessary compilation, binding and linking steps.
671
672 @node Running a Simple Ada Program
673 @section Running a Simple Ada Program
674
675 @noindent
676 Any text editor may be used to prepare an Ada program.
677 (If @code{Emacs} is
678 used, the optional Ada mode may be helpful in laying out the program.)
679 The
680 program text is a normal text file. We will assume in our initial
681 example that you have used your editor to prepare the following
682 standard format text file:
683
684 @smallexample @c ada
685 @cartouche
686 with Ada.Text_IO; use Ada.Text_IO;
687 procedure Hello is
688 begin
689 Put_Line ("Hello WORLD!");
690 end Hello;
691 @end cartouche
692 @end smallexample
693
694 @noindent
695 This file should be named @file{hello.adb}.
696 With the normal default file naming conventions, GNAT requires
697 that each file
698 contain a single compilation unit whose file name is the
699 unit name,
700 with periods replaced by hyphens; the
701 extension is @file{ads} for a
702 spec and @file{adb} for a body.
703 You can override this default file naming convention by use of the
704 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
705 Alternatively, if you want to rename your files according to this default
706 convention, which is probably more convenient if you will be using GNAT
707 for all your compilations, then the @code{gnatchop} utility
708 can be used to generate correctly-named source files
709 (@pxref{Renaming Files with gnatchop}).
710
711 You can compile the program using the following command (@code{$} is used
712 as the command prompt in the examples in this document):
713
714 @smallexample
715 $ gcc -c hello.adb
716 @end smallexample
717
718 @noindent
719 @command{gcc} is the command used to run the compiler. This compiler is
720 capable of compiling programs in several languages, including Ada and
721 C. It assumes that you have given it an Ada program if the file extension is
722 either @file{.ads} or @file{.adb}, and it will then call
723 the GNAT compiler to compile the specified file.
724
725 @ifclear vms
726 The @option{-c} switch is required. It tells @command{gcc} to only do a
727 compilation. (For C programs, @command{gcc} can also do linking, but this
728 capability is not used directly for Ada programs, so the @option{-c}
729 switch must always be present.)
730 @end ifclear
731
732 This compile command generates a file
733 @file{hello.o}, which is the object
734 file corresponding to your Ada program. It also generates
735 an ``Ada Library Information'' file @file{hello.ali},
736 which contains additional information used to check
737 that an Ada program is consistent.
738 To build an executable file,
739 use @code{gnatbind} to bind the program
740 and @command{gnatlink} to link it. The
741 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
742 @file{ALI} file, but the default extension of @file{.ali} can
743 be omitted. This means that in the most common case, the argument
744 is simply the name of the main program:
745
746 @smallexample
747 $ gnatbind hello
748 $ gnatlink hello
749 @end smallexample
750
751 @noindent
752 A simpler method of carrying out these steps is to use
753 @command{gnatmake},
754 a master program that invokes all the required
755 compilation, binding and linking tools in the correct order. In particular,
756 @command{gnatmake} automatically recompiles any sources that have been
757 modified since they were last compiled, or sources that depend
758 on such modified sources, so that ``version skew'' is avoided.
759 @cindex Version skew (avoided by @command{gnatmake})
760
761 @smallexample
762 $ gnatmake hello.adb
763 @end smallexample
764
765 @noindent
766 The result is an executable program called @file{hello}, which can be
767 run by entering:
768
769 @smallexample
770 $ ^hello^RUN HELLO^
771 @end smallexample
772
773 @noindent
774 assuming that the current directory is on the search path
775 for executable programs.
776
777 @noindent
778 and, if all has gone well, you will see
779
780 @smallexample
781 Hello WORLD!
782 @end smallexample
783
784 @noindent
785 appear in response to this command.
786
787 @c ****************************************
788 @node Running a Program with Multiple Units
789 @section Running a Program with Multiple Units
790
791 @noindent
792 Consider a slightly more complicated example that has three files: a
793 main program, and the spec and body of a package:
794
795 @smallexample @c ada
796 @cartouche
797 @group
798 package Greetings is
799 procedure Hello;
800 procedure Goodbye;
801 end Greetings;
802
803 with Ada.Text_IO; use Ada.Text_IO;
804 package body Greetings is
805 procedure Hello is
806 begin
807 Put_Line ("Hello WORLD!");
808 end Hello;
809
810 procedure Goodbye is
811 begin
812 Put_Line ("Goodbye WORLD!");
813 end Goodbye;
814 end Greetings;
815 @end group
816
817 @group
818 with Greetings;
819 procedure Gmain is
820 begin
821 Greetings.Hello;
822 Greetings.Goodbye;
823 end Gmain;
824 @end group
825 @end cartouche
826 @end smallexample
827
828 @noindent
829 Following the one-unit-per-file rule, place this program in the
830 following three separate files:
831
832 @table @file
833 @item greetings.ads
834 spec of package @code{Greetings}
835
836 @item greetings.adb
837 body of package @code{Greetings}
838
839 @item gmain.adb
840 body of main program
841 @end table
842
843 @noindent
844 To build an executable version of
845 this program, we could use four separate steps to compile, bind, and link
846 the program, as follows:
847
848 @smallexample
849 $ gcc -c gmain.adb
850 $ gcc -c greetings.adb
851 $ gnatbind gmain
852 $ gnatlink gmain
853 @end smallexample
854
855 @noindent
856 Note that there is no required order of compilation when using GNAT.
857 In particular it is perfectly fine to compile the main program first.
858 Also, it is not necessary to compile package specs in the case where
859 there is an accompanying body; you only need to compile the body. If you want
860 to submit these files to the compiler for semantic checking and not code
861 generation, then use the
862 @option{-gnatc} switch:
863
864 @smallexample
865 $ gcc -c greetings.ads -gnatc
866 @end smallexample
867
868 @noindent
869 Although the compilation can be done in separate steps as in the
870 above example, in practice it is almost always more convenient
871 to use the @command{gnatmake} tool. All you need to know in this case
872 is the name of the main program's source file. The effect of the above four
873 commands can be achieved with a single one:
874
875 @smallexample
876 $ gnatmake gmain.adb
877 @end smallexample
878
879 @noindent
880 In the next section we discuss the advantages of using @command{gnatmake} in
881 more detail.
882
883 @c *****************************
884 @node Using the gnatmake Utility
885 @section Using the @command{gnatmake} Utility
886
887 @noindent
888 If you work on a program by compiling single components at a time using
889 @command{gcc}, you typically keep track of the units you modify. In order to
890 build a consistent system, you compile not only these units, but also any
891 units that depend on the units you have modified.
892 For example, in the preceding case,
893 if you edit @file{gmain.adb}, you only need to recompile that file. But if
894 you edit @file{greetings.ads}, you must recompile both
895 @file{greetings.adb} and @file{gmain.adb}, because both files contain
896 units that depend on @file{greetings.ads}.
897
898 @code{gnatbind} will warn you if you forget one of these compilation
899 steps, so that it is impossible to generate an inconsistent program as a
900 result of forgetting to do a compilation. Nevertheless it is tedious and
901 error-prone to keep track of dependencies among units.
902 One approach to handle the dependency-bookkeeping is to use a
903 makefile. However, makefiles present maintenance problems of their own:
904 if the dependencies change as you change the program, you must make
905 sure that the makefile is kept up-to-date manually, which is also an
906 error-prone process.
907
908 The @command{gnatmake} utility takes care of these details automatically.
909 Invoke it using either one of the following forms:
910
911 @smallexample
912 $ gnatmake gmain.adb
913 $ gnatmake ^gmain^GMAIN^
914 @end smallexample
915
916 @noindent
917 The argument is the name of the file containing the main program;
918 you may omit the extension. @command{gnatmake}
919 examines the environment, automatically recompiles any files that need
920 recompiling, and binds and links the resulting set of object files,
921 generating the executable file, @file{^gmain^GMAIN.EXE^}.
922 In a large program, it
923 can be extremely helpful to use @command{gnatmake}, because working out by hand
924 what needs to be recompiled can be difficult.
925
926 Note that @command{gnatmake}
927 takes into account all the Ada rules that
928 establish dependencies among units. These include dependencies that result
929 from inlining subprogram bodies, and from
930 generic instantiation. Unlike some other
931 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
932 found by the compiler on a previous compilation, which may possibly
933 be wrong when sources change. @command{gnatmake} determines the exact set of
934 dependencies from scratch each time it is run.
935
936 @ifset vms
937 @node Editing with Emacs
938 @section Editing with Emacs
939 @cindex Emacs
940
941 @noindent
942 Emacs is an extensible self-documenting text editor that is available in a
943 separate VMSINSTAL kit.
944
945 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
946 click on the Emacs Help menu and run the Emacs Tutorial.
947 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
948 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
949
950 Documentation on Emacs and other tools is available in Emacs under the
951 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
952 use the middle mouse button to select a topic (e.g.@: Emacs).
953
954 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
955 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
956 get to the Emacs manual.
957 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
958 prompt.
959
960 The tutorial is highly recommended in order to learn the intricacies of Emacs,
961 which is sufficiently extensible to provide for a complete programming
962 environment and shell for the sophisticated user.
963 @end ifset
964
965 @ifclear vms
966 @node Introduction to GPS
967 @section Introduction to GPS
968 @cindex GPS (GNAT Programming Studio)
969 @cindex GNAT Programming Studio (GPS)
970 @noindent
971 Although the command line interface (@command{gnatmake}, etc.) alone
972 is sufficient, a graphical Interactive Development
973 Environment can make it easier for you to compose, navigate, and debug
974 programs. This section describes the main features of GPS
975 (``GNAT Programming Studio''), the GNAT graphical IDE.
976 You will see how to use GPS to build and debug an executable, and
977 you will also learn some of the basics of the GNAT ``project'' facility.
978
979 GPS enables you to do much more than is presented here;
980 e.g., you can produce a call graph, interface to a third-party
981 Version Control System, and inspect the generated assembly language
982 for a program.
983 Indeed, GPS also supports languages other than Ada.
984 Such additional information, and an explanation of all of the GPS menu
985 items. may be found in the on-line help, which includes
986 a user's guide and a tutorial (these are also accessible from the GNAT
987 startup menu).
988
989 @menu
990 * Building a New Program with GPS::
991 * Simple Debugging with GPS::
992 @end menu
993
994 @node Building a New Program with GPS
995 @subsection Building a New Program with GPS
996 @noindent
997 GPS invokes the GNAT compilation tools using information
998 contained in a @emph{project} (also known as a @emph{project file}):
999 a collection of properties such
1000 as source directories, identities of main subprograms, tool switches, etc.,
1001 and their associated values.
1002 See @ref{GNAT Project Manager} for details.
1003 In order to run GPS, you will need to either create a new project
1004 or else open an existing one.
1005
1006 This section will explain how you can use GPS to create a project,
1007 to associate Ada source files with a project, and to build and run
1008 programs.
1009
1010 @enumerate
1011 @item @emph{Creating a project}
1012
1013 Invoke GPS, either from the command line or the platform's IDE.
1014 After it starts, GPS will display a ``Welcome'' screen with three
1015 radio buttons:
1016
1017 @itemize @bullet
1018 @item
1019 @code{Start with default project in directory}
1020
1021 @item
1022 @code{Create new project with wizard}
1023
1024 @item
1025 @code{Open existing project}
1026 @end itemize
1027
1028 @noindent
1029 Select @code{Create new project with wizard} and press @code{OK}.
1030 A new window will appear. In the text box labeled with
1031 @code{Enter the name of the project to create}, type @file{sample}
1032 as the project name.
1033 In the next box, browse to choose the directory in which you
1034 would like to create the project file.
1035 After selecting an appropriate directory, press @code{Forward}.
1036
1037 A window will appear with the title
1038 @code{Version Control System Configuration}.
1039 Simply press @code{Forward}.
1040
1041 A window will appear with the title
1042 @code{Please select the source directories for this project}.
1043 The directory that you specified for the project file will be selected
1044 by default as the one to use for sources; simply press @code{Forward}.
1045
1046 A window will appear with the title
1047 @code{Please select the build directory for this project}.
1048 The directory that you specified for the project file will be selected
1049 by default for object files and executables;
1050 simply press @code{Forward}.
1051
1052 A window will appear with the title
1053 @code{Please select the main units for this project}.
1054 You will supply this information later, after creating the source file.
1055 Simply press @code{Forward} for now.
1056
1057 A window will appear with the title
1058 @code{Please select the switches to build the project}.
1059 Press @code{Apply}. This will create a project file named
1060 @file{sample.prj} in the directory that you had specified.
1061
1062 @item @emph{Creating and saving the source file}
1063
1064 After you create the new project, a GPS window will appear, which is
1065 partitioned into two main sections:
1066
1067 @itemize @bullet
1068 @item
1069 A @emph{Workspace area}, initially greyed out, which you will use for
1070 creating and editing source files
1071
1072 @item
1073 Directly below, a @emph{Messages area}, which initially displays a
1074 ``Welcome'' message.
1075 (If the Messages area is not visible, drag its border upward to expand it.)
1076 @end itemize
1077
1078 @noindent
1079 Select @code{File} on the menu bar, and then the @code{New} command.
1080 The Workspace area will become white, and you can now
1081 enter the source program explicitly.
1082 Type the following text
1083
1084 @smallexample @c ada
1085 @group
1086 with Ada.Text_IO; use Ada.Text_IO;
1087 procedure Hello is
1088 begin
1089 Put_Line("Hello from GPS!");
1090 end Hello;
1091 @end group
1092 @end smallexample
1093
1094 @noindent
1095 Select @code{File}, then @code{Save As}, and enter the source file name
1096 @file{hello.adb}.
1097 The file will be saved in the same directory you specified as the
1098 location of the default project file.
1099
1100 @item @emph{Updating the project file}
1101
1102 You need to add the new source file to the project.
1103 To do this, select
1104 the @code{Project} menu and then @code{Edit project properties}.
1105 Click the @code{Main files} tab on the left, and then the
1106 @code{Add} button.
1107 Choose @file{hello.adb} from the list, and press @code{Open}.
1108 The project settings window will reflect this action.
1109 Click @code{OK}.
1110
1111 @item @emph{Building and running the program}
1112
1113 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1114 and select @file{hello.adb}.
1115 The Messages window will display the resulting invocations of @command{gcc},
1116 @command{gnatbind}, and @command{gnatlink}
1117 (reflecting the default switch settings from the
1118 project file that you created) and then a ``successful compilation/build''
1119 message.
1120
1121 To run the program, choose the @code{Build} menu, then @code{Run}, and
1122 select @command{hello}.
1123 An @emph{Arguments Selection} window will appear.
1124 There are no command line arguments, so just click @code{OK}.
1125
1126 The Messages window will now display the program's output (the string
1127 @code{Hello from GPS}), and at the bottom of the GPS window a status
1128 update is displayed (@code{Run: hello}).
1129 Close the GPS window (or select @code{File}, then @code{Exit}) to
1130 terminate this GPS session.
1131 @end enumerate
1132
1133 @node Simple Debugging with GPS
1134 @subsection Simple Debugging with GPS
1135 @noindent
1136 This section illustrates basic debugging techniques (setting breakpoints,
1137 examining/modifying variables, single stepping).
1138
1139 @enumerate
1140 @item @emph{Opening a project}
1141
1142 Start GPS and select @code{Open existing project}; browse to
1143 specify the project file @file{sample.prj} that you had created in the
1144 earlier example.
1145
1146 @item @emph{Creating a source file}
1147
1148 Select @code{File}, then @code{New}, and type in the following program:
1149
1150 @smallexample @c ada
1151 @group
1152 with Ada.Text_IO; use Ada.Text_IO;
1153 procedure Example is
1154 Line : String (1..80);
1155 N : Natural;
1156 begin
1157 Put_Line("Type a line of text at each prompt; an empty line to exit");
1158 loop
1159 Put(": ");
1160 Get_Line (Line, N);
1161 Put_Line (Line (1..N) );
1162 exit when N=0;
1163 end loop;
1164 end Example;
1165 @end group
1166 @end smallexample
1167
1168 @noindent
1169 Select @code{File}, then @code{Save as}, and enter the file name
1170 @file{example.adb}.
1171
1172 @item @emph{Updating the project file}
1173
1174 Add @code{Example} as a new main unit for the project:
1175 @enumerate a
1176 @item
1177 Select @code{Project}, then @code{Edit Project Properties}.
1178
1179 @item
1180 Select the @code{Main files} tab, click @code{Add}, then
1181 select the file @file{example.adb} from the list, and
1182 click @code{Open}.
1183 You will see the file name appear in the list of main units
1184
1185 @item
1186 Click @code{OK}
1187 @end enumerate
1188
1189 @item @emph{Building/running the executable}
1190
1191 To build the executable
1192 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1193
1194 Run the program to see its effect (in the Messages area).
1195 Each line that you enter is displayed; an empty line will
1196 cause the loop to exit and the program to terminate.
1197
1198 @item @emph{Debugging the program}
1199
1200 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1201 which are required for debugging, are on by default when you create
1202 a new project.
1203 Thus unless you intentionally remove these settings, you will be able
1204 to debug any program that you develop using GPS.
1205
1206 @enumerate a
1207 @item @emph{Initializing}
1208
1209 Select @code{Debug}, then @code{Initialize}, then @file{example}
1210
1211 @item @emph{Setting a breakpoint}
1212
1213 After performing the initialization step, you will observe a small
1214 icon to the right of each line number.
1215 This serves as a toggle for breakpoints; clicking the icon will
1216 set a breakpoint at the corresponding line (the icon will change to
1217 a red circle with an ``x''), and clicking it again
1218 will remove the breakpoint / reset the icon.
1219
1220 For purposes of this example, set a breakpoint at line 10 (the
1221 statement @code{Put_Line@ (Line@ (1..N));}
1222
1223 @item @emph{Starting program execution}
1224
1225 Select @code{Debug}, then @code{Run}. When the
1226 @code{Program Arguments} window appears, click @code{OK}.
1227 A console window will appear; enter some line of text,
1228 e.g.@: @code{abcde}, at the prompt.
1229 The program will pause execution when it gets to the
1230 breakpoint, and the corresponding line is highlighted.
1231
1232 @item @emph{Examining a variable}
1233
1234 Move the mouse over one of the occurrences of the variable @code{N}.
1235 You will see the value (5) displayed, in ``tool tip'' fashion.
1236 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1237 You will see information about @code{N} appear in the @code{Debugger Data}
1238 pane, showing the value as 5.
1239
1240 @item @emph{Assigning a new value to a variable}
1241
1242 Right click on the @code{N} in the @code{Debugger Data} pane, and
1243 select @code{Set value of N}.
1244 When the input window appears, enter the value @code{4} and click
1245 @code{OK}.
1246 This value does not automatically appear in the @code{Debugger Data}
1247 pane; to see it, right click again on the @code{N} in the
1248 @code{Debugger Data} pane and select @code{Update value}.
1249 The new value, 4, will appear in red.
1250
1251 @item @emph{Single stepping}
1252
1253 Select @code{Debug}, then @code{Next}.
1254 This will cause the next statement to be executed, in this case the
1255 call of @code{Put_Line} with the string slice.
1256 Notice in the console window that the displayed string is simply
1257 @code{abcd} and not @code{abcde} which you had entered.
1258 This is because the upper bound of the slice is now 4 rather than 5.
1259
1260 @item @emph{Removing a breakpoint}
1261
1262 Toggle the breakpoint icon at line 10.
1263
1264 @item @emph{Resuming execution from a breakpoint}
1265
1266 Select @code{Debug}, then @code{Continue}.
1267 The program will reach the next iteration of the loop, and
1268 wait for input after displaying the prompt.
1269 This time, just hit the @kbd{Enter} key.
1270 The value of @code{N} will be 0, and the program will terminate.
1271 The console window will disappear.
1272 @end enumerate
1273 @end enumerate
1274 @end ifclear
1275
1276 @node The GNAT Compilation Model
1277 @chapter The GNAT Compilation Model
1278 @cindex GNAT compilation model
1279 @cindex Compilation model
1280
1281 @menu
1282 * Source Representation::
1283 * Foreign Language Representation::
1284 * File Naming Rules::
1285 * Using Other File Names::
1286 * Alternative File Naming Schemes::
1287 * Generating Object Files::
1288 * Source Dependencies::
1289 * The Ada Library Information Files::
1290 * Binding an Ada Program::
1291 * Mixed Language Programming::
1292 @ifclear vms
1293 * Building Mixed Ada & C++ Programs::
1294 * Comparison between GNAT and C/C++ Compilation Models::
1295 @end ifclear
1296 * Comparison between GNAT and Conventional Ada Library Models::
1297 @ifset vms
1298 * Placement of temporary files::
1299 @end ifset
1300 @end menu
1301
1302 @noindent
1303 This chapter describes the compilation model used by GNAT. Although
1304 similar to that used by other languages, such as C and C++, this model
1305 is substantially different from the traditional Ada compilation models,
1306 which are based on a library. The model is initially described without
1307 reference to the library-based model. If you have not previously used an
1308 Ada compiler, you need only read the first part of this chapter. The
1309 last section describes and discusses the differences between the GNAT
1310 model and the traditional Ada compiler models. If you have used other
1311 Ada compilers, this section will help you to understand those
1312 differences, and the advantages of the GNAT model.
1313
1314 @node Source Representation
1315 @section Source Representation
1316 @cindex Latin-1
1317
1318 @noindent
1319 Ada source programs are represented in standard text files, using
1320 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1321 7-bit ASCII set, plus additional characters used for
1322 representing foreign languages (@pxref{Foreign Language Representation}
1323 for support of non-USA character sets). The format effector characters
1324 are represented using their standard ASCII encodings, as follows:
1325
1326 @table @code
1327 @item VT
1328 @findex VT
1329 Vertical tab, @code{16#0B#}
1330
1331 @item HT
1332 @findex HT
1333 Horizontal tab, @code{16#09#}
1334
1335 @item CR
1336 @findex CR
1337 Carriage return, @code{16#0D#}
1338
1339 @item LF
1340 @findex LF
1341 Line feed, @code{16#0A#}
1342
1343 @item FF
1344 @findex FF
1345 Form feed, @code{16#0C#}
1346 @end table
1347
1348 @noindent
1349 Source files are in standard text file format. In addition, GNAT will
1350 recognize a wide variety of stream formats, in which the end of
1351 physical lines is marked by any of the following sequences:
1352 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1353 in accommodating files that are imported from other operating systems.
1354
1355 @cindex End of source file
1356 @cindex Source file, end
1357 @findex SUB
1358 The end of a source file is normally represented by the physical end of
1359 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1360 recognized as signalling the end of the source file. Again, this is
1361 provided for compatibility with other operating systems where this
1362 code is used to represent the end of file.
1363
1364 Each file contains a single Ada compilation unit, including any pragmas
1365 associated with the unit. For example, this means you must place a
1366 package declaration (a package @dfn{spec}) and the corresponding body in
1367 separate files. An Ada @dfn{compilation} (which is a sequence of
1368 compilation units) is represented using a sequence of files. Similarly,
1369 you will place each subunit or child unit in a separate file.
1370
1371 @node Foreign Language Representation
1372 @section Foreign Language Representation
1373
1374 @noindent
1375 GNAT supports the standard character sets defined in Ada as well as
1376 several other non-standard character sets for use in localized versions
1377 of the compiler (@pxref{Character Set Control}).
1378 @menu
1379 * Latin-1::
1380 * Other 8-Bit Codes::
1381 * Wide Character Encodings::
1382 @end menu
1383
1384 @node Latin-1
1385 @subsection Latin-1
1386 @cindex Latin-1
1387
1388 @noindent
1389 The basic character set is Latin-1. This character set is defined by ISO
1390 standard 8859, part 1. The lower half (character codes @code{16#00#}
1391 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1392 half is used to represent additional characters. These include extended letters
1393 used by European languages, such as French accents, the vowels with umlauts
1394 used in German, and the extra letter A-ring used in Swedish.
1395
1396 @findex Ada.Characters.Latin_1
1397 For a complete list of Latin-1 codes and their encodings, see the source
1398 file of library unit @code{Ada.Characters.Latin_1} in file
1399 @file{a-chlat1.ads}.
1400 You may use any of these extended characters freely in character or
1401 string literals. In addition, the extended characters that represent
1402 letters can be used in identifiers.
1403
1404 @node Other 8-Bit Codes
1405 @subsection Other 8-Bit Codes
1406
1407 @noindent
1408 GNAT also supports several other 8-bit coding schemes:
1409
1410 @table @asis
1411 @item ISO 8859-2 (Latin-2)
1412 @cindex Latin-2
1413 @cindex ISO 8859-2
1414 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1415 equivalence.
1416
1417 @item ISO 8859-3 (Latin-3)
1418 @cindex Latin-3
1419 @cindex ISO 8859-3
1420 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1421 equivalence.
1422
1423 @item ISO 8859-4 (Latin-4)
1424 @cindex Latin-4
1425 @cindex ISO 8859-4
1426 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1427 equivalence.
1428
1429 @item ISO 8859-5 (Cyrillic)
1430 @cindex ISO 8859-5
1431 @cindex Cyrillic
1432 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1433 lowercase equivalence.
1434
1435 @item ISO 8859-15 (Latin-9)
1436 @cindex ISO 8859-15
1437 @cindex Latin-9
1438 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1439 lowercase equivalence
1440
1441 @item IBM PC (code page 437)
1442 @cindex code page 437
1443 This code page is the normal default for PCs in the U.S. It corresponds
1444 to the original IBM PC character set. This set has some, but not all, of
1445 the extended Latin-1 letters, but these letters do not have the same
1446 encoding as Latin-1. In this mode, these letters are allowed in
1447 identifiers with uppercase and lowercase equivalence.
1448
1449 @item IBM PC (code page 850)
1450 @cindex code page 850
1451 This code page is a modification of 437 extended to include all the
1452 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1453 mode, all these letters are allowed in identifiers with uppercase and
1454 lowercase equivalence.
1455
1456 @item Full Upper 8-bit
1457 Any character in the range 80-FF allowed in identifiers, and all are
1458 considered distinct. In other words, there are no uppercase and lowercase
1459 equivalences in this range. This is useful in conjunction with
1460 certain encoding schemes used for some foreign character sets (e.g.,
1461 the typical method of representing Chinese characters on the PC).
1462
1463 @item No Upper-Half
1464 No upper-half characters in the range 80-FF are allowed in identifiers.
1465 This gives Ada 83 compatibility for identifier names.
1466 @end table
1467
1468 @noindent
1469 For precise data on the encodings permitted, and the uppercase and lowercase
1470 equivalences that are recognized, see the file @file{csets.adb} in
1471 the GNAT compiler sources. You will need to obtain a full source release
1472 of GNAT to obtain this file.
1473
1474 @node Wide Character Encodings
1475 @subsection Wide Character Encodings
1476
1477 @noindent
1478 GNAT allows wide character codes to appear in character and string
1479 literals, and also optionally in identifiers, by means of the following
1480 possible encoding schemes:
1481
1482 @table @asis
1483
1484 @item Hex Coding
1485 In this encoding, a wide character is represented by the following five
1486 character sequence:
1487
1488 @smallexample
1489 ESC a b c d
1490 @end smallexample
1491
1492 @noindent
1493 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1494 characters (using uppercase letters) of the wide character code. For
1495 example, ESC A345 is used to represent the wide character with code
1496 @code{16#A345#}.
1497 This scheme is compatible with use of the full Wide_Character set.
1498
1499 @item Upper-Half Coding
1500 @cindex Upper-Half Coding
1501 The wide character with encoding @code{16#abcd#} where the upper bit is on
1502 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1503 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1504 character, but is not required to be in the upper half. This method can
1505 be also used for shift-JIS or EUC, where the internal coding matches the
1506 external coding.
1507
1508 @item Shift JIS Coding
1509 @cindex Shift JIS Coding
1510 A wide character is represented by a two-character sequence,
1511 @code{16#ab#} and
1512 @code{16#cd#}, with the restrictions described for upper-half encoding as
1513 described above. The internal character code is the corresponding JIS
1514 character according to the standard algorithm for Shift-JIS
1515 conversion. Only characters defined in the JIS code set table can be
1516 used with this encoding method.
1517
1518 @item EUC Coding
1519 @cindex EUC Coding
1520 A wide character is represented by a two-character sequence
1521 @code{16#ab#} and
1522 @code{16#cd#}, with both characters being in the upper half. The internal
1523 character code is the corresponding JIS character according to the EUC
1524 encoding algorithm. Only characters defined in the JIS code set table
1525 can be used with this encoding method.
1526
1527 @item UTF-8 Coding
1528 A wide character is represented using
1529 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1530 10646-1/Am.2. Depending on the character value, the representation
1531 is a one, two, or three byte sequence:
1532 @smallexample
1533 @iftex
1534 @leftskip=.7cm
1535 @end iftex
1536 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1537 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1538 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1539
1540 @end smallexample
1541
1542 @noindent
1543 where the @var{xxx} bits correspond to the left-padded bits of the
1544 16-bit character value. Note that all lower half ASCII characters
1545 are represented as ASCII bytes and all upper half characters and
1546 other wide characters are represented as sequences of upper-half
1547 (The full UTF-8 scheme allows for encoding 31-bit characters as
1548 6-byte sequences, but in this implementation, all UTF-8 sequences
1549 of four or more bytes length will be treated as illegal).
1550 @item Brackets Coding
1551 In this encoding, a wide character is represented by the following eight
1552 character sequence:
1553
1554 @smallexample
1555 [ " a b c d " ]
1556 @end smallexample
1557
1558 @noindent
1559 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1560 characters (using uppercase letters) of the wide character code. For
1561 example, [``A345''] is used to represent the wide character with code
1562 @code{16#A345#}. It is also possible (though not required) to use the
1563 Brackets coding for upper half characters. For example, the code
1564 @code{16#A3#} can be represented as @code{[``A3'']}.
1565
1566 This scheme is compatible with use of the full Wide_Character set,
1567 and is also the method used for wide character encoding in the standard
1568 ACVC (Ada Compiler Validation Capability) test suite distributions.
1569
1570 @end table
1571
1572 @noindent
1573 Note: Some of these coding schemes do not permit the full use of the
1574 Ada character set. For example, neither Shift JIS, nor EUC allow the
1575 use of the upper half of the Latin-1 set.
1576
1577 @node File Naming Rules
1578 @section File Naming Rules
1579
1580 @noindent
1581 The default file name is determined by the name of the unit that the
1582 file contains. The name is formed by taking the full expanded name of
1583 the unit and replacing the separating dots with hyphens and using
1584 ^lowercase^uppercase^ for all letters.
1585
1586 An exception arises if the file name generated by the above rules starts
1587 with one of the characters
1588 @ifset vms
1589 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1590 @end ifset
1591 @ifclear vms
1592 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1593 @end ifclear
1594 and the second character is a
1595 minus. In this case, the character ^tilde^dollar sign^ is used in place
1596 of the minus. The reason for this special rule is to avoid clashes with
1597 the standard names for child units of the packages System, Ada,
1598 Interfaces, and GNAT, which use the prefixes
1599 @ifset vms
1600 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
1601 @end ifset
1602 @ifclear vms
1603 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
1604 @end ifclear
1605 respectively.
1606
1607 The file extension is @file{.ads} for a spec and
1608 @file{.adb} for a body. The following list shows some
1609 examples of these rules.
1610
1611 @table @file
1612 @item main.ads
1613 Main (spec)
1614 @item main.adb
1615 Main (body)
1616 @item arith_functions.ads
1617 Arith_Functions (package spec)
1618 @item arith_functions.adb
1619 Arith_Functions (package body)
1620 @item func-spec.ads
1621 Func.Spec (child package spec)
1622 @item func-spec.adb
1623 Func.Spec (child package body)
1624 @item main-sub.adb
1625 Sub (subunit of Main)
1626 @item ^a~bad.adb^A$BAD.ADB^
1627 A.Bad (child package body)
1628 @end table
1629
1630 @noindent
1631 Following these rules can result in excessively long
1632 file names if corresponding
1633 unit names are long (for example, if child units or subunits are
1634 heavily nested). An option is available to shorten such long file names
1635 (called file name ``krunching''). This may be particularly useful when
1636 programs being developed with GNAT are to be used on operating systems
1637 with limited file name lengths. @xref{Using gnatkr}.
1638
1639 Of course, no file shortening algorithm can guarantee uniqueness over
1640 all possible unit names; if file name krunching is used, it is your
1641 responsibility to ensure no name clashes occur. Alternatively you
1642 can specify the exact file names that you want used, as described
1643 in the next section. Finally, if your Ada programs are migrating from a
1644 compiler with a different naming convention, you can use the gnatchop
1645 utility to produce source files that follow the GNAT naming conventions.
1646 (For details @pxref{Renaming Files with gnatchop}.)
1647
1648 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
1649 systems, case is not significant. So for example on @code{Windows XP}
1650 if the canonical name is @code{main-sub.adb}, you can use the file name
1651 @code{Main-Sub.adb} instead. However, case is significant for other
1652 operating systems, so for example, if you want to use other than
1653 canonically cased file names on a Unix system, you need to follow
1654 the procedures described in the next section.
1655
1656 @node Using Other File Names
1657 @section Using Other File Names
1658 @cindex File names
1659
1660 @noindent
1661 In the previous section, we have described the default rules used by
1662 GNAT to determine the file name in which a given unit resides. It is
1663 often convenient to follow these default rules, and if you follow them,
1664 the compiler knows without being explicitly told where to find all
1665 the files it needs.
1666
1667 However, in some cases, particularly when a program is imported from
1668 another Ada compiler environment, it may be more convenient for the
1669 programmer to specify which file names contain which units. GNAT allows
1670 arbitrary file names to be used by means of the Source_File_Name pragma.
1671 The form of this pragma is as shown in the following examples:
1672 @cindex Source_File_Name pragma
1673
1674 @smallexample @c ada
1675 @cartouche
1676 pragma Source_File_Name (My_Utilities.Stacks,
1677 Spec_File_Name => "myutilst_a.ada");
1678 pragma Source_File_name (My_Utilities.Stacks,
1679 Body_File_Name => "myutilst.ada");
1680 @end cartouche
1681 @end smallexample
1682
1683 @noindent
1684 As shown in this example, the first argument for the pragma is the unit
1685 name (in this example a child unit). The second argument has the form
1686 of a named association. The identifier
1687 indicates whether the file name is for a spec or a body;
1688 the file name itself is given by a string literal.
1689
1690 The source file name pragma is a configuration pragma, which means that
1691 normally it will be placed in the @file{gnat.adc}
1692 file used to hold configuration
1693 pragmas that apply to a complete compilation environment.
1694 For more details on how the @file{gnat.adc} file is created and used
1695 see @ref{Handling of Configuration Pragmas}.
1696 @cindex @file{gnat.adc}
1697
1698 @ifclear vms
1699 GNAT allows completely arbitrary file names to be specified using the
1700 source file name pragma. However, if the file name specified has an
1701 extension other than @file{.ads} or @file{.adb} it is necessary to use
1702 a special syntax when compiling the file. The name in this case must be
1703 preceded by the special sequence @option{-x} followed by a space and the name
1704 of the language, here @code{ada}, as in:
1705
1706 @smallexample
1707 $ gcc -c -x ada peculiar_file_name.sim
1708 @end smallexample
1709 @end ifclear
1710
1711 @noindent
1712 @command{gnatmake} handles non-standard file names in the usual manner (the
1713 non-standard file name for the main program is simply used as the
1714 argument to gnatmake). Note that if the extension is also non-standard,
1715 then it must be included in the @command{gnatmake} command, it may not
1716 be omitted.
1717
1718 @node Alternative File Naming Schemes
1719 @section Alternative File Naming Schemes
1720 @cindex File naming schemes, alternative
1721 @cindex File names
1722
1723 In the previous section, we described the use of the @code{Source_File_Name}
1724 pragma to allow arbitrary names to be assigned to individual source files.
1725 However, this approach requires one pragma for each file, and especially in
1726 large systems can result in very long @file{gnat.adc} files, and also create
1727 a maintenance problem.
1728
1729 GNAT also provides a facility for specifying systematic file naming schemes
1730 other than the standard default naming scheme previously described. An
1731 alternative scheme for naming is specified by the use of
1732 @code{Source_File_Name} pragmas having the following format:
1733 @cindex Source_File_Name pragma
1734
1735 @smallexample @c ada
1736 pragma Source_File_Name (
1737 Spec_File_Name => FILE_NAME_PATTERN
1738 @r{[},Casing => CASING_SPEC@r{]}
1739 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1740
1741 pragma Source_File_Name (
1742 Body_File_Name => FILE_NAME_PATTERN
1743 @r{[},Casing => CASING_SPEC@r{]}
1744 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1745
1746 pragma Source_File_Name (
1747 Subunit_File_Name => FILE_NAME_PATTERN
1748 @r{[},Casing => CASING_SPEC@r{]}
1749 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1750
1751 FILE_NAME_PATTERN ::= STRING_LITERAL
1752 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1753 @end smallexample
1754
1755 @noindent
1756 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1757 It contains a single asterisk character, and the unit name is substituted
1758 systematically for this asterisk. The optional parameter
1759 @code{Casing} indicates
1760 whether the unit name is to be all upper-case letters, all lower-case letters,
1761 or mixed-case. If no
1762 @code{Casing} parameter is used, then the default is all
1763 ^lower-case^upper-case^.
1764
1765 The optional @code{Dot_Replacement} string is used to replace any periods
1766 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1767 argument is used then separating dots appear unchanged in the resulting
1768 file name.
1769 Although the above syntax indicates that the
1770 @code{Casing} argument must appear
1771 before the @code{Dot_Replacement} argument, but it
1772 is also permissible to write these arguments in the opposite order.
1773
1774 As indicated, it is possible to specify different naming schemes for
1775 bodies, specs, and subunits. Quite often the rule for subunits is the
1776 same as the rule for bodies, in which case, there is no need to give
1777 a separate @code{Subunit_File_Name} rule, and in this case the
1778 @code{Body_File_name} rule is used for subunits as well.
1779
1780 The separate rule for subunits can also be used to implement the rather
1781 unusual case of a compilation environment (e.g.@: a single directory) which
1782 contains a subunit and a child unit with the same unit name. Although
1783 both units cannot appear in the same partition, the Ada Reference Manual
1784 allows (but does not require) the possibility of the two units coexisting
1785 in the same environment.
1786
1787 The file name translation works in the following steps:
1788
1789 @itemize @bullet
1790
1791 @item
1792 If there is a specific @code{Source_File_Name} pragma for the given unit,
1793 then this is always used, and any general pattern rules are ignored.
1794
1795 @item
1796 If there is a pattern type @code{Source_File_Name} pragma that applies to
1797 the unit, then the resulting file name will be used if the file exists. If
1798 more than one pattern matches, the latest one will be tried first, and the
1799 first attempt resulting in a reference to a file that exists will be used.
1800
1801 @item
1802 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1803 for which the corresponding file exists, then the standard GNAT default
1804 naming rules are used.
1805
1806 @end itemize
1807
1808 @noindent
1809 As an example of the use of this mechanism, consider a commonly used scheme
1810 in which file names are all lower case, with separating periods copied
1811 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
1812 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
1813 two pragmas appear:
1814
1815 @smallexample @c ada
1816 pragma Source_File_Name
1817 (Spec_File_Name => "*.1.ada");
1818 pragma Source_File_Name
1819 (Body_File_Name => "*.2.ada");
1820 @end smallexample
1821
1822 @noindent
1823 The default GNAT scheme is actually implemented by providing the following
1824 default pragmas internally:
1825
1826 @smallexample @c ada
1827 pragma Source_File_Name
1828 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
1829 pragma Source_File_Name
1830 (Body_File_Name => "*.adb", Dot_Replacement => "-");
1831 @end smallexample
1832
1833 @noindent
1834 Our final example implements a scheme typically used with one of the
1835 Ada 83 compilers, where the separator character for subunits was ``__''
1836 (two underscores), specs were identified by adding @file{_.ADA}, bodies
1837 by adding @file{.ADA}, and subunits by
1838 adding @file{.SEP}. All file names were
1839 upper case. Child units were not present of course since this was an
1840 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1841 the same double underscore separator for child units.
1842
1843 @smallexample @c ada
1844 pragma Source_File_Name
1845 (Spec_File_Name => "*_.ADA",
1846 Dot_Replacement => "__",
1847 Casing = Uppercase);
1848 pragma Source_File_Name
1849 (Body_File_Name => "*.ADA",
1850 Dot_Replacement => "__",
1851 Casing = Uppercase);
1852 pragma Source_File_Name
1853 (Subunit_File_Name => "*.SEP",
1854 Dot_Replacement => "__",
1855 Casing = Uppercase);
1856 @end smallexample
1857
1858 @node Generating Object Files
1859 @section Generating Object Files
1860
1861 @noindent
1862 An Ada program consists of a set of source files, and the first step in
1863 compiling the program is to generate the corresponding object files.
1864 These are generated by compiling a subset of these source files.
1865 The files you need to compile are the following:
1866
1867 @itemize @bullet
1868 @item
1869 If a package spec has no body, compile the package spec to produce the
1870 object file for the package.
1871
1872 @item
1873 If a package has both a spec and a body, compile the body to produce the
1874 object file for the package. The source file for the package spec need
1875 not be compiled in this case because there is only one object file, which
1876 contains the code for both the spec and body of the package.
1877
1878 @item
1879 For a subprogram, compile the subprogram body to produce the object file
1880 for the subprogram. The spec, if one is present, is as usual in a
1881 separate file, and need not be compiled.
1882
1883 @item
1884 @cindex Subunits
1885 In the case of subunits, only compile the parent unit. A single object
1886 file is generated for the entire subunit tree, which includes all the
1887 subunits.
1888
1889 @item
1890 Compile child units independently of their parent units
1891 (though, of course, the spec of all the ancestor unit must be present in order
1892 to compile a child unit).
1893
1894 @item
1895 @cindex Generics
1896 Compile generic units in the same manner as any other units. The object
1897 files in this case are small dummy files that contain at most the
1898 flag used for elaboration checking. This is because GNAT always handles generic
1899 instantiation by means of macro expansion. However, it is still necessary to
1900 compile generic units, for dependency checking and elaboration purposes.
1901 @end itemize
1902
1903 @noindent
1904 The preceding rules describe the set of files that must be compiled to
1905 generate the object files for a program. Each object file has the same
1906 name as the corresponding source file, except that the extension is
1907 @file{.o} as usual.
1908
1909 You may wish to compile other files for the purpose of checking their
1910 syntactic and semantic correctness. For example, in the case where a
1911 package has a separate spec and body, you would not normally compile the
1912 spec. However, it is convenient in practice to compile the spec to make
1913 sure it is error-free before compiling clients of this spec, because such
1914 compilations will fail if there is an error in the spec.
1915
1916 GNAT provides an option for compiling such files purely for the
1917 purposes of checking correctness; such compilations are not required as
1918 part of the process of building a program. To compile a file in this
1919 checking mode, use the @option{-gnatc} switch.
1920
1921 @node Source Dependencies
1922 @section Source Dependencies
1923
1924 @noindent
1925 A given object file clearly depends on the source file which is compiled
1926 to produce it. Here we are using @dfn{depends} in the sense of a typical
1927 @code{make} utility; in other words, an object file depends on a source
1928 file if changes to the source file require the object file to be
1929 recompiled.
1930 In addition to this basic dependency, a given object may depend on
1931 additional source files as follows:
1932
1933 @itemize @bullet
1934 @item
1935 If a file being compiled @code{with}'s a unit @var{X}, the object file
1936 depends on the file containing the spec of unit @var{X}. This includes
1937 files that are @code{with}'ed implicitly either because they are parents
1938 of @code{with}'ed child units or they are run-time units required by the
1939 language constructs used in a particular unit.
1940
1941 @item
1942 If a file being compiled instantiates a library level generic unit, the
1943 object file depends on both the spec and body files for this generic
1944 unit.
1945
1946 @item
1947 If a file being compiled instantiates a generic unit defined within a
1948 package, the object file depends on the body file for the package as
1949 well as the spec file.
1950
1951 @item
1952 @findex Inline
1953 @cindex @option{-gnatn} switch
1954 If a file being compiled contains a call to a subprogram for which
1955 pragma @code{Inline} applies and inlining is activated with the
1956 @option{-gnatn} switch, the object file depends on the file containing the
1957 body of this subprogram as well as on the file containing the spec. Note
1958 that for inlining to actually occur as a result of the use of this switch,
1959 it is necessary to compile in optimizing mode.
1960
1961 @cindex @option{-gnatN} switch
1962 The use of @option{-gnatN} activates inlining optimization
1963 that is performed by the front end of the compiler. This inlining does
1964 not require that the code generation be optimized. Like @option{-gnatn},
1965 the use of this switch generates additional dependencies.
1966
1967 When using a gcc-based back end (in practice this means using any version
1968 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
1969 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
1970 Historically front end inlining was more extensive than the gcc back end
1971 inlining, but that is no longer the case.
1972
1973 @item
1974 If an object file @file{O} depends on the proper body of a subunit through
1975 inlining or instantiation, it depends on the parent unit of the subunit.
1976 This means that any modification of the parent unit or one of its subunits
1977 affects the compilation of @file{O}.
1978
1979 @item
1980 The object file for a parent unit depends on all its subunit body files.
1981
1982 @item
1983 The previous two rules meant that for purposes of computing dependencies and
1984 recompilation, a body and all its subunits are treated as an indivisible whole.
1985
1986 @noindent
1987 These rules are applied transitively: if unit @code{A} @code{with}'s
1988 unit @code{B}, whose elaboration calls an inlined procedure in package
1989 @code{C}, the object file for unit @code{A} will depend on the body of
1990 @code{C}, in file @file{c.adb}.
1991
1992 The set of dependent files described by these rules includes all the
1993 files on which the unit is semantically dependent, as dictated by the
1994 Ada language standard. However, it is a superset of what the
1995 standard describes, because it includes generic, inline, and subunit
1996 dependencies.
1997
1998 An object file must be recreated by recompiling the corresponding source
1999 file if any of the source files on which it depends are modified. For
2000 example, if the @code{make} utility is used to control compilation,
2001 the rule for an Ada object file must mention all the source files on
2002 which the object file depends, according to the above definition.
2003 The determination of the necessary
2004 recompilations is done automatically when one uses @command{gnatmake}.
2005 @end itemize
2006
2007 @node The Ada Library Information Files
2008 @section The Ada Library Information Files
2009 @cindex Ada Library Information files
2010 @cindex @file{ALI} files
2011
2012 @noindent
2013 Each compilation actually generates two output files. The first of these
2014 is the normal object file that has a @file{.o} extension. The second is a
2015 text file containing full dependency information. It has the same
2016 name as the source file, but an @file{.ali} extension.
2017 This file is known as the Ada Library Information (@file{ALI}) file.
2018 The following information is contained in the @file{ALI} file.
2019
2020 @itemize @bullet
2021 @item
2022 Version information (indicates which version of GNAT was used to compile
2023 the unit(s) in question)
2024
2025 @item
2026 Main program information (including priority and time slice settings,
2027 as well as the wide character encoding used during compilation).
2028
2029 @item
2030 List of arguments used in the @command{gcc} command for the compilation
2031
2032 @item
2033 Attributes of the unit, including configuration pragmas used, an indication
2034 of whether the compilation was successful, exception model used etc.
2035
2036 @item
2037 A list of relevant restrictions applying to the unit (used for consistency)
2038 checking.
2039
2040 @item
2041 Categorization information (e.g.@: use of pragma @code{Pure}).
2042
2043 @item
2044 Information on all @code{with}'ed units, including presence of
2045 @code{Elaborate} or @code{Elaborate_All} pragmas.
2046
2047 @item
2048 Information from any @code{Linker_Options} pragmas used in the unit
2049
2050 @item
2051 Information on the use of @code{Body_Version} or @code{Version}
2052 attributes in the unit.
2053
2054 @item
2055 Dependency information. This is a list of files, together with
2056 time stamp and checksum information. These are files on which
2057 the unit depends in the sense that recompilation is required
2058 if any of these units are modified.
2059
2060 @item
2061 Cross-reference data. Contains information on all entities referenced
2062 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2063 provide cross-reference information.
2064
2065 @end itemize
2066
2067 @noindent
2068 For a full detailed description of the format of the @file{ALI} file,
2069 see the source of the body of unit @code{Lib.Writ}, contained in file
2070 @file{lib-writ.adb} in the GNAT compiler sources.
2071
2072 @node Binding an Ada Program
2073 @section Binding an Ada Program
2074
2075 @noindent
2076 When using languages such as C and C++, once the source files have been
2077 compiled the only remaining step in building an executable program
2078 is linking the object modules together. This means that it is possible to
2079 link an inconsistent version of a program, in which two units have
2080 included different versions of the same header.
2081
2082 The rules of Ada do not permit such an inconsistent program to be built.
2083 For example, if two clients have different versions of the same package,
2084 it is illegal to build a program containing these two clients.
2085 These rules are enforced by the GNAT binder, which also determines an
2086 elaboration order consistent with the Ada rules.
2087
2088 The GNAT binder is run after all the object files for a program have
2089 been created. It is given the name of the main program unit, and from
2090 this it determines the set of units required by the program, by reading the
2091 corresponding ALI files. It generates error messages if the program is
2092 inconsistent or if no valid order of elaboration exists.
2093
2094 If no errors are detected, the binder produces a main program, in Ada by
2095 default, that contains calls to the elaboration procedures of those
2096 compilation unit that require them, followed by
2097 a call to the main program. This Ada program is compiled to generate the
2098 object file for the main program. The name of
2099 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2100 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2101 main program unit.
2102
2103 Finally, the linker is used to build the resulting executable program,
2104 using the object from the main program from the bind step as well as the
2105 object files for the Ada units of the program.
2106
2107 @node Mixed Language Programming
2108 @section Mixed Language Programming
2109 @cindex Mixed Language Programming
2110
2111 @noindent
2112 This section describes how to develop a mixed-language program,
2113 specifically one that comprises units in both Ada and C.
2114
2115 @menu
2116 * Interfacing to C::
2117 * Calling Conventions::
2118 @end menu
2119
2120 @node Interfacing to C
2121 @subsection Interfacing to C
2122 @noindent
2123 Interfacing Ada with a foreign language such as C involves using
2124 compiler directives to import and/or export entity definitions in each
2125 language---using @code{extern} statements in C, for instance, and the
2126 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2127 A full treatment of these topics is provided in Appendix B, section 1
2128 of the Ada Reference Manual.
2129
2130 There are two ways to build a program using GNAT that contains some Ada
2131 sources and some foreign language sources, depending on whether or not
2132 the main subprogram is written in Ada. Here is a source example with
2133 the main subprogram in Ada:
2134
2135 @smallexample
2136 /* file1.c */
2137 #include <stdio.h>
2138
2139 void print_num (int num)
2140 @{
2141 printf ("num is %d.\n", num);
2142 return;
2143 @}
2144
2145 /* file2.c */
2146
2147 /* num_from_Ada is declared in my_main.adb */
2148 extern int num_from_Ada;
2149
2150 int get_num (void)
2151 @{
2152 return num_from_Ada;
2153 @}
2154 @end smallexample
2155
2156 @smallexample @c ada
2157 -- my_main.adb
2158 procedure My_Main is
2159
2160 -- Declare then export an Integer entity called num_from_Ada
2161 My_Num : Integer := 10;
2162 pragma Export (C, My_Num, "num_from_Ada");
2163
2164 -- Declare an Ada function spec for Get_Num, then use
2165 -- C function get_num for the implementation.
2166 function Get_Num return Integer;
2167 pragma Import (C, Get_Num, "get_num");
2168
2169 -- Declare an Ada procedure spec for Print_Num, then use
2170 -- C function print_num for the implementation.
2171 procedure Print_Num (Num : Integer);
2172 pragma Import (C, Print_Num, "print_num");
2173
2174 begin
2175 Print_Num (Get_Num);
2176 end My_Main;
2177 @end smallexample
2178
2179 @enumerate
2180 @item
2181 To build this example, first compile the foreign language files to
2182 generate object files:
2183 @smallexample
2184 ^gcc -c file1.c^gcc -c FILE1.C^
2185 ^gcc -c file2.c^gcc -c FILE2.C^
2186 @end smallexample
2187
2188 @item
2189 Then, compile the Ada units to produce a set of object files and ALI
2190 files:
2191 @smallexample
2192 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2193 @end smallexample
2194
2195 @item
2196 Run the Ada binder on the Ada main program:
2197 @smallexample
2198 gnatbind my_main.ali
2199 @end smallexample
2200
2201 @item
2202 Link the Ada main program, the Ada objects and the other language
2203 objects:
2204 @smallexample
2205 gnatlink my_main.ali file1.o file2.o
2206 @end smallexample
2207 @end enumerate
2208
2209 The last three steps can be grouped in a single command:
2210 @smallexample
2211 gnatmake my_main.adb -largs file1.o file2.o
2212 @end smallexample
2213
2214 @cindex Binder output file
2215 @noindent
2216 If the main program is in a language other than Ada, then you may have
2217 more than one entry point into the Ada subsystem. You must use a special
2218 binder option to generate callable routines that initialize and
2219 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2220 Calls to the initialization and finalization routines must be inserted
2221 in the main program, or some other appropriate point in the code. The
2222 call to initialize the Ada units must occur before the first Ada
2223 subprogram is called, and the call to finalize the Ada units must occur
2224 after the last Ada subprogram returns. The binder will place the
2225 initialization and finalization subprograms into the
2226 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2227 sources. To illustrate, we have the following example:
2228
2229 @smallexample
2230 /* main.c */
2231 extern void adainit (void);
2232 extern void adafinal (void);
2233 extern int add (int, int);
2234 extern int sub (int, int);
2235
2236 int main (int argc, char *argv[])
2237 @{
2238 int a = 21, b = 7;
2239
2240 adainit();
2241
2242 /* Should print "21 + 7 = 28" */
2243 printf ("%d + %d = %d\n", a, b, add (a, b));
2244 /* Should print "21 - 7 = 14" */
2245 printf ("%d - %d = %d\n", a, b, sub (a, b));
2246
2247 adafinal();
2248 @}
2249 @end smallexample
2250
2251 @smallexample @c ada
2252 -- unit1.ads
2253 package Unit1 is
2254 function Add (A, B : Integer) return Integer;
2255 pragma Export (C, Add, "add");
2256 end Unit1;
2257
2258 -- unit1.adb
2259 package body Unit1 is
2260 function Add (A, B : Integer) return Integer is
2261 begin
2262 return A + B;
2263 end Add;
2264 end Unit1;
2265
2266 -- unit2.ads
2267 package Unit2 is
2268 function Sub (A, B : Integer) return Integer;
2269 pragma Export (C, Sub, "sub");
2270 end Unit2;
2271
2272 -- unit2.adb
2273 package body Unit2 is
2274 function Sub (A, B : Integer) return Integer is
2275 begin
2276 return A - B;
2277 end Sub;
2278 end Unit2;
2279 @end smallexample
2280
2281 @enumerate
2282 @item
2283 The build procedure for this application is similar to the last
2284 example's. First, compile the foreign language files to generate object
2285 files:
2286 @smallexample
2287 ^gcc -c main.c^gcc -c main.c^
2288 @end smallexample
2289
2290 @item
2291 Next, compile the Ada units to produce a set of object files and ALI
2292 files:
2293 @smallexample
2294 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2295 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2296 @end smallexample
2297
2298 @item
2299 Run the Ada binder on every generated ALI file. Make sure to use the
2300 @option{-n} option to specify a foreign main program:
2301 @smallexample
2302 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2303 @end smallexample
2304
2305 @item
2306 Link the Ada main program, the Ada objects and the foreign language
2307 objects. You need only list the last ALI file here:
2308 @smallexample
2309 gnatlink unit2.ali main.o -o exec_file
2310 @end smallexample
2311
2312 This procedure yields a binary executable called @file{exec_file}.
2313 @end enumerate
2314
2315 @noindent
2316 Depending on the circumstances (for example when your non-Ada main object
2317 does not provide symbol @code{main}), you may also need to instruct the
2318 GNAT linker not to include the standard startup objects by passing the
2319 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2320
2321 @node Calling Conventions
2322 @subsection Calling Conventions
2323 @cindex Foreign Languages
2324 @cindex Calling Conventions
2325 GNAT follows standard calling sequence conventions and will thus interface
2326 to any other language that also follows these conventions. The following
2327 Convention identifiers are recognized by GNAT:
2328
2329 @table @code
2330 @cindex Interfacing to Ada
2331 @cindex Other Ada compilers
2332 @cindex Convention Ada
2333 @item Ada
2334 This indicates that the standard Ada calling sequence will be
2335 used and all Ada data items may be passed without any limitations in the
2336 case where GNAT is used to generate both the caller and callee. It is also
2337 possible to mix GNAT generated code and code generated by another Ada
2338 compiler. In this case, the data types should be restricted to simple
2339 cases, including primitive types. Whether complex data types can be passed
2340 depends on the situation. Probably it is safe to pass simple arrays, such
2341 as arrays of integers or floats. Records may or may not work, depending
2342 on whether both compilers lay them out identically. Complex structures
2343 involving variant records, access parameters, tasks, or protected types,
2344 are unlikely to be able to be passed.
2345
2346 Note that in the case of GNAT running
2347 on a platform that supports HP Ada 83, a higher degree of compatibility
2348 can be guaranteed, and in particular records are laid out in an identical
2349 manner in the two compilers. Note also that if output from two different
2350 compilers is mixed, the program is responsible for dealing with elaboration
2351 issues. Probably the safest approach is to write the main program in the
2352 version of Ada other than GNAT, so that it takes care of its own elaboration
2353 requirements, and then call the GNAT-generated adainit procedure to ensure
2354 elaboration of the GNAT components. Consult the documentation of the other
2355 Ada compiler for further details on elaboration.
2356
2357 However, it is not possible to mix the tasking run time of GNAT and
2358 HP Ada 83, All the tasking operations must either be entirely within
2359 GNAT compiled sections of the program, or entirely within HP Ada 83
2360 compiled sections of the program.
2361
2362 @cindex Interfacing to Assembly
2363 @cindex Convention Assembler
2364 @item Assembler
2365 Specifies assembler as the convention. In practice this has the
2366 same effect as convention Ada (but is not equivalent in the sense of being
2367 considered the same convention).
2368
2369 @cindex Convention Asm
2370 @findex Asm
2371 @item Asm
2372 Equivalent to Assembler.
2373
2374 @cindex Interfacing to COBOL
2375 @cindex Convention COBOL
2376 @findex COBOL
2377 @item COBOL
2378 Data will be passed according to the conventions described
2379 in section B.4 of the Ada Reference Manual.
2380
2381 @findex C
2382 @cindex Interfacing to C
2383 @cindex Convention C
2384 @item C
2385 Data will be passed according to the conventions described
2386 in section B.3 of the Ada Reference Manual.
2387
2388 A note on interfacing to a C ``varargs'' function:
2389 @findex C varargs function
2390 @cindex Interfacing to C varargs function
2391 @cindex varargs function interfaces
2392
2393 @itemize @bullet
2394 @item
2395 In C, @code{varargs} allows a function to take a variable number of
2396 arguments. There is no direct equivalent in this to Ada. One
2397 approach that can be used is to create a C wrapper for each
2398 different profile and then interface to this C wrapper. For
2399 example, to print an @code{int} value using @code{printf},
2400 create a C function @code{printfi} that takes two arguments, a
2401 pointer to a string and an int, and calls @code{printf}.
2402 Then in the Ada program, use pragma @code{Import} to
2403 interface to @code{printfi}.
2404
2405 @item
2406 It may work on some platforms to directly interface to
2407 a @code{varargs} function by providing a specific Ada profile
2408 for a particular call. However, this does not work on
2409 all platforms, since there is no guarantee that the
2410 calling sequence for a two argument normal C function
2411 is the same as for calling a @code{varargs} C function with
2412 the same two arguments.
2413 @end itemize
2414
2415 @cindex Convention Default
2416 @findex Default
2417 @item Default
2418 Equivalent to C.
2419
2420 @cindex Convention External
2421 @findex External
2422 @item External
2423 Equivalent to C.
2424
2425 @ifclear vms
2426 @findex C++
2427 @cindex Interfacing to C++
2428 @cindex Convention C++
2429 @item C_Plus_Plus (or CPP)
2430 This stands for C++. For most purposes this is identical to C.
2431 See the separate description of the specialized GNAT pragmas relating to
2432 C++ interfacing for further details.
2433 @end ifclear
2434
2435 @findex Fortran
2436 @cindex Interfacing to Fortran
2437 @cindex Convention Fortran
2438 @item Fortran
2439 Data will be passed according to the conventions described
2440 in section B.5 of the Ada Reference Manual.
2441
2442 @item Intrinsic
2443 This applies to an intrinsic operation, as defined in the Ada
2444 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2445 this means that the body of the subprogram is provided by the compiler itself,
2446 usually by means of an efficient code sequence, and that the user does not
2447 supply an explicit body for it. In an application program, the pragma may
2448 be applied to the following sets of names:
2449
2450 @itemize @bullet
2451 @item
2452 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2453 Shift_Right_Arithmetic. The corresponding subprogram declaration must have
2454 two formal parameters. The
2455 first one must be a signed integer type or a modular type with a binary
2456 modulus, and the second parameter must be of type Natural.
2457 The return type must be the same as the type of the first argument. The size
2458 of this type can only be 8, 16, 32, or 64.
2459
2460 @item
2461 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2462 The corresponding operator declaration must have parameters and result type
2463 that have the same root numeric type (for example, all three are long_float
2464 types). This simplifies the definition of operations that use type checking
2465 to perform dimensional checks:
2466
2467 @smallexample @c ada
2468 type Distance is new Long_Float;
2469 type Time is new Long_Float;
2470 type Velocity is new Long_Float;
2471 function "/" (D : Distance; T : Time)
2472 return Velocity;
2473 pragma Import (Intrinsic, "/");
2474 @end smallexample
2475
2476 @noindent
2477 This common idiom is often programmed with a generic definition and an
2478 explicit body. The pragma makes it simpler to introduce such declarations.
2479 It incurs no overhead in compilation time or code size, because it is
2480 implemented as a single machine instruction.
2481
2482 @item
2483 General subprogram entities, to bind an Ada subprogram declaration to
2484 a compiler builtin by name with back-ends where such interfaces are
2485 available. A typical example is the set of ``__builtin'' functions
2486 exposed by the GCC back-end, as in the following example:
2487
2488 @smallexample @c ada
2489 function builtin_sqrt (F : Float) return Float;
2490 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2491 @end smallexample
2492
2493 Most of the GCC builtins are accessible this way, and as for other
2494 import conventions (e.g. C), it is the user's responsibility to ensure
2495 that the Ada subprogram profile matches the underlying builtin
2496 expectations.
2497 @end itemize
2498
2499 @noindent
2500
2501 @ifset unw
2502 @findex Stdcall
2503 @cindex Convention Stdcall
2504 @item Stdcall
2505 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2506 and specifies that the @code{Stdcall} calling sequence will be used,
2507 as defined by the NT API. Nevertheless, to ease building
2508 cross-platform bindings this convention will be handled as a @code{C} calling
2509 convention on non-Windows platforms.
2510
2511 @findex DLL
2512 @cindex Convention DLL
2513 @item DLL
2514 This is equivalent to @code{Stdcall}.
2515
2516 @findex Win32
2517 @cindex Convention Win32
2518 @item Win32
2519 This is equivalent to @code{Stdcall}.
2520 @end ifset
2521
2522 @findex Stubbed
2523 @cindex Convention Stubbed
2524 @item Stubbed
2525 This is a special convention that indicates that the compiler
2526 should provide a stub body that raises @code{Program_Error}.
2527 @end table
2528
2529 @noindent
2530 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2531 that can be used to parameterize conventions and allow additional synonyms
2532 to be specified. For example if you have legacy code in which the convention
2533 identifier Fortran77 was used for Fortran, you can use the configuration
2534 pragma:
2535
2536 @smallexample @c ada
2537 pragma Convention_Identifier (Fortran77, Fortran);
2538 @end smallexample
2539
2540 @noindent
2541 And from now on the identifier Fortran77 may be used as a convention
2542 identifier (for example in an @code{Import} pragma) with the same
2543 meaning as Fortran.
2544
2545 @ifclear vms
2546 @node Building Mixed Ada & C++ Programs
2547 @section Building Mixed Ada and C++ Programs
2548
2549 @noindent
2550 A programmer inexperienced with mixed-language development may find that
2551 building an application containing both Ada and C++ code can be a
2552 challenge. This section gives a few
2553 hints that should make this task easier. The first section addresses
2554 the differences between interfacing with C and interfacing with C++.
2555 The second section
2556 looks into the delicate problem of linking the complete application from
2557 its Ada and C++ parts. The last section gives some hints on how the GNAT
2558 run-time library can be adapted in order to allow inter-language dispatching
2559 with a new C++ compiler.
2560
2561 @menu
2562 * Interfacing to C++::
2563 * Linking a Mixed C++ & Ada Program::
2564 * A Simple Example::
2565 * Interfacing with C++ constructors::
2566 * Interfacing with C++ at the Class Level::
2567 @end menu
2568
2569 @node Interfacing to C++
2570 @subsection Interfacing to C++
2571
2572 @noindent
2573 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2574 generating code that is compatible with the G++ Application Binary
2575 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2576
2577 @noindent
2578 Interfacing can be done at 3 levels: simple data, subprograms, and
2579 classes. In the first two cases, GNAT offers a specific @code{Convention
2580 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2581 Usually, C++ mangles the names of subprograms. To generate proper mangled
2582 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2583 This problem can also be addressed manually in two ways:
2584
2585 @itemize @bullet
2586 @item
2587 by modifying the C++ code in order to force a C convention using
2588 the @code{extern "C"} syntax.
2589
2590 @item
2591 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2592 Link_Name argument of the pragma import.
2593 @end itemize
2594
2595 @noindent
2596 Interfacing at the class level can be achieved by using the GNAT specific
2597 pragmas such as @code{CPP_Constructor}. @xref{Interfacing to C++,,,
2598 gnat_rm, GNAT Reference Manual}, for additional information.
2599
2600 @node Linking a Mixed C++ & Ada Program
2601 @subsection Linking a Mixed C++ & Ada Program
2602
2603 @noindent
2604 Usually the linker of the C++ development system must be used to link
2605 mixed applications because most C++ systems will resolve elaboration
2606 issues (such as calling constructors on global class instances)
2607 transparently during the link phase. GNAT has been adapted to ease the
2608 use of a foreign linker for the last phase. Three cases can be
2609 considered:
2610 @enumerate
2611
2612 @item
2613 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
2614 The C++ linker can simply be called by using the C++ specific driver
2615 called @code{g++}.
2616
2617 Note that if the C++ code uses inline functions, you will need to
2618 compile your C++ code with the @code{-fkeep-inline-functions} switch in
2619 order to provide an existing function implementation that the Ada code can
2620 link with.
2621
2622 @smallexample
2623 $ g++ -c -fkeep-inline-functions file1.C
2624 $ g++ -c -fkeep-inline-functions file2.C
2625 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
2626 @end smallexample
2627
2628 @item
2629 Using GNAT and G++ from two different GCC installations: If both
2630 compilers are on the @env{PATH}, the previous method may be used. It is
2631 important to note that environment variables such as
2632 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
2633 @env{GCC_ROOT} will affect both compilers
2634 at the same time and may make one of the two compilers operate
2635 improperly if set during invocation of the wrong compiler. It is also
2636 very important that the linker uses the proper @file{libgcc.a} GCC
2637 library -- that is, the one from the C++ compiler installation. The
2638 implicit link command as suggested in the @command{gnatmake} command
2639 from the former example can be replaced by an explicit link command with
2640 the full-verbosity option in order to verify which library is used:
2641 @smallexample
2642 $ gnatbind ada_unit
2643 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2644 @end smallexample
2645 If there is a problem due to interfering environment variables, it can
2646 be worked around by using an intermediate script. The following example
2647 shows the proper script to use when GNAT has not been installed at its
2648 default location and g++ has been installed at its default location:
2649
2650 @smallexample
2651 $ cat ./my_script
2652 #!/bin/sh
2653 unset BINUTILS_ROOT
2654 unset GCC_ROOT
2655 c++ $*
2656 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2657 @end smallexample
2658
2659 @item
2660 Using a non-GNU C++ compiler: The commands previously described can be
2661 used to insure that the C++ linker is used. Nonetheless, you need to add
2662 a few more parameters to the link command line, depending on the exception
2663 mechanism used.
2664
2665 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
2666 to the libgcc libraries are required:
2667
2668 @smallexample
2669 $ cat ./my_script
2670 #!/bin/sh
2671 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
2672 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2673 @end smallexample
2674
2675 Where CC is the name of the non-GNU C++ compiler.
2676
2677 If the @code{zero cost} exception mechanism is used, and the platform
2678 supports automatic registration of exception tables (e.g.@: Solaris),
2679 paths to more objects are required:
2680
2681 @smallexample
2682 $ cat ./my_script
2683 #!/bin/sh
2684 CC `gcc -print-file-name=crtbegin.o` $* \
2685 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
2686 `gcc -print-file-name=crtend.o`
2687 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2688 @end smallexample
2689
2690 If the @code{zero cost} exception mechanism is used, and the platform
2691 doesn't support automatic registration of exception tables (e.g.@: HP-UX
2692 or AIX), the simple approach described above will not work and
2693 a pre-linking phase using GNAT will be necessary.
2694
2695 @end enumerate
2696
2697 Another alternative is to use the @command{gprbuild} multi-language builder
2698 which has a large knowledge base and knows how to link Ada and C++ code
2699 together automatically in most cases.
2700
2701 @node A Simple Example
2702 @subsection A Simple Example
2703 @noindent
2704 The following example, provided as part of the GNAT examples, shows how
2705 to achieve procedural interfacing between Ada and C++ in both
2706 directions. The C++ class A has two methods. The first method is exported
2707 to Ada by the means of an extern C wrapper function. The second method
2708 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
2709 a limited record with a layout comparable to the C++ class. The Ada
2710 subprogram, in turn, calls the C++ method. So, starting from the C++
2711 main program, the process passes back and forth between the two
2712 languages.
2713
2714 @noindent
2715 Here are the compilation commands:
2716 @smallexample
2717 $ gnatmake -c simple_cpp_interface
2718 $ g++ -c cpp_main.C
2719 $ g++ -c ex7.C
2720 $ gnatbind -n simple_cpp_interface
2721 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
2722 -lstdc++ ex7.o cpp_main.o
2723 @end smallexample
2724
2725 @noindent
2726 Here are the corresponding sources:
2727 @smallexample
2728
2729 //cpp_main.C
2730
2731 #include "ex7.h"
2732
2733 extern "C" @{
2734 void adainit (void);
2735 void adafinal (void);
2736 void method1 (A *t);
2737 @}
2738
2739 void method1 (A *t)
2740 @{
2741 t->method1 ();
2742 @}
2743
2744 int main ()
2745 @{
2746 A obj;
2747 adainit ();
2748 obj.method2 (3030);
2749 adafinal ();
2750 @}
2751
2752 //ex7.h
2753
2754 class Origin @{
2755 public:
2756 int o_value;
2757 @};
2758 class A : public Origin @{
2759 public:
2760 void method1 (void);
2761 void method2 (int v);
2762 A();
2763 int a_value;
2764 @};
2765
2766 //ex7.C
2767
2768 #include "ex7.h"
2769 #include <stdio.h>
2770
2771 extern "C" @{ void ada_method2 (A *t, int v);@}
2772
2773 void A::method1 (void)
2774 @{
2775 a_value = 2020;
2776 printf ("in A::method1, a_value = %d \n",a_value);
2777
2778 @}
2779
2780 void A::method2 (int v)
2781 @{
2782 ada_method2 (this, v);
2783 printf ("in A::method2, a_value = %d \n",a_value);
2784
2785 @}
2786
2787 A::A(void)
2788 @{
2789 a_value = 1010;
2790 printf ("in A::A, a_value = %d \n",a_value);
2791 @}
2792 @end smallexample
2793
2794 @smallexample @c ada
2795 -- Ada sources
2796 package body Simple_Cpp_Interface is
2797
2798 procedure Ada_Method2 (This : in out A; V : Integer) is
2799 begin
2800 Method1 (This);
2801 This.A_Value := V;
2802 end Ada_Method2;
2803
2804 end Simple_Cpp_Interface;
2805
2806 with System;
2807 package Simple_Cpp_Interface is
2808 type A is limited
2809 record
2810 Vptr : System.Address;
2811 O_Value : Integer;
2812 A_Value : Integer;
2813 end record;
2814 pragma Convention (C, A);
2815
2816 procedure Method1 (This : in out A);
2817 pragma Import (C, Method1);
2818
2819 procedure Ada_Method2 (This : in out A; V : Integer);
2820 pragma Export (C, Ada_Method2);
2821
2822 end Simple_Cpp_Interface;
2823 @end smallexample
2824
2825 @node Interfacing with C++ constructors
2826 @subsection Interfacing with C++ constructors
2827 @noindent
2828
2829 In order to interface with C++ constructors GNAT provides the
2830 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
2831 gnat_rm, GNAT Reference Manual}, for additional information).
2832 In this section we present some common uses of C++ constructors
2833 in mixed-languages programs in GNAT.
2834
2835 Let us assume that we need to interface with the following
2836 C++ class:
2837
2838 @smallexample
2839 @b{class} Root @{
2840 @b{public}:
2841 int a_value;
2842 int b_value;
2843 @b{virtual} int Get_Value ();
2844 Root(); // Default constructor
2845 Root(int v); // 1st non-default constructor
2846 Root(int v, int w); // 2nd non-default constructor
2847 @};
2848 @end smallexample
2849
2850 For this purpose we can write the following package spec (further
2851 information on how to build this spec is available in
2852 @ref{Interfacing with C++ at the Class Level} and
2853 @ref{Generating Ada Bindings for C and C++ headers}).
2854
2855 @smallexample @c ada
2856 with Interfaces.C; use Interfaces.C;
2857 package Pkg_Root is
2858 type Root is tagged limited record
2859 A_Value : int;
2860 B_Value : int;
2861 end record;
2862 pragma Import (CPP, Root);
2863
2864 function Get_Value (Obj : Root) return int;
2865 pragma Import (CPP, Get_Value);
2866
2867 function Constructor return Root;
2868 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
2869
2870 function Constructor (v : Integer) return Root;
2871 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
2872
2873 function Constructor (v, w : Integer) return Root;
2874 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
2875 end Pkg_Root;
2876 @end smallexample
2877
2878 On the Ada side the constructor is represented by a function (whose
2879 name is arbitrary) that returns the classwide type corresponding to
2880 the imported C++ class. Although the constructor is described as a
2881 function, it is typically a procedure with an extra implicit argument
2882 (the object being initialized) at the implementation level. GNAT
2883 issues the appropriate call, whatever it is, to get the object
2884 properly initialized.
2885
2886 Constructors can only appear in the following contexts:
2887
2888 @itemize @bullet
2889 @item
2890 On the right side of an initialization of an object of type @var{T}.
2891 @item
2892 On the right side of an initialization of a record component of type @var{T}.
2893 @item
2894 In an Ada 2005 limited aggregate.
2895 @item
2896 In an Ada 2005 nested limited aggregate.
2897 @item
2898 In an Ada 2005 limited aggregate that initializes an object built in
2899 place by an extended return statement.
2900 @end itemize
2901
2902 @noindent
2903 In a declaration of an object whose type is a class imported from C++,
2904 either the default C++ constructor is implicitly called by GNAT, or
2905 else the required C++ constructor must be explicitly called in the
2906 expression that initializes the object. For example:
2907
2908 @smallexample @c ada
2909 Obj1 : Root;
2910 Obj2 : Root := Constructor;
2911 Obj3 : Root := Constructor (v => 10);
2912 Obj4 : Root := Constructor (30, 40);
2913 @end smallexample
2914
2915 The first two declarations are equivalent: in both cases the default C++
2916 constructor is invoked (in the former case the call to the constructor is
2917 implicit, and in the latter case the call is explicit in the object
2918 declaration). @code{Obj3} is initialized by the C++ non-default constructor
2919 that takes an integer argument, and @code{Obj4} is initialized by the
2920 non-default C++ constructor that takes two integers.
2921
2922 Let us derive the imported C++ class in the Ada side. For example:
2923
2924 @smallexample @c ada
2925 type DT is new Root with record
2926 C_Value : Natural := 2009;
2927 end record;
2928 @end smallexample
2929
2930 In this case the components DT inherited from the C++ side must be
2931 initialized by a C++ constructor, and the additional Ada components
2932 of type DT are initialized by GNAT. The initialization of such an
2933 object is done either by default, or by means of a function returning
2934 an aggregate of type DT, or by means of an extension aggregate.
2935
2936 @smallexample @c ada
2937 Obj5 : DT;
2938 Obj6 : DT := Function_Returning_DT (50);
2939 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
2940 @end smallexample
2941
2942 The declaration of @code{Obj5} invokes the default constructors: the
2943 C++ default constructor of the parent type takes care of the initialization
2944 of the components inherited from Root, and GNAT takes care of the default
2945 initialization of the additional Ada components of type DT (that is,
2946 @code{C_Value} is initialized to value 2009). The order of invocation of
2947 the constructors is consistent with the order of elaboration required by
2948 Ada and C++. That is, the constructor of the parent type is always called
2949 before the constructor of the derived type.
2950
2951 Let us now consider a record that has components whose type is imported
2952 from C++. For example:
2953
2954 @smallexample @c ada
2955 type Rec1 is limited record
2956 Data1 : Root := Constructor (10);
2957 Value : Natural := 1000;
2958 end record;
2959
2960 type Rec2 (D : Integer := 20) is limited record
2961 Rec : Rec1;
2962 Data2 : Root := Constructor (D, 30);
2963 end record;
2964 @end smallexample
2965
2966 The initialization of an object of type @code{Rec2} will call the
2967 non-default C++ constructors specified for the imported components.
2968 For example:
2969
2970 @smallexample @c ada
2971 Obj8 : Rec2 (40);
2972 @end smallexample
2973
2974 Using Ada 2005 we can use limited aggregates to initialize an object
2975 invoking C++ constructors that differ from those specified in the type
2976 declarations. For example:
2977
2978 @smallexample @c ada
2979 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
2980 others => <>),
2981 others => <>);
2982 @end smallexample
2983
2984 The above declaration uses an Ada 2005 limited aggregate to
2985 initialize @code{Obj9}, and the C++ constructor that has two integer
2986 arguments is invoked to initialize the @code{Data1} component instead
2987 of the constructor specified in the declaration of type @code{Rec1}. In
2988 Ada 2005 the box in the aggregate indicates that unspecified components
2989 are initialized using the expression (if any) available in the component
2990 declaration. That is, in this case discriminant @code{D} is initialized
2991 to value @code{20}, @code{Value} is initialized to value 1000, and the
2992 non-default C++ constructor that handles two integers takes care of
2993 initializing component @code{Data2} with values @code{20,30}.
2994
2995 In Ada 2005 we can use the extended return statement to build the Ada
2996 equivalent to C++ non-default constructors. For example:
2997
2998 @smallexample @c ada
2999 function Constructor (V : Integer) return Rec2 is
3000 begin
3001 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20),
3002 others => <>),
3003 others => <>) do
3004 -- Further actions required for construction of
3005 -- objects of type Rec2
3006 ...
3007 end record;
3008 end Constructor;
3009 @end smallexample
3010
3011 In this example the extended return statement construct is used to
3012 build in place the returned object whose components are initialized
3013 by means of a limited aggregate. Any further action associated with
3014 the constructor can be placed inside the construct.
3015
3016 @node Interfacing with C++ at the Class Level
3017 @subsection Interfacing with C++ at the Class Level
3018 @noindent
3019 In this section we demonstrate the GNAT features for interfacing with
3020 C++ by means of an example making use of Ada 2005 abstract interface
3021 types. This example consists of a classification of animals; classes
3022 have been used to model our main classification of animals, and
3023 interfaces provide support for the management of secondary
3024 classifications. We first demonstrate a case in which the types and
3025 constructors are defined on the C++ side and imported from the Ada
3026 side, and latter the reverse case.
3027
3028 The root of our derivation will be the @code{Animal} class, with a
3029 single private attribute (the @code{Age} of the animal) and two public
3030 primitives to set and get the value of this attribute.
3031
3032 @smallexample
3033 @b{class} Animal @{
3034 @b{public}:
3035 @b{virtual} void Set_Age (int New_Age);
3036 @b{virtual} int Age ();
3037 @b{private}:
3038 int Age_Count;
3039 @};
3040 @end smallexample
3041
3042 Abstract interface types are defined in C++ by means of classes with pure
3043 virtual functions and no data members. In our example we will use two
3044 interfaces that provide support for the common management of @code{Carnivore}
3045 and @code{Domestic} animals:
3046
3047 @smallexample
3048 @b{class} Carnivore @{
3049 @b{public}:
3050 @b{virtual} int Number_Of_Teeth () = 0;
3051 @};
3052
3053 @b{class} Domestic @{
3054 @b{public}:
3055 @b{virtual void} Set_Owner (char* Name) = 0;
3056 @};
3057 @end smallexample
3058
3059 Using these declarations, we can now say that a @code{Dog} is an animal that is
3060 both Carnivore and Domestic, that is:
3061
3062 @smallexample
3063 @b{class} Dog : Animal, Carnivore, Domestic @{
3064 @b{public}:
3065 @b{virtual} int Number_Of_Teeth ();
3066 @b{virtual} void Set_Owner (char* Name);
3067
3068 Dog(); // Constructor
3069 @b{private}:
3070 int Tooth_Count;
3071 char *Owner;
3072 @};
3073 @end smallexample
3074
3075 In the following examples we will assume that the previous declarations are
3076 located in a file named @code{animals.h}. The following package demonstrates
3077 how to import these C++ declarations from the Ada side:
3078
3079 @smallexample @c ada
3080 with Interfaces.C.Strings; use Interfaces.C.Strings;
3081 package Animals is
3082 type Carnivore is interface;
3083 pragma Convention (C_Plus_Plus, Carnivore);
3084 function Number_Of_Teeth (X : Carnivore)
3085 return Natural is abstract;
3086
3087 type Domestic is interface;
3088 pragma Convention (C_Plus_Plus, Set_Owner);
3089 procedure Set_Owner
3090 (X : in out Domestic;
3091 Name : Chars_Ptr) is abstract;
3092
3093 type Animal is tagged record
3094 Age : Natural := 0;
3095 end record;
3096 pragma Import (C_Plus_Plus, Animal);
3097
3098 procedure Set_Age (X : in out Animal; Age : Integer);
3099 pragma Import (C_Plus_Plus, Set_Age);
3100
3101 function Age (X : Animal) return Integer;
3102 pragma Import (C_Plus_Plus, Age);
3103
3104 type Dog is new Animal and Carnivore and Domestic with record
3105 Tooth_Count : Natural;
3106 Owner : String (1 .. 30);
3107 end record;
3108 pragma Import (C_Plus_Plus, Dog);
3109
3110 function Number_Of_Teeth (A : Dog) return Integer;
3111 pragma Import (C_Plus_Plus, Number_Of_Teeth);
3112
3113 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3114 pragma Import (C_Plus_Plus, Set_Owner);
3115
3116 function New_Dog return Dog;
3117 pragma CPP_Constructor (New_Dog);
3118 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3119 end Animals;
3120 @end smallexample
3121
3122 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3123 interfacing with these C++ classes is easy. The only requirement is that all
3124 the primitives and components must be declared exactly in the same order in
3125 the two languages.
3126
3127 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3128 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3129 the arguments to the called primitives will be the same as for C++. For the
3130 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3131 to indicate that they have been defined on the C++ side; this is required
3132 because the dispatch table associated with these tagged types will be built
3133 in the C++ side and therefore will not contain the predefined Ada primitives
3134 which Ada would otherwise expect.
3135
3136 As the reader can see there is no need to indicate the C++ mangled names
3137 associated with each subprogram because it is assumed that all the calls to
3138 these primitives will be dispatching calls. The only exception is the
3139 constructor, which must be registered with the compiler by means of
3140 @code{pragma CPP_Constructor} and needs to provide its associated C++
3141 mangled name because the Ada compiler generates direct calls to it.
3142
3143 With the above packages we can now declare objects of type Dog on the Ada side
3144 and dispatch calls to the corresponding subprograms on the C++ side. We can
3145 also extend the tagged type Dog with further fields and primitives, and
3146 override some of its C++ primitives on the Ada side. For example, here we have
3147 a type derivation defined on the Ada side that inherits all the dispatching
3148 primitives of the ancestor from the C++ side.
3149
3150 @smallexample
3151 @b{with} Animals; @b{use} Animals;
3152 @b{package} Vaccinated_Animals @b{is}
3153 @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3154 @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3155 @b{end} Vaccinated_Animals;
3156 @end smallexample
3157
3158 It is important to note that, because of the ABI compatibility, the programmer
3159 does not need to add any further information to indicate either the object
3160 layout or the dispatch table entry associated with each dispatching operation.
3161
3162 Now let us define all the types and constructors on the Ada side and export
3163 them to C++, using the same hierarchy of our previous example:
3164
3165 @smallexample @c ada
3166 with Interfaces.C.Strings;
3167 use Interfaces.C.Strings;
3168 package Animals is
3169 type Carnivore is interface;
3170 pragma Convention (C_Plus_Plus, Carnivore);
3171 function Number_Of_Teeth (X : Carnivore)
3172 return Natural is abstract;
3173
3174 type Domestic is interface;
3175 pragma Convention (C_Plus_Plus, Set_Owner);
3176 procedure Set_Owner
3177 (X : in out Domestic;
3178 Name : Chars_Ptr) is abstract;
3179
3180 type Animal is tagged record
3181 Age : Natural := 0;
3182 end record;
3183 pragma Convention (C_Plus_Plus, Animal);
3184
3185 procedure Set_Age (X : in out Animal; Age : Integer);
3186 pragma Export (C_Plus_Plus, Set_Age);
3187
3188 function Age (X : Animal) return Integer;
3189 pragma Export (C_Plus_Plus, Age);
3190
3191 type Dog is new Animal and Carnivore and Domestic with record
3192 Tooth_Count : Natural;
3193 Owner : String (1 .. 30);
3194 end record;
3195 pragma Convention (C_Plus_Plus, Dog);
3196
3197 function Number_Of_Teeth (A : Dog) return Integer;
3198 pragma Export (C_Plus_Plus, Number_Of_Teeth);
3199
3200 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3201 pragma Export (C_Plus_Plus, Set_Owner);
3202
3203 function New_Dog return Dog'Class;
3204 pragma Export (C_Plus_Plus, New_Dog);
3205 end Animals;
3206 @end smallexample
3207
3208 Compared with our previous example the only difference is the use of
3209 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3210 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3211 nothing else to be done; as explained above, the only requirement is that all
3212 the primitives and components are declared in exactly the same order.
3213
3214 For completeness, let us see a brief C++ main program that uses the
3215 declarations available in @code{animals.h} (presented in our first example) to
3216 import and use the declarations from the Ada side, properly initializing and
3217 finalizing the Ada run-time system along the way:
3218
3219 @smallexample
3220 @b{#include} "animals.h"
3221 @b{#include} <iostream>
3222 @b{using namespace} std;
3223
3224 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3225 void Check_Domestic (Domestic *obj) @{@dots{}@}
3226 void Check_Animal (Animal *obj) @{@dots{}@}
3227 void Check_Dog (Dog *obj) @{@dots{}@}
3228
3229 @b{extern} "C" @{
3230 void adainit (void);
3231 void adafinal (void);
3232 Dog* new_dog ();
3233 @}
3234
3235 void test ()
3236 @{
3237 Dog *obj = new_dog(); // Ada constructor
3238 Check_Carnivore (obj); // Check secondary DT
3239 Check_Domestic (obj); // Check secondary DT
3240 Check_Animal (obj); // Check primary DT
3241 Check_Dog (obj); // Check primary DT
3242 @}
3243
3244 int main ()
3245 @{
3246 adainit (); test(); adafinal ();
3247 return 0;
3248 @}
3249 @end smallexample
3250
3251 @node Comparison between GNAT and C/C++ Compilation Models
3252 @section Comparison between GNAT and C/C++ Compilation Models
3253
3254 @noindent
3255 The GNAT model of compilation is close to the C and C++ models. You can
3256 think of Ada specs as corresponding to header files in C. As in C, you
3257 don't need to compile specs; they are compiled when they are used. The
3258 Ada @code{with} is similar in effect to the @code{#include} of a C
3259 header.
3260
3261 One notable difference is that, in Ada, you may compile specs separately
3262 to check them for semantic and syntactic accuracy. This is not always
3263 possible with C headers because they are fragments of programs that have
3264 less specific syntactic or semantic rules.
3265
3266 The other major difference is the requirement for running the binder,
3267 which performs two important functions. First, it checks for
3268 consistency. In C or C++, the only defense against assembling
3269 inconsistent programs lies outside the compiler, in a makefile, for
3270 example. The binder satisfies the Ada requirement that it be impossible
3271 to construct an inconsistent program when the compiler is used in normal
3272 mode.
3273
3274 @cindex Elaboration order control
3275 The other important function of the binder is to deal with elaboration
3276 issues. There are also elaboration issues in C++ that are handled
3277 automatically. This automatic handling has the advantage of being
3278 simpler to use, but the C++ programmer has no control over elaboration.
3279 Where @code{gnatbind} might complain there was no valid order of
3280 elaboration, a C++ compiler would simply construct a program that
3281 malfunctioned at run time.
3282 @end ifclear
3283
3284 @node Comparison between GNAT and Conventional Ada Library Models
3285 @section Comparison between GNAT and Conventional Ada Library Models
3286
3287 @noindent
3288 This section is intended for Ada programmers who have
3289 used an Ada compiler implementing the traditional Ada library
3290 model, as described in the Ada Reference Manual.
3291
3292 @cindex GNAT library
3293 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3294 source files themselves acts as the library. Compiling Ada programs does
3295 not generate any centralized information, but rather an object file and
3296 a ALI file, which are of interest only to the binder and linker.
3297 In a traditional system, the compiler reads information not only from
3298 the source file being compiled, but also from the centralized library.
3299 This means that the effect of a compilation depends on what has been
3300 previously compiled. In particular:
3301
3302 @itemize @bullet
3303 @item
3304 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3305 to the version of the unit most recently compiled into the library.
3306
3307 @item
3308 Inlining is effective only if the necessary body has already been
3309 compiled into the library.
3310
3311 @item
3312 Compiling a unit may obsolete other units in the library.
3313 @end itemize
3314
3315 @noindent
3316 In GNAT, compiling one unit never affects the compilation of any other
3317 units because the compiler reads only source files. Only changes to source
3318 files can affect the results of a compilation. In particular:
3319
3320 @itemize @bullet
3321 @item
3322 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3323 to the source version of the unit that is currently accessible to the
3324 compiler.
3325
3326 @item
3327 @cindex Inlining
3328 Inlining requires the appropriate source files for the package or
3329 subprogram bodies to be available to the compiler. Inlining is always
3330 effective, independent of the order in which units are complied.
3331
3332 @item
3333 Compiling a unit never affects any other compilations. The editing of
3334 sources may cause previous compilations to be out of date if they
3335 depended on the source file being modified.
3336 @end itemize
3337
3338 @noindent
3339 The most important result of these differences is that order of compilation
3340 is never significant in GNAT. There is no situation in which one is
3341 required to do one compilation before another. What shows up as order of
3342 compilation requirements in the traditional Ada library becomes, in
3343 GNAT, simple source dependencies; in other words, there is only a set
3344 of rules saying what source files must be present when a file is
3345 compiled.
3346
3347 @ifset vms
3348 @node Placement of temporary files
3349 @section Placement of temporary files
3350 @cindex Temporary files (user control over placement)
3351
3352 @noindent
3353 GNAT creates temporary files in the directory designated by the environment
3354 variable @env{TMPDIR}.
3355 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3356 for detailed information on how environment variables are resolved.
3357 For most users the easiest way to make use of this feature is to simply
3358 define @env{TMPDIR} as a job level logical name).
3359 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3360 for compiler temporary files, then you can include something like the
3361 following command in your @file{LOGIN.COM} file:
3362
3363 @smallexample
3364 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3365 @end smallexample
3366
3367 @noindent
3368 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3369 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3370 designated by @env{TEMP}.
3371 If none of these environment variables are defined then GNAT uses the
3372 directory designated by the logical name @code{SYS$SCRATCH:}
3373 (by default the user's home directory). If all else fails
3374 GNAT uses the current directory for temporary files.
3375 @end ifset
3376
3377 @c *************************
3378 @node Compiling with gcc
3379 @chapter Compiling with @command{gcc}
3380
3381 @noindent
3382 This chapter discusses how to compile Ada programs using the @command{gcc}
3383 command. It also describes the set of switches
3384 that can be used to control the behavior of the compiler.
3385 @menu
3386 * Compiling Programs::
3387 * Switches for gcc::
3388 * Search Paths and the Run-Time Library (RTL)::
3389 * Order of Compilation Issues::
3390 * Examples::
3391 @end menu
3392
3393 @node Compiling Programs
3394 @section Compiling Programs
3395
3396 @noindent
3397 The first step in creating an executable program is to compile the units
3398 of the program using the @command{gcc} command. You must compile the
3399 following files:
3400
3401 @itemize @bullet
3402 @item
3403 the body file (@file{.adb}) for a library level subprogram or generic
3404 subprogram
3405
3406 @item
3407 the spec file (@file{.ads}) for a library level package or generic
3408 package that has no body
3409
3410 @item
3411 the body file (@file{.adb}) for a library level package
3412 or generic package that has a body
3413
3414 @end itemize
3415
3416 @noindent
3417 You need @emph{not} compile the following files
3418
3419 @itemize @bullet
3420
3421 @item
3422 the spec of a library unit which has a body
3423
3424 @item
3425 subunits
3426 @end itemize
3427
3428 @noindent
3429 because they are compiled as part of compiling related units. GNAT
3430 package specs
3431 when the corresponding body is compiled, and subunits when the parent is
3432 compiled.
3433
3434 @cindex cannot generate code
3435 If you attempt to compile any of these files, you will get one of the
3436 following error messages (where @var{fff} is the name of the file you
3437 compiled):
3438
3439 @smallexample
3440 cannot generate code for file @var{fff} (package spec)
3441 to check package spec, use -gnatc
3442
3443 cannot generate code for file @var{fff} (missing subunits)
3444 to check parent unit, use -gnatc
3445
3446 cannot generate code for file @var{fff} (subprogram spec)
3447 to check subprogram spec, use -gnatc
3448
3449 cannot generate code for file @var{fff} (subunit)
3450 to check subunit, use -gnatc
3451 @end smallexample
3452
3453 @noindent
3454 As indicated by the above error messages, if you want to submit
3455 one of these files to the compiler to check for correct semantics
3456 without generating code, then use the @option{-gnatc} switch.
3457
3458 The basic command for compiling a file containing an Ada unit is
3459
3460 @smallexample
3461 @c $ gcc -c @ovar{switches} @file{file name}
3462 @c Expanding @ovar macro inline (explanation in macro def comments)
3463 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3464 @end smallexample
3465
3466 @noindent
3467 where @var{file name} is the name of the Ada file (usually
3468 having an extension
3469 @file{.ads} for a spec or @file{.adb} for a body).
3470 @ifclear vms
3471 You specify the
3472 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3473 @end ifclear
3474 The result of a successful compilation is an object file, which has the
3475 same name as the source file but an extension of @file{.o} and an Ada
3476 Library Information (ALI) file, which also has the same name as the
3477 source file, but with @file{.ali} as the extension. GNAT creates these
3478 two output files in the current directory, but you may specify a source
3479 file in any directory using an absolute or relative path specification
3480 containing the directory information.
3481
3482 @findex gnat1
3483 @command{gcc} is actually a driver program that looks at the extensions of
3484 the file arguments and loads the appropriate compiler. For example, the
3485 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3486 These programs are in directories known to the driver program (in some
3487 configurations via environment variables you set), but need not be in
3488 your path. The @command{gcc} driver also calls the assembler and any other
3489 utilities needed to complete the generation of the required object
3490 files.
3491
3492 It is possible to supply several file names on the same @command{gcc}
3493 command. This causes @command{gcc} to call the appropriate compiler for
3494 each file. For example, the following command lists two separate
3495 files to be compiled:
3496
3497 @smallexample
3498 $ gcc -c x.adb y.adb
3499 @end smallexample
3500
3501 @noindent
3502 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3503 @file{y.adb}.
3504 The compiler generates two object files @file{x.o} and @file{y.o}
3505 and the two ALI files @file{x.ali} and @file{y.ali}.
3506 Any switches apply to all the files ^listed,^listed.^
3507
3508 @node Switches for gcc
3509 @section Switches for @command{gcc}
3510
3511 @noindent
3512 The @command{gcc} command accepts switches that control the
3513 compilation process. These switches are fully described in this section.
3514 First we briefly list all the switches, in alphabetical order, then we
3515 describe the switches in more detail in functionally grouped sections.
3516
3517 More switches exist for GCC than those documented here, especially
3518 for specific targets. However, their use is not recommended as
3519 they may change code generation in ways that are incompatible with
3520 the Ada run-time library, or can cause inconsistencies between
3521 compilation units.
3522
3523 @menu
3524 * Output and Error Message Control::
3525 * Warning Message Control::
3526 * Debugging and Assertion Control::
3527 * Validity Checking::
3528 * Style Checking::
3529 * Run-Time Checks::
3530 * Using gcc for Syntax Checking::
3531 * Using gcc for Semantic Checking::
3532 * Compiling Different Versions of Ada::
3533 * Character Set Control::
3534 * File Naming Control::
3535 * Subprogram Inlining Control::
3536 * Auxiliary Output Control::
3537 * Debugging Control::
3538 * Exception Handling Control::
3539 * Units to Sources Mapping Files::
3540 * Integrated Preprocessing::
3541 * Code Generation Control::
3542 @ifset vms
3543 * Return Codes::
3544 @end ifset
3545 @end menu
3546
3547 @table @option
3548 @c !sort!
3549 @ifclear vms
3550 @cindex @option{-b} (@command{gcc})
3551 @item -b @var{target}
3552 Compile your program to run on @var{target}, which is the name of a
3553 system configuration. You must have a GNAT cross-compiler built if
3554 @var{target} is not the same as your host system.
3555
3556 @item -B@var{dir}
3557 @cindex @option{-B} (@command{gcc})
3558 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3559 from @var{dir} instead of the default location. Only use this switch
3560 when multiple versions of the GNAT compiler are available.
3561 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3562 GNU Compiler Collection (GCC)}, for further details. You would normally
3563 use the @option{-b} or @option{-V} switch instead.
3564
3565 @item -c
3566 @cindex @option{-c} (@command{gcc})
3567 Compile. Always use this switch when compiling Ada programs.
3568
3569 Note: for some other languages when using @command{gcc}, notably in
3570 the case of C and C++, it is possible to use
3571 use @command{gcc} without a @option{-c} switch to
3572 compile and link in one step. In the case of GNAT, you
3573 cannot use this approach, because the binder must be run
3574 and @command{gcc} cannot be used to run the GNAT binder.
3575 @end ifclear
3576
3577 @item -fcallgraph-info@r{[}=su,da@r{]}
3578 @cindex @option{-fcallgraph-info} (@command{gcc})
3579 Makes the compiler output callgraph information for the program, on a
3580 per-file basis. The information is generated in the VCG format. It can
3581 be decorated with additional, per-node and/or per-edge information, if a
3582 list of comma-separated markers is additionally specified. When the
3583 @var{su} marker is specified, the callgraph is decorated with stack usage information; it is equivalent to @option{-fstack-usage}. When the @var{da}
3584 marker is specified, the callgraph is decorated with information about
3585 dynamically allocated objects.
3586
3587 @item -fdump-scos
3588 @cindex @option{-fdump-scos} (@command{gcc})
3589 Generates SCO (Source Coverage Obligation) information in the ALI file.
3590 This information is used by advanced coverage tools. See unit @file{SCOs}
3591 in the compiler sources for details in files @file{scos.ads} and
3592 @file{scos.adb}.
3593
3594 @item -fdump-xref
3595 @cindex @option{-fdump-xref} (@command{gcc})
3596 Generates cross reference information in GLI files for C and C++ sources.
3597 The GLI files have the same syntax as the ALI files for Ada, and can be used
3598 for source navigation in IDEs and on the command line using e.g. gnatxref
3599 and the @option{--ext=gli} switch.
3600
3601 @item -flto@r{[}=n@r{]}
3602 @cindex @option{-flto} (@command{gcc})
3603 Enables Link Time Optimization. This switch must be used in conjunction
3604 with the traditional @option{-Ox} switches and instructs the compiler to
3605 defer most optimizations until the link stage. The advantage of this
3606 approach is that the compiler can do a whole-program analysis and choose
3607 the best interprocedural optimization strategy based on a complete view
3608 of the program, instead of a fragmentary view with the usual approach.
3609 This can also speed up the compilation of huge programs and reduce the
3610 size of the final executable, compared with a per-unit compilation with
3611 full inlining across modules enabled with the @option{-gnatn2} switch.
3612 The drawback of this approach is that it may require much more memory.
3613 The switch, as well as the accompanying @option{-Ox} switches, must be
3614 specified both for the compilation and the link phases.
3615 If the @var{n} parameter is specified, the optimization and final code
3616 generation at link time are executed using @var{n} parallel jobs by
3617 means of an installed @command{make} program.
3618
3619 @item -fno-inline
3620 @cindex @option{-fno-inline} (@command{gcc})
3621 Suppresses all inlining, even if other optimization or inlining
3622 switches are set. This includes suppression of inlining that
3623 results from the use of the pragma @code{Inline_Always}.
3624 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3625 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3626 effects if this switch is present. Note that inlining can also
3627 be suppressed on a finer-grained basis with pragma @code{No_Inline}.
3628
3629 @item -fno-inline-functions
3630 @cindex @option{-fno-inline-functions} (@command{gcc})
3631 Suppresses automatic inlining of subprograms, which is enabled
3632 if @option{-O3} is used.
3633
3634 @item -fno-inline-small-functions
3635 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3636 Suppresses automatic inlining of small subprograms, which is enabled
3637 if @option{-O2} is used.
3638
3639 @item -fno-inline-functions-called-once
3640 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3641 Suppresses inlining of subprograms local to the unit and called once
3642 from within it, which is enabled if @option{-O1} is used.
3643
3644 @item -fno-ivopts
3645 @cindex @option{-fno-ivopts} (@command{gcc})
3646 Suppresses high-level loop induction variable optimizations, which are
3647 enabled if @option{-O1} is used. These optimizations are generally
3648 profitable but, for some specific cases of loops with numerous uses
3649 of the iteration variable that follow a common pattern, they may end
3650 up destroying the regularity that could be exploited at a lower level
3651 and thus producing inferior code.
3652
3653 @item -fno-strict-aliasing
3654 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3655 Causes the compiler to avoid assumptions regarding non-aliasing
3656 of objects of different types. See
3657 @ref{Optimization and Strict Aliasing} for details.
3658
3659 @item -fstack-check
3660 @cindex @option{-fstack-check} (@command{gcc})
3661 Activates stack checking.
3662 See @ref{Stack Overflow Checking} for details.
3663
3664 @item -fstack-usage
3665 @cindex @option{-fstack-usage} (@command{gcc})
3666 Makes the compiler output stack usage information for the program, on a
3667 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
3668
3669 @item ^-g^/DEBUG^
3670 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3671 Generate debugging information. This information is stored in the object
3672 file and copied from there to the final executable file by the linker,
3673 where it can be read by the debugger. You must use the
3674 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3675
3676 @item -gnat83
3677 @cindex @option{-gnat83} (@command{gcc})
3678 Enforce Ada 83 restrictions.
3679
3680 @item -gnat95
3681 @cindex @option{-gnat95} (@command{gcc})
3682 Enforce Ada 95 restrictions.
3683
3684 @item -gnat05
3685 @cindex @option{-gnat05} (@command{gcc})
3686 Allow full Ada 2005 features.
3687
3688 @item -gnat2005
3689 @cindex @option{-gnat2005} (@command{gcc})
3690 Allow full Ada 2005 features (same as @option{-gnat05})
3691
3692 @item -gnat12
3693 @cindex @option{-gnat12} (@command{gcc})
3694
3695 @item -gnat2012
3696 @cindex @option{-gnat2012} (@command{gcc})
3697 Allow full Ada 2012 features (same as @option{-gnat12})
3698
3699 @item -gnata
3700 @cindex @option{-gnata} (@command{gcc})
3701 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3702 activated. Note that these pragmas can also be controlled using the
3703 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3704 It also activates pragmas @code{Check}, @code{Precondition}, and
3705 @code{Postcondition}. Note that these pragmas can also be controlled
3706 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
3707 also activates all assertions defined in the RM as aspects: preconditions,
3708 postconditions, type invariants and (sub)type predicates. In all Ada modes,
3709 corresponding pragmas for type invariants and (sub)type predicates are
3710 also activated.
3711
3712 @item -gnatA
3713 @cindex @option{-gnatA} (@command{gcc})
3714 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
3715 it will be ignored.
3716
3717 @item -gnatb
3718 @cindex @option{-gnatb} (@command{gcc})
3719 Generate brief messages to @file{stderr} even if verbose mode set.
3720
3721 @item -gnatB
3722 @cindex @option{-gnatB} (@command{gcc})
3723 Assume no invalid (bad) values except for 'Valid attribute use
3724 (@pxref{Validity Checking}).
3725
3726 @item -gnatc
3727 @cindex @option{-gnatc} (@command{gcc})
3728 Check syntax and semantics only (no code generation attempted). When the
3729 compiler is invoked by @command{gnatmake}, if the switch @option{-gnatc} is
3730 only given to the compiler (after @option{-cargs} or in package Compiler of
3731 the project file, @command{gnatmake} will fail because it will not find the
3732 object file after compilation. If @command{gnatmake} is called with
3733 @option{-gnatc} as a builder switch (before @option{-cargs} or in package
3734 Builder of the project file) then @command{gnatmake} will not fail because
3735 it will not look for the object files after compilation, and it will not try
3736 to build and link. This switch may not be given if a previous @code{-gnatR}
3737 switch has been given, since @code{-gnatR} requires that the code generator
3738 be called to complete determination of representation information.
3739
3740 @item -gnatC
3741 @cindex @option{-gnatC} (@command{gcc})
3742 Generate CodePeer intermediate format (no code generation attempted).
3743 This switch will generate an intermediate representation suitable for
3744 use by CodePeer (@file{.scil} files). This switch is not compatible with
3745 code generation (it will, among other things, disable some switches such
3746 as -gnatn, and enable others such as -gnata).
3747
3748 @item -gnatd
3749 @cindex @option{-gnatd} (@command{gcc})
3750 Specify debug options for the compiler. The string of characters after
3751 the @option{-gnatd} specify the specific debug options. The possible
3752 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3753 compiler source file @file{debug.adb} for details of the implemented
3754 debug options. Certain debug options are relevant to applications
3755 programmers, and these are documented at appropriate points in this
3756 users guide.
3757
3758 @ifclear vms
3759 @item -gnatD
3760 @cindex @option{-gnatD[nn]} (@command{gcc})
3761 @end ifclear
3762 @ifset vms
3763 @item /XDEBUG /LXDEBUG=nnn
3764 @end ifset
3765 Create expanded source files for source level debugging. This switch
3766 also suppress generation of cross-reference information
3767 (see @option{-gnatx}). Note that this switch is not allowed if a previous
3768 -gnatR switch has been given, since these two switches are not compatible.
3769
3770 @item ^-gnateA^/ALIASING_CHECK^
3771 @cindex @option{-gnateA} (@command{gcc})
3772 Check that the actual parameters of a subprogram call are not aliases of one
3773 another. To qualify as aliasing, the actuals must denote objects of a composite
3774 type, their memory locations must be identical or overlapping, and at least one
3775 of the corresponding formal parameters must be of mode OUT or IN OUT.
3776
3777 @smallexample
3778 type Rec_Typ is record
3779 Data : Integer := 0;
3780 end record;
3781
3782 function Self (Val : Rec_Typ) return Rec_Typ is
3783 begin
3784 return Val;
3785 end Self;
3786
3787 procedure Detect_Aliasing (Val_1 : in out Rec_Typ; Val_2 : Rec_Typ) is
3788 begin
3789 null;
3790 end Detect_Aliasing;
3791
3792 Obj : Rec_Typ;
3793
3794 Detect_Aliasing (Obj, Obj);
3795 Detect_Aliasing (Obj, Self (Obj));
3796 @end smallexample
3797
3798 In the example above, the first call to @code{Detect_Aliasing} fails with a
3799 @code{Program_Error} at runtime because the actuals for @code{Val_1} and
3800 @code{Val_2} denote the same object. The second call executes without raising
3801 an exception because @code{Self(Obj)} produces an anonymous object which does
3802 not share the memory location of @code{Obj}.
3803
3804 @item -gnatec=@var{path}
3805 @cindex @option{-gnatec} (@command{gcc})
3806 Specify a configuration pragma file
3807 @ifclear vms
3808 (the equal sign is optional)
3809 @end ifclear
3810 (@pxref{The Configuration Pragmas Files}).
3811
3812 @item -gnateC
3813 @cindex @option{-gnateC} (@command{gcc})
3814 Generate CodePeer messages in a compiler-like format. This switch is only
3815 effective if @option{-gnatcC} is also specified and requires an installation
3816 of CodePeer.
3817
3818 @item ^-gnated^/DISABLE_ATOMIC_SYNCHRONIZATION^
3819 @cindex @option{-gnated} (@command{gcc})
3820 Disable atomic synchronization
3821
3822 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
3823 @cindex @option{-gnateD} (@command{gcc})
3824 Defines a symbol, associated with @var{value}, for preprocessing.
3825 (@pxref{Integrated Preprocessing}).
3826
3827 @item -gnateE
3828 @cindex @option{-gnateE} (@command{gcc})
3829 Generate extra information in exception messages. In particular, display
3830 extra column information and the value and range associated with index and
3831 range check failures, and extra column information for access checks.
3832 In cases where the compiler is able to determine at compile time that
3833 a check will fail, it gives a warning, and the extra information is not
3834 produced at run time.
3835
3836 @item -gnatef
3837 @cindex @option{-gnatef} (@command{gcc})
3838 Display full source path name in brief error messages.
3839
3840 @item -gnateF
3841 @cindex @option{-gnateF} (@command{gcc})
3842 Check for overflow on all floating-point operations, including those
3843 for unconstrained predefined types. See description of pragma
3844 @code{Check_Float_Overflow} in GNAT RM.
3845
3846 @item -gnateG
3847 @cindex @option{-gnateG} (@command{gcc})
3848 Save result of preprocessing in a text file.
3849
3850 @item -gnatei@var{nnn}
3851 @cindex @option{-gnatei} (@command{gcc})
3852 Set maximum number of instantiations during compilation of a single unit to
3853 @var{nnn}. This may be useful in increasing the default maximum of 8000 for
3854 the rare case when a single unit legitimately exceeds this limit.
3855
3856 @item -gnateI@var{nnn}
3857 @cindex @option{-gnateI} (@command{gcc})
3858 Indicates that the source is a multi-unit source and that the index of the
3859 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
3860 to be a valid index in the multi-unit source.
3861
3862 @item -gnatel
3863 @cindex @option{-gnatel} (@command{gcc})
3864 This switch can be used with the static elaboration model to issue info
3865 messages showing
3866 where implicit @code{pragma Elaborate} and @code{pragma Elaborate_All}
3867 are generated. This is useful in diagnosing elaboration circularities
3868 caused by these implicit pragmas when using the static elaboration
3869 model. See See the section in this guide on elaboration checking for
3870 further details. These messages are not generated by default, and are
3871 intended only for temporary use when debugging circularity problems.
3872
3873 @item -gnateL
3874 @cindex @option{-gnatel} (@command{gcc})
3875 This switch turns off the info messages about implicit elaboration pragmas.
3876
3877 @item -gnatem=@var{path}
3878 @cindex @option{-gnatem} (@command{gcc})
3879 Specify a mapping file
3880 @ifclear vms
3881 (the equal sign is optional)
3882 @end ifclear
3883 (@pxref{Units to Sources Mapping Files}).
3884
3885 @item -gnatep=@var{file}
3886 @cindex @option{-gnatep} (@command{gcc})
3887 Specify a preprocessing data file
3888 @ifclear vms
3889 (the equal sign is optional)
3890 @end ifclear
3891 (@pxref{Integrated Preprocessing}).
3892
3893 @item -gnateP
3894 @cindex @option{-gnateP} (@command{gcc})
3895 Turn categorization dependency errors into warnings.
3896 Ada requires that units that WITH one another have compatible categories, for
3897 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
3898 these errors become warnings (which can be ignored, or suppressed in the usual
3899 manner). This can be useful in some specialized circumstances such as the
3900 temporary use of special test software.
3901
3902 @item -gnateS
3903 @cindex @option{-gnateS} (@command{gcc})
3904 Synonym of @option{-fdump-scos}, kept for backwards compatibility.
3905
3906 @item -gnatet=@var{path}
3907 @cindex @option{-gnatet=file} (@command{gcc})
3908 Generate target dependent information. The format of the output file is
3909 described in the section about switch @option{-gnateT}.
3910
3911 @item -gnateT=@var{path}
3912 @cindex @option{-gnateT} (@command{gcc})
3913 Read target dependent information, such as endianness or sizes and alignments
3914 of base type. If this switch is passed, the default target dependent
3915 information of the compiler is replaced by the one read from the input file.
3916 This is used by tools other than the compiler, e.g. to do
3917 semantic analysis of programs that will run on some other target than
3918 the machine on which the tool is run.
3919
3920 The following target dependent values should be defined,
3921 where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
3922 positive integer value, and fields marked with a question mark are
3923 boolean fields, where a value of 0 is False, and a value of 1 is True:
3924
3925 @smallexample
3926 Bits_BE : Nat; -- Bits stored big-endian?
3927 Bits_Per_Unit : Pos; -- Bits in a storage unit
3928 Bits_Per_Word : Pos; -- Bits in a word
3929 Bytes_BE : Nat; -- Bytes stored big-endian?
3930 Char_Size : Pos; -- Standard.Character'Size
3931 Double_Float_Alignment : Nat; -- Alignment of double float
3932 Double_Scalar_Alignment : Nat; -- Alignment of double length scalar
3933 Double_Size : Pos; -- Standard.Long_Float'Size
3934 Float_Size : Pos; -- Standard.Float'Size
3935 Float_Words_BE : Nat; -- Float words stored big-endian?
3936 Int_Size : Pos; -- Standard.Integer'Size
3937 Long_Double_Size : Pos; -- Standard.Long_Long_Float'Size
3938 Long_Long_Size : Pos; -- Standard.Long_Long_Integer'Size
3939 Long_Size : Pos; -- Standard.Long_Integer'Size
3940 Maximum_Alignment : Pos; -- Maximum permitted alignment
3941 Max_Unaligned_Field : Pos; -- Maximum size for unaligned bit field
3942 Pointer_Size : Pos; -- System.Address'Size
3943 Short_Enums : Nat; -- Short foreign convention enums?
3944 Short_Size : Pos; -- Standard.Short_Integer'Size
3945 Strict_Alignment : Nat; -- Strict alignment?
3946 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
3947 Wchar_T_Size : Pos; -- Interfaces.C.wchar_t'Size
3948 Words_BE : Nat; -- Words stored big-endian?
3949 @end smallexample
3950
3951 The format of the input file is as follows. First come the values of
3952 the variables defined above, with one line per value:
3953
3954 @smallexample
3955 name value
3956 @end smallexample
3957
3958 where @code{name} is the name of the parameter, spelled out in full,
3959 and cased as in the above list, and @code{value} is an unsigned decimal
3960 integer. Two or more blanks separates the name from the value.
3961
3962 All the variables must be present, in alphabetical order (i.e. the
3963 same order as the list above).
3964
3965 Then there is a blank line to separate the two parts of the file. Then
3966 come the lines showing the floating-point types to be registered, with
3967 one line per registered mode:
3968
3969 @smallexample
3970 name digs float_rep size alignment
3971 @end smallexample
3972
3973 where @code{name} is the string name of the type (which can have
3974 single spaces embedded in the name (e.g. long double), @code{digs} is
3975 the number of digits for the floating-point type, @code{float_rep} is
3976 the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
3977 AAMP), @code{size} is the size in bits, @code{alignment} is the
3978 alignment in bits. The name is followed by at least two blanks, fields
3979 are separated by at least one blank, and a LF character immediately
3980 follows the alignment field.
3981
3982 Here is an example of a target parameterization file:
3983
3984 @smallexample
3985 Bits_BE 0
3986 Bits_Per_Unit 8
3987 Bits_Per_Word 64
3988 Bytes_BE 0
3989 Char_Size 8
3990 Double_Float_Alignment 0
3991 Double_Scalar_Alignment 0
3992 Double_Size 64
3993 Float_Size 32
3994 Float_Words_BE 0
3995 Int_Size 64
3996 Long_Double_Size 128
3997 Long_Long_Size 64
3998 Long_Size 64
3999 Maximum_Alignment 16
4000 Max_Unaligned_Field 64
4001 Pointer_Size 64
4002 Short_Size 16
4003 Strict_Alignment 0
4004 System_Allocator_Alignment 16
4005 Wchar_T_Size 32
4006 Words_BE 0
4007
4008 float 15 I 64 64
4009 double 15 I 64 64
4010 long double 18 I 80 128
4011 TF 33 I 128 128
4012 @end smallexample
4013
4014 @item -gnateu
4015 @cindex @option{-gnateu} (@command{gcc})
4016 Ignore unrecognized validity, warning, and style switches that
4017 appear after this switch is given. This may be useful when
4018 compiling sources developed on a later version of the compiler
4019 with an earlier version. Of course the earlier version must
4020 support this switch.
4021
4022 @item ^-gnateV^/PARAMETER_VALIDITY_CHECK^
4023 @cindex @option{-gnateV} (@command{gcc})
4024 Check that all actual parameters of a subprogram call are valid according to
4025 the rules of validity checking (@pxref{Validity Checking}).
4026
4027 @item ^-gnateY^/IGNORE_SUPPRESS_SYLE_CHECK_PRAGMAS^
4028 @cindex @option{-gnateY} (@command{gcc})
4029 Ignore all STYLE_CHECKS pragmas. Full legality checks
4030 are still carried out, but the pragmas have no effect
4031 on what style checks are active. This allows all style
4032 checking options to be controlled from the command line.
4033
4034 @item -gnatE
4035 @cindex @option{-gnatE} (@command{gcc})
4036 Full dynamic elaboration checks.
4037
4038 @item -gnatf
4039 @cindex @option{-gnatf} (@command{gcc})
4040 Full errors. Multiple errors per line, all undefined references, do not
4041 attempt to suppress cascaded errors.
4042
4043 @item -gnatF
4044 @cindex @option{-gnatF} (@command{gcc})
4045 Externals names are folded to all uppercase.
4046
4047 @item ^-gnatg^/GNAT_INTERNAL^
4048 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4049 Internal GNAT implementation mode. This should not be used for
4050 applications programs, it is intended only for use by the compiler
4051 and its run-time library. For documentation, see the GNAT sources.
4052 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4053 @option{^-gnatw.ge^/WARNINGS=GNAT,ERRORS^} and
4054 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4055 so that all standard warnings and all standard style options are turned on.
4056 All warnings and style messages are treated as errors.
4057
4058 @ifclear vms
4059 @item -gnatG=nn
4060 @cindex @option{-gnatG[nn]} (@command{gcc})
4061 @end ifclear
4062 @ifset vms
4063 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4064 @end ifset
4065 List generated expanded code in source form.
4066
4067 @item ^-gnath^/HELP^
4068 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4069 Output usage information. The output is written to @file{stdout}.
4070
4071 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4072 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4073 Identifier character set
4074 @ifclear vms
4075 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4076 @end ifclear
4077 For details of the possible selections for @var{c},
4078 see @ref{Character Set Control}.
4079
4080 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4081 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4082 Ignore representation clauses. When this switch is used,
4083 representation clauses are treated as comments. This is useful
4084 when initially porting code where you want to ignore rep clause
4085 problems, and also for compiling foreign code (particularly
4086 for use with ASIS). The representation clauses that are ignored
4087 are: enumeration_representation_clause, record_representation_clause,
4088 and attribute_definition_clause for the following attributes:
4089 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4090 Object_Size, Size, Small, Stream_Size, and Value_Size.
4091 Note that this option should be used only for compiling -- the
4092 code is likely to malfunction at run time.
4093
4094 Note that when @code{-gnatct} is used to generate trees for input
4095 into @code{ASIS} tools, these representation clauses are removed
4096 from the tree and ignored. This means that the tool will not see them.
4097
4098 @item -gnatjnn
4099 @cindex @option{-gnatjnn} (@command{gcc})
4100 Reformat error messages to fit on nn character lines
4101
4102 @item -gnatk=@var{n}
4103 @cindex @option{-gnatk} (@command{gcc})
4104 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4105
4106 @item -gnatl
4107 @cindex @option{-gnatl} (@command{gcc})
4108 Output full source listing with embedded error messages.
4109
4110 @item -gnatL
4111 @cindex @option{-gnatL} (@command{gcc})
4112 Used in conjunction with -gnatG or -gnatD to intersperse original
4113 source lines (as comment lines with line numbers) in the expanded
4114 source output.
4115
4116 @item -gnatm=@var{n}
4117 @cindex @option{-gnatm} (@command{gcc})
4118 Limit number of detected error or warning messages to @var{n}
4119 where @var{n} is in the range 1..999999. The default setting if
4120 no switch is given is 9999. If the number of warnings reaches this
4121 limit, then a message is output and further warnings are suppressed,
4122 but the compilation is continued. If the number of error messages
4123 reaches this limit, then a message is output and the compilation
4124 is abandoned. The equal sign here is optional. A value of zero
4125 means that no limit applies.
4126
4127 @item -gnatn[12]
4128 @cindex @option{-gnatn} (@command{gcc})
4129 Activate inlining for subprograms for which pragma @code{Inline} is
4130 specified. This inlining is performed by the GCC back-end. An optional
4131 digit sets the inlining level: 1 for moderate inlining across modules
4132 or 2 for full inlining across modules. If no inlining level is specified,
4133 the compiler will pick it based on the optimization level.
4134
4135 @item -gnatN
4136 @cindex @option{-gnatN} (@command{gcc})
4137 Activate front end inlining for subprograms for which
4138 pragma @code{Inline} is specified. This inlining is performed
4139 by the front end and will be visible in the
4140 @option{-gnatG} output.
4141
4142 When using a gcc-based back end (in practice this means using any version
4143 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4144 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4145 Historically front end inlining was more extensive than the gcc back end
4146 inlining, but that is no longer the case.
4147
4148 @item -gnato??
4149 @cindex @option{-gnato??} (@command{gcc})
4150 Set default mode for handling generation of code to avoid intermediate
4151 arithmetic overflow. Here `@code{??}' is two digits, a
4152 single digit, or nothing. Each digit is one of the digits `@code{1}'
4153 through `@code{3}':
4154
4155 @itemize @bullet
4156 @item @code{1}:
4157 all intermediate overflows checked against base type (@code{STRICT})
4158 @item @code{2}:
4159 minimize intermediate overflows (@code{MINIMIZED})
4160 @item @code{3}:
4161 eliminate intermediate overflows (@code{ELIMINATED})
4162 @end itemize
4163
4164 If only one digit appears then it applies to all
4165 cases; if two digits are given, then the first applies outside
4166 assertions, and the second within assertions.
4167
4168 If no digits follow the @option{-gnato}, then it is equivalent to
4169 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
4170 causing all intermediate overflows to be handled in strict mode.
4171
4172 This switch also causes arithmetic overflow checking to be performed
4173 (as though pragma @code{Unsuppress (Overflow_Mode)} has been specified.
4174
4175 The default if no option @option{-gnato} is given is that overflow handling
4176 is in @code{STRICT} mode (computations done using the base type), and that
4177 overflow checking is suppressed.
4178
4179 Note that division by zero is a separate check that is not
4180 controlled by this switch (division by zero checking is on by default).
4181
4182 See also @ref{Specifying the Desired Mode}.
4183
4184 @item -gnatp
4185 @cindex @option{-gnatp} (@command{gcc})
4186 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4187 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4188
4189 @item -gnat-p
4190 @cindex @option{-gnat-p} (@command{gcc})
4191 Cancel effect of previous @option{-gnatp} switch.
4192
4193 @item -gnatP
4194 @cindex @option{-gnatP} (@command{gcc})
4195 Enable polling. This is required on some systems (notably Windows NT) to
4196 obtain asynchronous abort and asynchronous transfer of control capability.
4197 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4198 details.
4199
4200 @item -gnatq
4201 @cindex @option{-gnatq} (@command{gcc})
4202 Don't quit. Try semantics, even if parse errors.
4203
4204 @item -gnatQ
4205 @cindex @option{-gnatQ} (@command{gcc})
4206 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4207
4208 @item -gnatr
4209 @cindex @option{-gnatr} (@command{gcc})
4210 Treat pragma Restrictions as Restriction_Warnings.
4211
4212 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4213 @cindex @option{-gnatR} (@command{gcc})
4214 Output representation information for declared types and objects.
4215 Note that this switch is not allowed if a previous @code{-gnatD} switch has
4216 been given, since these two switches are not compatible.
4217
4218 @item ^-gnatRm[s]^/REPRESENTATION_INFO^
4219 Output convention and parameter passing mechanisms for all subprograms.
4220
4221 @item -gnats
4222 @cindex @option{-gnats} (@command{gcc})
4223 Syntax check only.
4224
4225 @item -gnatS
4226 @cindex @option{-gnatS} (@command{gcc})
4227 Print package Standard.
4228
4229 @item -gnatt
4230 @cindex @option{-gnatt} (@command{gcc})
4231 Generate tree output file.
4232
4233 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4234 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4235 All compiler tables start at @var{nnn} times usual starting size.
4236
4237 @item -gnatu
4238 @cindex @option{-gnatu} (@command{gcc})
4239 List units for this compilation.
4240
4241 @item -gnatU
4242 @cindex @option{-gnatU} (@command{gcc})
4243 Tag all error messages with the unique string ``error:''
4244
4245 @item -gnatv
4246 @cindex @option{-gnatv} (@command{gcc})
4247 Verbose mode. Full error output with source lines to @file{stdout}.
4248
4249 @item -gnatV
4250 @cindex @option{-gnatV} (@command{gcc})
4251 Control level of validity checking (@pxref{Validity Checking}).
4252
4253 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4254 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4255 Warning mode where
4256 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4257 the exact warnings that
4258 are enabled or disabled (@pxref{Warning Message Control}).
4259
4260 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4261 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4262 Wide character encoding method
4263 @ifclear vms
4264 (@var{e}=n/h/u/s/e/8).
4265 @end ifclear
4266 @ifset vms
4267 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4268 @end ifset
4269
4270 @item -gnatx
4271 @cindex @option{-gnatx} (@command{gcc})
4272 Suppress generation of cross-reference information.
4273
4274 @item -gnatX
4275 @cindex @option{-gnatX} (@command{gcc})
4276 Enable GNAT implementation extensions and latest Ada version.
4277
4278 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4279 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4280 Enable built-in style checks (@pxref{Style Checking}).
4281
4282 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4283 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4284 Distribution stub generation and compilation
4285 @ifclear vms
4286 (@var{m}=r/c for receiver/caller stubs).
4287 @end ifclear
4288 @ifset vms
4289 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4290 to be generated and compiled).
4291 @end ifset
4292
4293 @item ^-I^/SEARCH=^@var{dir}
4294 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4295 @cindex RTL
4296 Direct GNAT to search the @var{dir} directory for source files needed by
4297 the current compilation
4298 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4299
4300 @item ^-I-^/NOCURRENT_DIRECTORY^
4301 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4302 @cindex RTL
4303 Except for the source file named in the command line, do not look for source
4304 files in the directory containing the source file named in the command line
4305 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4306
4307 @ifclear vms
4308 @item -mbig-switch
4309 @cindex @option{-mbig-switch} (@command{gcc})
4310 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4311 This standard gcc switch causes the compiler to use larger offsets in its
4312 jump table representation for @code{case} statements.
4313 This may result in less efficient code, but is sometimes necessary
4314 (for example on HP-UX targets)
4315 @cindex HP-UX and @option{-mbig-switch} option
4316 in order to compile large and/or nested @code{case} statements.
4317
4318 @item -o @var{file}
4319 @cindex @option{-o} (@command{gcc})
4320 This switch is used in @command{gcc} to redirect the generated object file
4321 and its associated ALI file. Beware of this switch with GNAT, because it may
4322 cause the object file and ALI file to have different names which in turn
4323 may confuse the binder and the linker.
4324 @end ifclear
4325
4326 @item -nostdinc
4327 @cindex @option{-nostdinc} (@command{gcc})
4328 Inhibit the search of the default location for the GNAT Run Time
4329 Library (RTL) source files.
4330
4331 @item -nostdlib
4332 @cindex @option{-nostdlib} (@command{gcc})
4333 Inhibit the search of the default location for the GNAT Run Time
4334 Library (RTL) ALI files.
4335
4336 @ifclear vms
4337 @c @item -O@ovar{n}
4338 @c Expanding @ovar macro inline (explanation in macro def comments)
4339 @item -O@r{[}@var{n}@r{]}
4340 @cindex @option{-O} (@command{gcc})
4341 @var{n} controls the optimization level.
4342
4343 @table @asis
4344 @item n = 0
4345 No optimization, the default setting if no @option{-O} appears
4346
4347 @item n = 1
4348 Normal optimization, the default if you specify @option{-O} without
4349 an operand. A good compromise between code quality and compilation
4350 time.
4351
4352 @item n = 2
4353 Extensive optimization, may improve execution time, possibly at the cost of
4354 substantially increased compilation time.
4355
4356 @item n = 3
4357 Same as @option{-O2}, and also includes inline expansion for small subprograms
4358 in the same unit.
4359
4360 @item n = s
4361 Optimize space usage
4362 @end table
4363
4364 @noindent
4365 See also @ref{Optimization Levels}.
4366 @end ifclear
4367
4368 @ifset vms
4369 @item /NOOPTIMIZE
4370 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4371 Equivalent to @option{/OPTIMIZE=NONE}.
4372 This is the default behavior in the absence of an @option{/OPTIMIZE}
4373 qualifier.
4374
4375 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4376 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4377 Selects the level of optimization for your program. The supported
4378 keywords are as follows:
4379 @table @code
4380 @item ALL
4381 Perform most optimizations, including those that
4382 are expensive.
4383 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4384 without keyword options.
4385
4386 @item NONE
4387 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4388
4389 @item SOME
4390 Perform some optimizations, but omit ones that are costly.
4391
4392 @item DEVELOPMENT
4393 Same as @code{SOME}.
4394
4395 @item INLINING
4396 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4397 automatic inlining of small subprograms within a unit
4398
4399 @item UNROLL_LOOPS
4400 Try to unroll loops. This keyword may be specified together with
4401 any keyword above other than @code{NONE}. Loop unrolling
4402 usually, but not always, improves the performance of programs.
4403
4404 @item SPACE
4405 Optimize space usage
4406 @end table
4407
4408 @noindent
4409 See also @ref{Optimization Levels}.
4410 @end ifset
4411
4412 @ifclear vms
4413 @item -pass-exit-codes
4414 @cindex @option{-pass-exit-codes} (@command{gcc})
4415 Catch exit codes from the compiler and use the most meaningful as
4416 exit status.
4417 @end ifclear
4418
4419 @item --RTS=@var{rts-path}
4420 @cindex @option{--RTS} (@command{gcc})
4421 Specifies the default location of the runtime library. Same meaning as the
4422 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4423
4424 @item ^-S^/ASM^
4425 @cindex @option{^-S^/ASM^} (@command{gcc})
4426 ^Used in place of @option{-c} to^Used to^
4427 cause the assembler source file to be
4428 generated, using @file{^.s^.S^} as the extension,
4429 instead of the object file.
4430 This may be useful if you need to examine the generated assembly code.
4431
4432 @item ^-fverbose-asm^/VERBOSE_ASM^
4433 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4434 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4435 to cause the generated assembly code file to be annotated with variable
4436 names, making it significantly easier to follow.
4437
4438 @item ^-v^/VERBOSE^
4439 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4440 Show commands generated by the @command{gcc} driver. Normally used only for
4441 debugging purposes or if you need to be sure what version of the
4442 compiler you are executing.
4443
4444 @ifclear vms
4445 @item -V @var{ver}
4446 @cindex @option{-V} (@command{gcc})
4447 Execute @var{ver} version of the compiler. This is the @command{gcc}
4448 version, not the GNAT version.
4449 @end ifclear
4450
4451 @item ^-w^/NO_BACK_END_WARNINGS^
4452 @cindex @option{-w} (@command{gcc})
4453 Turn off warnings generated by the back end of the compiler. Use of
4454 this switch also causes the default for front end warnings to be set
4455 to suppress (as though @option{-gnatws} had appeared at the start of
4456 the options).
4457
4458 @end table
4459
4460 @ifclear vms
4461 @c Combining qualifiers does not work on VMS
4462 You may combine a sequence of GNAT switches into a single switch. For
4463 example, the combined switch
4464
4465 @cindex Combining GNAT switches
4466 @smallexample
4467 -gnatofi3
4468 @end smallexample
4469
4470 @noindent
4471 is equivalent to specifying the following sequence of switches:
4472
4473 @smallexample
4474 -gnato -gnatf -gnati3
4475 @end smallexample
4476 @end ifclear
4477
4478 @noindent
4479 The following restrictions apply to the combination of switches
4480 in this manner:
4481
4482 @itemize @bullet
4483 @item
4484 The switch @option{-gnatc} if combined with other switches must come
4485 first in the string.
4486
4487 @item
4488 The switch @option{-gnats} if combined with other switches must come
4489 first in the string.
4490
4491 @item
4492 The switches
4493 ^^@option{/DISTRIBUTION_STUBS=},^
4494 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4495 switches, and only one of them may appear in the command line.
4496
4497 @item
4498 The switch @option{-gnat-p} may not be combined with any other switch.
4499
4500 @ifclear vms
4501 @item
4502 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4503 switch), then all further characters in the switch are interpreted
4504 as style modifiers (see description of @option{-gnaty}).
4505
4506 @item
4507 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4508 switch), then all further characters in the switch are interpreted
4509 as debug flags (see description of @option{-gnatd}).
4510
4511 @item
4512 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4513 switch), then all further characters in the switch are interpreted
4514 as warning mode modifiers (see description of @option{-gnatw}).
4515
4516 @item
4517 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4518 switch), then all further characters in the switch are interpreted
4519 as validity checking options (@pxref{Validity Checking}).
4520
4521 @item
4522 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4523 a combined list of options.
4524 @end ifclear
4525 @end itemize
4526
4527 @node Output and Error Message Control
4528 @subsection Output and Error Message Control
4529 @findex stderr
4530
4531 @noindent
4532 The standard default format for error messages is called ``brief format''.
4533 Brief format messages are written to @file{stderr} (the standard error
4534 file) and have the following form:
4535
4536 @smallexample
4537 e.adb:3:04: Incorrect spelling of keyword "function"
4538 e.adb:4:20: ";" should be "is"
4539 @end smallexample
4540
4541 @noindent
4542 The first integer after the file name is the line number in the file,
4543 and the second integer is the column number within the line.
4544 @ifclear vms
4545 @code{GPS} can parse the error messages
4546 and point to the referenced character.
4547 @end ifclear
4548 The following switches provide control over the error message
4549 format:
4550
4551 @table @option
4552 @c !sort!
4553 @item -gnatv
4554 @cindex @option{-gnatv} (@command{gcc})
4555 @findex stdout
4556 @ifclear vms
4557 The v stands for verbose.
4558 @end ifclear
4559 The effect of this setting is to write long-format error
4560 messages to @file{stdout} (the standard output file.
4561 The same program compiled with the
4562 @option{-gnatv} switch would generate:
4563
4564 @smallexample
4565 @cartouche
4566 3. funcion X (Q : Integer)
4567 |
4568 >>> Incorrect spelling of keyword "function"
4569 4. return Integer;
4570 |
4571 >>> ";" should be "is"
4572 @end cartouche
4573 @end smallexample
4574
4575 @noindent
4576 The vertical bar indicates the location of the error, and the @samp{>>>}
4577 prefix can be used to search for error messages. When this switch is
4578 used the only source lines output are those with errors.
4579
4580 @item -gnatl
4581 @cindex @option{-gnatl} (@command{gcc})
4582 @ifclear vms
4583 The @code{l} stands for list.
4584 @end ifclear
4585 This switch causes a full listing of
4586 the file to be generated. In the case where a body is
4587 compiled, the corresponding spec is also listed, along
4588 with any subunits. Typical output from compiling a package
4589 body @file{p.adb} might look like:
4590
4591 @smallexample @c ada
4592 @cartouche
4593 Compiling: p.adb
4594
4595 1. package body p is
4596 2. procedure a;
4597 3. procedure a is separate;
4598 4. begin
4599 5. null
4600 |
4601 >>> missing ";"
4602
4603 6. end;
4604
4605 Compiling: p.ads
4606
4607 1. package p is
4608 2. pragma Elaborate_Body
4609 |
4610 >>> missing ";"
4611
4612 3. end p;
4613
4614 Compiling: p-a.adb
4615
4616 1. separate p
4617 |
4618 >>> missing "("
4619
4620 2. procedure a is
4621 3. begin
4622 4. null
4623 |
4624 >>> missing ";"
4625
4626 5. end;
4627 @end cartouche
4628 @end smallexample
4629
4630 @noindent
4631 @findex stderr
4632 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4633 standard output is redirected, a brief summary is written to
4634 @file{stderr} (standard error) giving the number of error messages and
4635 warning messages generated.
4636
4637 @item ^-gnatl^/OUTPUT_FILE^=file
4638 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4639 This has the same effect as @option{-gnatl} except that the output is
4640 written to a file instead of to standard output. If the given name
4641 @file{fname} does not start with a period, then it is the full name
4642 of the file to be written. If @file{fname} is an extension, it is
4643 appended to the name of the file being compiled. For example, if
4644 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4645 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4646
4647 @item -gnatU
4648 @cindex @option{-gnatU} (@command{gcc})
4649 This switch forces all error messages to be preceded by the unique
4650 string ``error:''. This means that error messages take a few more
4651 characters in space, but allows easy searching for and identification
4652 of error messages.
4653
4654 @item -gnatb
4655 @cindex @option{-gnatb} (@command{gcc})
4656 @ifclear vms
4657 The @code{b} stands for brief.
4658 @end ifclear
4659 This switch causes GNAT to generate the
4660 brief format error messages to @file{stderr} (the standard error
4661 file) as well as the verbose
4662 format message or full listing (which as usual is written to
4663 @file{stdout} (the standard output file).
4664
4665 @item -gnatm=@var{n}
4666 @cindex @option{-gnatm} (@command{gcc})
4667 @ifclear vms
4668 The @code{m} stands for maximum.
4669 @end ifclear
4670 @var{n} is a decimal integer in the
4671 range of 1 to 999999 and limits the number of error or warning
4672 messages to be generated. For example, using
4673 @option{-gnatm2} might yield
4674
4675 @smallexample
4676 e.adb:3:04: Incorrect spelling of keyword "function"
4677 e.adb:5:35: missing ".."
4678 fatal error: maximum number of errors detected
4679 compilation abandoned
4680 @end smallexample
4681
4682 @noindent
4683 The default setting if
4684 no switch is given is 9999. If the number of warnings reaches this
4685 limit, then a message is output and further warnings are suppressed,
4686 but the compilation is continued. If the number of error messages
4687 reaches this limit, then a message is output and the compilation
4688 is abandoned. A value of zero means that no limit applies.
4689
4690 @noindent
4691 Note that the equal sign is optional, so the switches
4692 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4693
4694 @item -gnatf
4695 @cindex @option{-gnatf} (@command{gcc})
4696 @cindex Error messages, suppressing
4697 @ifclear vms
4698 The @code{f} stands for full.
4699 @end ifclear
4700 Normally, the compiler suppresses error messages that are likely to be
4701 redundant. This switch causes all error
4702 messages to be generated. In particular, in the case of
4703 references to undefined variables. If a given variable is referenced
4704 several times, the normal format of messages is
4705 @smallexample
4706 e.adb:7:07: "V" is undefined (more references follow)
4707 @end smallexample
4708
4709 @noindent
4710 where the parenthetical comment warns that there are additional
4711 references to the variable @code{V}. Compiling the same program with the
4712 @option{-gnatf} switch yields
4713
4714 @smallexample
4715 e.adb:7:07: "V" is undefined
4716 e.adb:8:07: "V" is undefined
4717 e.adb:8:12: "V" is undefined
4718 e.adb:8:16: "V" is undefined
4719 e.adb:9:07: "V" is undefined
4720 e.adb:9:12: "V" is undefined
4721 @end smallexample
4722
4723 @noindent
4724 The @option{-gnatf} switch also generates additional information for
4725 some error messages. Some examples are:
4726
4727 @itemize @bullet
4728 @item
4729 Details on possibly non-portable unchecked conversion
4730 @item
4731 List possible interpretations for ambiguous calls
4732 @item
4733 Additional details on incorrect parameters
4734 @end itemize
4735
4736 @item -gnatjnn
4737 @cindex @option{-gnatjnn} (@command{gcc})
4738 In normal operation mode (or if @option{-gnatj0} is used), then error messages
4739 with continuation lines are treated as though the continuation lines were
4740 separate messages (and so a warning with two continuation lines counts as
4741 three warnings, and is listed as three separate messages).
4742
4743 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4744 messages are output in a different manner. A message and all its continuation
4745 lines are treated as a unit, and count as only one warning or message in the
4746 statistics totals. Furthermore, the message is reformatted so that no line
4747 is longer than nn characters.
4748
4749 @item -gnatq
4750 @cindex @option{-gnatq} (@command{gcc})
4751 @ifclear vms
4752 The @code{q} stands for quit (really ``don't quit'').
4753 @end ifclear
4754 In normal operation mode, the compiler first parses the program and
4755 determines if there are any syntax errors. If there are, appropriate
4756 error messages are generated and compilation is immediately terminated.
4757 This switch tells
4758 GNAT to continue with semantic analysis even if syntax errors have been
4759 found. This may enable the detection of more errors in a single run. On
4760 the other hand, the semantic analyzer is more likely to encounter some
4761 internal fatal error when given a syntactically invalid tree.
4762
4763 @item -gnatQ
4764 @cindex @option{-gnatQ} (@command{gcc})
4765 In normal operation mode, the @file{ALI} file is not generated if any
4766 illegalities are detected in the program. The use of @option{-gnatQ} forces
4767 generation of the @file{ALI} file. This file is marked as being in
4768 error, so it cannot be used for binding purposes, but it does contain
4769 reasonably complete cross-reference information, and thus may be useful
4770 for use by tools (e.g., semantic browsing tools or integrated development
4771 environments) that are driven from the @file{ALI} file. This switch
4772 implies @option{-gnatq}, since the semantic phase must be run to get a
4773 meaningful ALI file.
4774
4775 In addition, if @option{-gnatt} is also specified, then the tree file is
4776 generated even if there are illegalities. It may be useful in this case
4777 to also specify @option{-gnatq} to ensure that full semantic processing
4778 occurs. The resulting tree file can be processed by ASIS, for the purpose
4779 of providing partial information about illegal units, but if the error
4780 causes the tree to be badly malformed, then ASIS may crash during the
4781 analysis.
4782
4783 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4784 being in error, @command{gnatmake} will attempt to recompile the source when it
4785 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4786
4787 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4788 since ALI files are never generated if @option{-gnats} is set.
4789
4790 @end table
4791
4792 @node Warning Message Control
4793 @subsection Warning Message Control
4794 @cindex Warning messages
4795 @noindent
4796 In addition to error messages, which correspond to illegalities as defined
4797 in the Ada Reference Manual, the compiler detects two kinds of warning
4798 situations.
4799
4800 First, the compiler considers some constructs suspicious and generates a
4801 warning message to alert you to a possible error. Second, if the
4802 compiler detects a situation that is sure to raise an exception at
4803 run time, it generates a warning message. The following shows an example
4804 of warning messages:
4805 @smallexample
4806 e.adb:4:24: warning: creation of object may raise Storage_Error
4807 e.adb:10:17: warning: static value out of range
4808 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4809 @end smallexample
4810
4811 @noindent
4812 GNAT considers a large number of situations as appropriate
4813 for the generation of warning messages. As always, warnings are not
4814 definite indications of errors. For example, if you do an out-of-range
4815 assignment with the deliberate intention of raising a
4816 @code{Constraint_Error} exception, then the warning that may be
4817 issued does not indicate an error. Some of the situations for which GNAT
4818 issues warnings (at least some of the time) are given in the following
4819 list. This list is not complete, and new warnings are often added to
4820 subsequent versions of GNAT. The list is intended to give a general idea
4821 of the kinds of warnings that are generated.
4822
4823 @itemize @bullet
4824 @item
4825 Possible infinitely recursive calls
4826
4827 @item
4828 Out-of-range values being assigned
4829
4830 @item
4831 Possible order of elaboration problems
4832
4833 @item
4834 Size not a multiple of alignment for a record type
4835
4836 @item
4837 Assertions (pragma Assert) that are sure to fail
4838
4839 @item
4840 Unreachable code
4841
4842 @item
4843 Address clauses with possibly unaligned values, or where an attempt is
4844 made to overlay a smaller variable with a larger one.
4845
4846 @item
4847 Fixed-point type declarations with a null range
4848
4849 @item
4850 Direct_IO or Sequential_IO instantiated with a type that has access values
4851
4852 @item
4853 Variables that are never assigned a value
4854
4855 @item
4856 Variables that are referenced before being initialized
4857
4858 @item
4859 Task entries with no corresponding @code{accept} statement
4860
4861 @item
4862 Duplicate accepts for the same task entry in a @code{select}
4863
4864 @item
4865 Objects that take too much storage
4866
4867 @item
4868 Unchecked conversion between types of differing sizes
4869
4870 @item
4871 Missing @code{return} statement along some execution path in a function
4872
4873 @item
4874 Incorrect (unrecognized) pragmas
4875
4876 @item
4877 Incorrect external names
4878
4879 @item
4880 Allocation from empty storage pool
4881
4882 @item
4883 Potentially blocking operation in protected type
4884
4885 @item
4886 Suspicious parenthesization of expressions
4887
4888 @item
4889 Mismatching bounds in an aggregate
4890
4891 @item
4892 Attempt to return local value by reference
4893
4894 @item
4895 Premature instantiation of a generic body
4896
4897 @item
4898 Attempt to pack aliased components
4899
4900 @item
4901 Out of bounds array subscripts
4902
4903 @item
4904 Wrong length on string assignment
4905
4906 @item
4907 Violations of style rules if style checking is enabled
4908
4909 @item
4910 Unused @code{with} clauses
4911
4912 @item
4913 @code{Bit_Order} usage that does not have any effect
4914
4915 @item
4916 @code{Standard.Duration} used to resolve universal fixed expression
4917
4918 @item
4919 Dereference of possibly null value
4920
4921 @item
4922 Declaration that is likely to cause storage error
4923
4924 @item
4925 Internal GNAT unit @code{with}'ed by application unit
4926
4927 @item
4928 Values known to be out of range at compile time
4929
4930 @item
4931 Unreferenced or unmodified variables. Note that a special
4932 exemption applies to variables which contain any of the substrings
4933 @code{DISCARD, DUMMY, IGNORE, JUNK, UNUSED}, in any casing. Such variables
4934 are considered likely to be intentionally used in a situation where
4935 otherwise a warning would be given, so warnings of this kind are
4936 always suppressed for such variables.
4937
4938 @item
4939 Address overlays that could clobber memory
4940
4941 @item
4942 Unexpected initialization when address clause present
4943
4944 @item
4945 Bad alignment for address clause
4946
4947 @item
4948 Useless type conversions
4949
4950 @item
4951 Redundant assignment statements and other redundant constructs
4952
4953 @item
4954 Useless exception handlers
4955
4956 @item
4957 Accidental hiding of name by child unit
4958
4959 @item
4960 Access before elaboration detected at compile time
4961
4962 @item
4963 A range in a @code{for} loop that is known to be null or might be null
4964
4965 @end itemize
4966
4967 @noindent
4968 The following section lists compiler switches that are available
4969 to control the handling of warning messages. It is also possible
4970 to exercise much finer control over what warnings are issued and
4971 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
4972 gnat_rm, GNAT Reference manual}.
4973
4974 @table @option
4975 @c !sort!
4976 @item -gnatwa
4977 @emph{Activate most optional warnings.}
4978 @cindex @option{-gnatwa} (@command{gcc})
4979 This switch activates most optional warning messages. See the remaining list
4980 in this section for details on optional warning messages that can be
4981 individually controlled. The warnings that are not turned on by this
4982 switch are:
4983 @option{-gnatwd} (implicit dereferencing),
4984 @option{-gnatwh} (hiding),
4985 @option{-gnatw.d} (tag warnings with -gnatw switch)
4986 @option{-gnatw.h} (holes (gaps) in record layouts)
4987 @option{-gnatw.i} (overlapping actuals),
4988 @option{-gnatw.k} (redefinition of names in standard),
4989 @option{-gnatwl} (elaboration warnings),
4990 @option{-gnatw.l} (inherited aspects),
4991 @option{-gnatw.o} (warn on values set by out parameters ignored),
4992 @option{-gnatwt} (tracking of deleted conditional code)
4993 and @option{-gnatw.u} (unordered enumeration),
4994 All other optional warnings are turned on.
4995
4996 @item -gnatwA
4997 @emph{Suppress all optional errors.}
4998 @cindex @option{-gnatwA} (@command{gcc})
4999 This switch suppresses all optional warning messages, see remaining list
5000 in this section for details on optional warning messages that can be
5001 individually controlled. Note that unlike switch @option{-gnatws}, the
5002 use of switch @option{-gnatwA} does not suppress warnings that are
5003 normally given unconditionally and cannot be individually controlled
5004 (for example, the warning about a missing exit path in a function).
5005 Also, again unlike switch @option{-gnatws}, warnings suppressed by
5006 the use of switch @option{-gnatwA} can be individually turned back
5007 on. For example the use of switch @option{-gnatwA} followed by
5008 switch @option{-gnatwd} will suppress all optional warnings except
5009 the warnings for implicit dereferencing.
5010
5011 @item -gnatw.a
5012 @emph{Activate warnings on failing assertions.}
5013 @cindex @option{-gnatw.a} (@command{gcc})
5014 @cindex Assert failures
5015 This switch activates warnings for assertions where the compiler can tell at
5016 compile time that the assertion will fail. Note that this warning is given
5017 even if assertions are disabled. The default is that such warnings are
5018 generated.
5019
5020 @item -gnatw.A
5021 @emph{Suppress warnings on failing assertions.}
5022 @cindex @option{-gnatw.A} (@command{gcc})
5023 @cindex Assert failures
5024 This switch suppresses warnings for assertions where the compiler can tell at
5025 compile time that the assertion will fail.
5026
5027 @item -gnatwb
5028 @emph{Activate warnings on bad fixed values.}
5029 @cindex @option{-gnatwb} (@command{gcc})
5030 @cindex Bad fixed values
5031 @cindex Fixed-point Small value
5032 @cindex Small value
5033 This switch activates warnings for static fixed-point expressions whose
5034 value is not an exact multiple of Small. Such values are implementation
5035 dependent, since an implementation is free to choose either of the multiples
5036 that surround the value. GNAT always chooses the closer one, but this is not
5037 required behavior, and it is better to specify a value that is an exact
5038 multiple, ensuring predictable execution. The default is that such warnings
5039 are not generated.
5040
5041 @item -gnatwB
5042 @emph{Suppress warnings on bad fixed values.}
5043 @cindex @option{-gnatwB} (@command{gcc})
5044 This switch suppresses warnings for static fixed-point expressions whose
5045 value is not an exact multiple of Small.
5046
5047 @item -gnatw.b
5048 @emph{Activate warnings on biased representation.}
5049 @cindex @option{-gnatw.b} (@command{gcc})
5050 @cindex Biased representation
5051 This switch activates warnings when a size clause, value size clause, component
5052 clause, or component size clause forces the use of biased representation for an
5053 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5054 to represent 10/11). The default is that such warnings are generated.
5055
5056 @item -gnatw.B
5057 @emph{Suppress warnings on biased representation.}
5058 @cindex @option{-gnatwB} (@command{gcc})
5059 This switch suppresses warnings for representation clauses that force the use
5060 of biased representation.
5061
5062 @item -gnatwc
5063 @emph{Activate warnings on conditionals.}
5064 @cindex @option{-gnatwc} (@command{gcc})
5065 @cindex Conditionals, constant
5066 This switch activates warnings for conditional expressions used in
5067 tests that are known to be True or False at compile time. The default
5068 is that such warnings are not generated.
5069 Note that this warning does
5070 not get issued for the use of boolean variables or constants whose
5071 values are known at compile time, since this is a standard technique
5072 for conditional compilation in Ada, and this would generate too many
5073 false positive warnings.
5074
5075 This warning option also activates a special test for comparisons using
5076 the operators ``>='' and`` <=''.
5077 If the compiler can tell that only the equality condition is possible,
5078 then it will warn that the ``>'' or ``<'' part of the test
5079 is useless and that the operator could be replaced by ``=''.
5080 An example would be comparing a @code{Natural} variable <= 0.
5081
5082 This warning option also generates warnings if
5083 one or both tests is optimized away in a membership test for integer
5084 values if the result can be determined at compile time. Range tests on
5085 enumeration types are not included, since it is common for such tests
5086 to include an end point.
5087
5088 This warning can also be turned on using @option{-gnatwa}.
5089
5090 @item -gnatwC
5091 @emph{Suppress warnings on conditionals.}
5092 @cindex @option{-gnatwC} (@command{gcc})
5093 This switch suppresses warnings for conditional expressions used in
5094 tests that are known to be True or False at compile time.
5095
5096 @item -gnatw.c
5097 @emph{Activate warnings on missing component clauses.}
5098 @cindex @option{-gnatw.c} (@command{gcc})
5099 @cindex Component clause, missing
5100 This switch activates warnings for record components where a record
5101 representation clause is present and has component clauses for the
5102 majority, but not all, of the components. A warning is given for each
5103 component for which no component clause is present.
5104
5105 This warning can also be turned on using @option{-gnatwa}.
5106
5107 @item -gnatw.C
5108 @emph{Suppress warnings on missing component clauses.}
5109 @cindex @option{-gnatwC} (@command{gcc})
5110 This switch suppresses warnings for record components that are
5111 missing a component clause in the situation described above.
5112
5113 @item -gnatwd
5114 @emph{Activate warnings on implicit dereferencing.}
5115 @cindex @option{-gnatwd} (@command{gcc})
5116 If this switch is set, then the use of a prefix of an access type
5117 in an indexed component, slice, or selected component without an
5118 explicit @code{.all} will generate a warning. With this warning
5119 enabled, access checks occur only at points where an explicit
5120 @code{.all} appears in the source code (assuming no warnings are
5121 generated as a result of this switch). The default is that such
5122 warnings are not generated.
5123 Note that @option{-gnatwa} does not affect the setting of
5124 this warning option.
5125
5126 @item -gnatwD
5127 @emph{Suppress warnings on implicit dereferencing.}
5128 @cindex @option{-gnatwD} (@command{gcc})
5129 @cindex Implicit dereferencing
5130 @cindex Dereferencing, implicit
5131 This switch suppresses warnings for implicit dereferences in
5132 indexed components, slices, and selected components.
5133
5134 @item -gnatw.d
5135 @emph{Activate tagging of warning and info messages.}
5136 @cindex @option{-gnatw.d} (@command{gcc})
5137 If this switch is set, then warning messages are tagged, with one of the
5138 following strings:
5139
5140 @table @option
5141
5142 @item [-gnatw?]
5143 Used to tag warnings controlled by the switch @option{-gnatwx} where x
5144 is a letter a-z.
5145
5146 @item [-gnatw.?]
5147 Used to tag warnings controlled by the switch @option{-gnatw.x} where x
5148 is a letter a-z.
5149
5150 @item [-gnatel]
5151 Used to tag elaboration information (info) messages generated when the
5152 static model of elaboration is used and the @option{-gnatel} switch is set.
5153
5154 @item [restriction warning]
5155 Used to tag warning messages for restriction violations, activated by use
5156 of the pragma @option{Restriction_Warnings}.
5157
5158 @item [warning-as-error]
5159 Used to tag warning messages that have been converted to error messages by
5160 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
5161 the string "error: " rather than "warning: ".
5162
5163 @item [enabled by default]
5164 Used to tag all other warnings that are always given by default, unless
5165 warnings are completely suppressed using pragma @option{Warnings(Off)} or
5166 the switch @option{-gnatws}.
5167
5168 @end table
5169
5170 @item -gnatw.D
5171 @emph{Deactivate tagging of warning and info messages messages.}
5172 @cindex @option{-gnatw.d} (@command{gcc})
5173 If this switch is set, then warning messages return to the default
5174 mode in which warnings and info messages are not tagged as described above for
5175 @code{-gnatw.d}.
5176
5177 @item -gnatwe
5178 @emph{Treat warnings and style checks as errors.}
5179 @cindex @option{-gnatwe} (@command{gcc})
5180 @cindex Warnings, treat as error
5181 This switch causes warning messages and style check messages to be
5182 treated as errors.
5183 The warning string still appears, but the warning messages are counted
5184 as errors, and prevent the generation of an object file. Note that this
5185 is the only -gnatw switch that affects the handling of style check messages.
5186
5187 @item -gnatw.e
5188 @emph{Activate every optional warning}
5189 @cindex @option{-gnatw.e} (@command{gcc})
5190 @cindex Warnings, activate every optional warning
5191 This switch activates all optional warnings, including those which
5192 are not activated by @code{-gnatwa}. The use of this switch is not
5193 recommended for normal use. If you turn this switch on, it is almost
5194 certain that you will get large numbers of useless warnings. The
5195 warnings that are excluded from @code{-gnatwa} are typically highly
5196 specialized warnings that are suitable for use only in code that has
5197 been specifically designed according to specialized coding rules.
5198
5199 @item -gnatwf
5200 @emph{Activate warnings on unreferenced formals.}
5201 @cindex @option{-gnatwf} (@command{gcc})
5202 @cindex Formals, unreferenced
5203 This switch causes a warning to be generated if a formal parameter
5204 is not referenced in the body of the subprogram. This warning can
5205 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5206 default is that these warnings are not generated.
5207
5208 @item -gnatwF
5209 @emph{Suppress warnings on unreferenced formals.}
5210 @cindex @option{-gnatwF} (@command{gcc})
5211 This switch suppresses warnings for unreferenced formal
5212 parameters. Note that the
5213 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5214 effect of warning on unreferenced entities other than subprogram
5215 formals.
5216
5217 @item -gnatwg
5218 @emph{Activate warnings on unrecognized pragmas.}
5219 @cindex @option{-gnatwg} (@command{gcc})
5220 @cindex Pragmas, unrecognized
5221 This switch causes a warning to be generated if an unrecognized
5222 pragma is encountered. Apart from issuing this warning, the
5223 pragma is ignored and has no effect. This warning can
5224 also be turned on using @option{-gnatwa}. The default
5225 is that such warnings are issued (satisfying the Ada Reference
5226 Manual requirement that such warnings appear).
5227
5228 @item -gnatwG
5229 @emph{Suppress warnings on unrecognized pragmas.}
5230 @cindex @option{-gnatwG} (@command{gcc})
5231 This switch suppresses warnings for unrecognized pragmas.
5232
5233 @item -gnatw.g
5234 @emph{Warnings used for GNAT sources}
5235 @cindex @option{-gnatw.g} (@command{gcc})
5236 This switch sets the warning categories that are used by the standard
5237 GNAT style. Currently this is equivalent to
5238 @option{-gnatwAao.sI.C.V.X}
5239 but more warnings may be added in the future without advanced notice.
5240
5241 @item -gnatwh
5242 @emph{Activate warnings on hiding.}
5243 @cindex @option{-gnatwh} (@command{gcc})
5244 @cindex Hiding of Declarations
5245 This switch activates warnings on hiding declarations.
5246 A declaration is considered hiding
5247 if it is for a non-overloadable entity, and it declares an entity with the
5248 same name as some other entity that is directly or use-visible. The default
5249 is that such warnings are not generated.
5250 Note that @option{-gnatwa} does not affect the setting of this warning option.
5251
5252 @item -gnatwH
5253 @emph{Suppress warnings on hiding.}
5254 @cindex @option{-gnatwH} (@command{gcc})
5255 This switch suppresses warnings on hiding declarations.
5256
5257 @item -gnatw.h
5258 @emph{Activate warnings on holes/gaps in records.}
5259 @cindex @option{-gnatw.h} (@command{gcc})
5260 @cindex Record Representation (gaps)
5261 This switch activates warnings on component clauses in record
5262 representation clauses that leave holes (gaps) in the record layout.
5263 If this warning option is active, then record representation clauses
5264 should specify a contiguous layout, adding unused fill fields if needed.
5265 Note that @option{-gnatwa} does not affect the setting of this warning option.
5266
5267 @item -gnatw.H
5268 @emph{Suppress warnings on holes/gaps in records.}
5269 @cindex @option{-gnatw.H} (@command{gcc})
5270 This switch suppresses warnings on component clauses in record
5271 representation clauses that leave holes (haps) in the record layout.
5272
5273 @item -gnatwi
5274 @emph{Activate warnings on implementation units.}
5275 @cindex @option{-gnatwi} (@command{gcc})
5276 This switch activates warnings for a @code{with} of an internal GNAT
5277 implementation unit, defined as any unit from the @code{Ada},
5278 @code{Interfaces}, @code{GNAT},
5279 ^^@code{DEC},^ or @code{System}
5280 hierarchies that is not
5281 documented in either the Ada Reference Manual or the GNAT
5282 Programmer's Reference Manual. Such units are intended only
5283 for internal implementation purposes and should not be @code{with}'ed
5284 by user programs. The default is that such warnings are generated
5285 This warning can also be turned on using @option{-gnatwa}.
5286
5287 @item -gnatwI
5288 @emph{Disable warnings on implementation units.}
5289 @cindex @option{-gnatwI} (@command{gcc})
5290 This switch disables warnings for a @code{with} of an internal GNAT
5291 implementation unit.
5292
5293 @item -gnatw.i
5294 @emph{Activate warnings on overlapping actuals.}
5295 @cindex @option{-gnatw.i} (@command{gcc})
5296 This switch enables a warning on statically detectable overlapping actuals in
5297 a subprogram call, when one of the actuals is an in-out parameter, and the
5298 types of the actuals are not by-copy types. The warning is off by default,
5299 and is not included under -gnatwa.
5300
5301 @item -gnatw.I
5302 @emph{Disable warnings on overlapping actuals.}
5303 @cindex @option{-gnatw.I} (@command{gcc})
5304 This switch disables warnings on overlapping actuals in a call..
5305
5306 @item -gnatwj
5307 @emph{Activate warnings on obsolescent features (Annex J).}
5308 @cindex @option{-gnatwj} (@command{gcc})
5309 @cindex Features, obsolescent
5310 @cindex Obsolescent features
5311 If this warning option is activated, then warnings are generated for
5312 calls to subprograms marked with @code{pragma Obsolescent} and
5313 for use of features in Annex J of the Ada Reference Manual. In the
5314 case of Annex J, not all features are flagged. In particular use
5315 of the renamed packages (like @code{Text_IO}) and use of package
5316 @code{ASCII} are not flagged, since these are very common and
5317 would generate many annoying positive warnings. The default is that
5318 such warnings are not generated. This warning is also turned on by
5319 the use of @option{-gnatwa}.
5320
5321 In addition to the above cases, warnings are also generated for
5322 GNAT features that have been provided in past versions but which
5323 have been superseded (typically by features in the new Ada standard).
5324 For example, @code{pragma Ravenscar} will be flagged since its
5325 function is replaced by @code{pragma Profile(Ravenscar)}, and
5326 @code{pragma Interface_Name} will be flagged since its function
5327 is replaced by @code{pragma Import}.
5328
5329 Note that this warning option functions differently from the
5330 restriction @code{No_Obsolescent_Features} in two respects.
5331 First, the restriction applies only to annex J features.
5332 Second, the restriction does flag uses of package @code{ASCII}.
5333
5334 @item -gnatwJ
5335 @emph{Suppress warnings on obsolescent features (Annex J).}
5336 @cindex @option{-gnatwJ} (@command{gcc})
5337 This switch disables warnings on use of obsolescent features.
5338
5339 @item -gnatwk
5340 @emph{Activate warnings on variables that could be constants.}
5341 @cindex @option{-gnatwk} (@command{gcc})
5342 This switch activates warnings for variables that are initialized but
5343 never modified, and then could be declared constants. The default is that
5344 such warnings are not given.
5345 This warning can also be turned on using @option{-gnatwa}.
5346
5347 @item -gnatwK
5348 @emph{Suppress warnings on variables that could be constants.}
5349 @cindex @option{-gnatwK} (@command{gcc})
5350 This switch disables warnings on variables that could be declared constants.
5351
5352 @item -gnatw.k
5353 @emph{Activate warnings on redefinition of names in standard.}
5354 @cindex @option{-gnatw.k} (@command{gcc})
5355 This switch activates warnings for declarations that declare a name that
5356 is defined in package Standard. Such declarations can be confusing,
5357 especially since the names in package Standard continue to be directly
5358 visible, meaning that use visibiliy on such redeclared names does not
5359 work as expected. Names of discriminants and components in records are
5360 not included in this check.
5361 This warning is not part of the warnings activated by @option{-gnatwa}.
5362 It must be explicitly activated.
5363
5364 @item -gnatw.K
5365 @emph{Suppress warnings on variables that could be constants.}
5366 @cindex @option{-gnatwK} (@command{gcc})
5367 This switch activates warnings for declarations that declare a name that
5368 is defined in package Standard.
5369
5370 @item -gnatwl
5371 @emph{Activate warnings for elaboration pragmas.}
5372 @cindex @option{-gnatwl} (@command{gcc})
5373 @cindex Elaboration, warnings
5374 This switch activates warnings on missing
5375 for possible elaboration problems, including suspicious use
5376 of @code{Elaborate} pragmas, when using the static elaboration model, and
5377 possible situations that may raise @code{Program_Error} when using the
5378 dynamic elaboration model.
5379 See the section in this guide on elaboration checking for further details.
5380 The default is that such warnings
5381 are not generated.
5382 This warning is not automatically turned on by the use of @option{-gnatwa}.
5383
5384 @item -gnatwL
5385 @emph{Suppress warnings for elaboration pragmas.}
5386 @cindex @option{-gnatwL} (@command{gcc})
5387 This switch suppresses warnings for possible elaboration problems.
5388
5389 @item -gnatw.l
5390 @emph{List inherited aspects.}
5391 @cindex @option{-gnatw.l} (@command{gcc})
5392 This switch causes the compiler to list inherited invariants,
5393 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
5394 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
5395 These messages are not automatically turned on by the use of @option{-gnatwa}.
5396
5397 @item -gnatw.L
5398 @emph{Suppress listing of inherited aspects.}
5399 @cindex @option{-gnatw.L} (@command{gcc})
5400 This switch suppresses listing of inherited aspects.
5401
5402 @item -gnatwm
5403 @emph{Activate warnings on modified but unreferenced variables.}
5404 @cindex @option{-gnatwm} (@command{gcc})
5405 This switch activates warnings for variables that are assigned (using
5406 an initialization value or with one or more assignment statements) but
5407 whose value is never read. The warning is suppressed for volatile
5408 variables and also for variables that are renamings of other variables
5409 or for which an address clause is given.
5410 This warning can also be turned on using @option{-gnatwa}.
5411 The default is that these warnings are not given.
5412
5413 @item -gnatwM
5414 @emph{Disable warnings on modified but unreferenced variables.}
5415 @cindex @option{-gnatwM} (@command{gcc})
5416 This switch disables warnings for variables that are assigned or
5417 initialized, but never read.
5418
5419 @item -gnatw.m
5420 @emph{Activate warnings on suspicious modulus values.}
5421 @cindex @option{-gnatw.m} (@command{gcc})
5422 This switch activates warnings for modulus values that seem suspicious.
5423 The cases caught are where the size is the same as the modulus (e.g.
5424 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5425 with no size clause. The guess in both cases is that 2**x was intended
5426 rather than x. In addition expressions of the form 2*x for small x
5427 generate a warning (the almost certainly accurate guess being that
5428 2**x was intended). The default is that these warnings are given.
5429
5430 @item -gnatw.M
5431 @emph{Disable warnings on suspicious modulus values.}
5432 @cindex @option{-gnatw.M} (@command{gcc})
5433 This switch disables warnings for suspicious modulus values.
5434
5435 @item -gnatwn
5436 @emph{Set normal warnings mode.}
5437 @cindex @option{-gnatwn} (@command{gcc})
5438 This switch sets normal warning mode, in which enabled warnings are
5439 issued and treated as warnings rather than errors. This is the default
5440 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5441 an explicit @option{-gnatws} or
5442 @option{-gnatwe}. It also cancels the effect of the
5443 implicit @option{-gnatwe} that is activated by the
5444 use of @option{-gnatg}.
5445
5446 @item -gnatw.n
5447 @emph{Activate warnings on atomic synchronization.}
5448 @cindex @option{-gnatw.n} (@command{gcc})
5449 @cindex Atomic Synchronization, warnings
5450 This switch actives warnings when an access to an atomic variable
5451 requires the generation of atomic synchronization code. These
5452 warnings are off by default and this warning is not included
5453 in @code{-gnatwa}.
5454
5455 @item -gnatw.N
5456 @emph{Suppress warnings on atomic synchronization.}
5457 @cindex @option{-gnatw.n} (@command{gcc})
5458 @cindex Atomic Synchronization, warnings
5459 This switch suppresses warnings when an access to an atomic variable
5460 requires the generation of atomic synchronization code.
5461
5462 @item -gnatwo
5463 @emph{Activate warnings on address clause overlays.}
5464 @cindex @option{-gnatwo} (@command{gcc})
5465 @cindex Address Clauses, warnings
5466 This switch activates warnings for possibly unintended initialization
5467 effects of defining address clauses that cause one variable to overlap
5468 another. The default is that such warnings are generated.
5469 This warning can also be turned on using @option{-gnatwa}.
5470
5471 @item -gnatwO
5472 @emph{Suppress warnings on address clause overlays.}
5473 @cindex @option{-gnatwO} (@command{gcc})
5474 This switch suppresses warnings on possibly unintended initialization
5475 effects of defining address clauses that cause one variable to overlap
5476 another.
5477
5478 @item -gnatw.o
5479 @emph{Activate warnings on modified but unreferenced out parameters.}
5480 @cindex @option{-gnatw.o} (@command{gcc})
5481 This switch activates warnings for variables that are modified by using
5482 them as actuals for a call to a procedure with an out mode formal, where
5483 the resulting assigned value is never read. It is applicable in the case
5484 where there is more than one out mode formal. If there is only one out
5485 mode formal, the warning is issued by default (controlled by -gnatwu).
5486 The warning is suppressed for volatile
5487 variables and also for variables that are renamings of other variables
5488 or for which an address clause is given.
5489 The default is that these warnings are not given. Note that this warning
5490 is not included in -gnatwa, it must be activated explicitly.
5491
5492 @item -gnatw.O
5493 @emph{Disable warnings on modified but unreferenced out parameters.}
5494 @cindex @option{-gnatw.O} (@command{gcc})
5495 This switch suppresses warnings for variables that are modified by using
5496 them as actuals for a call to a procedure with an out mode formal, where
5497 the resulting assigned value is never read.
5498
5499 @item -gnatwp
5500 @emph{Activate warnings on ineffective pragma Inlines.}
5501 @cindex @option{-gnatwp} (@command{gcc})
5502 @cindex Inlining, warnings
5503 This switch activates warnings for failure of front end inlining
5504 (activated by @option{-gnatN}) to inline a particular call. There are
5505 many reasons for not being able to inline a call, including most
5506 commonly that the call is too complex to inline. The default is
5507 that such warnings are not given.
5508 This warning can also be turned on using @option{-gnatwa}.
5509 Warnings on ineffective inlining by the gcc back-end can be activated
5510 separately, using the gcc switch -Winline.
5511
5512 @item -gnatwP
5513 @emph{Suppress warnings on ineffective pragma Inlines.}
5514 @cindex @option{-gnatwP} (@command{gcc})
5515 This switch suppresses warnings on ineffective pragma Inlines. If the
5516 inlining mechanism cannot inline a call, it will simply ignore the
5517 request silently.
5518
5519 @item -gnatw.p
5520 @emph{Activate warnings on parameter ordering.}
5521 @cindex @option{-gnatw.p} (@command{gcc})
5522 @cindex Parameter order, warnings
5523 This switch activates warnings for cases of suspicious parameter
5524 ordering when the list of arguments are all simple identifiers that
5525 match the names of the formals, but are in a different order. The
5526 warning is suppressed if any use of named parameter notation is used,
5527 so this is the appropriate way to suppress a false positive (and
5528 serves to emphasize that the "misordering" is deliberate). The
5529 default is
5530 that such warnings are not given.
5531 This warning can also be turned on using @option{-gnatwa}.
5532
5533 @item -gnatw.P
5534 @emph{Suppress warnings on parameter ordering.}
5535 @cindex @option{-gnatw.P} (@command{gcc})
5536 This switch suppresses warnings on cases of suspicious parameter
5537 ordering.
5538
5539 @item -gnatwq
5540 @emph{Activate warnings on questionable missing parentheses.}
5541 @cindex @option{-gnatwq} (@command{gcc})
5542 @cindex Parentheses, warnings
5543 This switch activates warnings for cases where parentheses are not used and
5544 the result is potential ambiguity from a readers point of view. For example
5545 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5546 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5547 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5548 follow the rule of always parenthesizing to make the association clear, and
5549 this warning switch warns if such parentheses are not present. The default
5550 is that these warnings are given.
5551 This warning can also be turned on using @option{-gnatwa}.
5552
5553 @item -gnatwQ
5554 @emph{Suppress warnings on questionable missing parentheses.}
5555 @cindex @option{-gnatwQ} (@command{gcc})
5556 This switch suppresses warnings for cases where the association is not
5557 clear and the use of parentheses is preferred.
5558
5559 @item -gnatwr
5560 @emph{Activate warnings on redundant constructs.}
5561 @cindex @option{-gnatwr} (@command{gcc})
5562 This switch activates warnings for redundant constructs. The following
5563 is the current list of constructs regarded as redundant:
5564
5565 @itemize @bullet
5566 @item
5567 Assignment of an item to itself.
5568 @item
5569 Type conversion that converts an expression to its own type.
5570 @item
5571 Use of the attribute @code{Base} where @code{typ'Base} is the same
5572 as @code{typ}.
5573 @item
5574 Use of pragma @code{Pack} when all components are placed by a record
5575 representation clause.
5576 @item
5577 Exception handler containing only a reraise statement (raise with no
5578 operand) which has no effect.
5579 @item
5580 Use of the operator abs on an operand that is known at compile time
5581 to be non-negative
5582 @item
5583 Comparison of boolean expressions to an explicit True value.
5584 @end itemize
5585
5586 This warning can also be turned on using @option{-gnatwa}.
5587 The default is that warnings for redundant constructs are not given.
5588
5589 @item -gnatwR
5590 @emph{Suppress warnings on redundant constructs.}
5591 @cindex @option{-gnatwR} (@command{gcc})
5592 This switch suppresses warnings for redundant constructs.
5593
5594 @item -gnatw.r
5595 @emph{Activate warnings for object renaming function.}
5596 @cindex @option{-gnatw.r} (@command{gcc})
5597 This switch activates warnings for an object renaming that renames a
5598 function call, which is equivalent to a constant declaration (as
5599 opposed to renaming the function itself). The default is that these
5600 warnings are given. This warning can also be turned on using
5601 @option{-gnatwa}.
5602
5603 @item -gnatw.R
5604 @emph{Suppress warnings for object renaming function.}
5605 @cindex @option{-gnatwT} (@command{gcc})
5606 This switch suppresses warnings for object renaming function.
5607
5608 @item -gnatws
5609 @emph{Suppress all warnings.}
5610 @cindex @option{-gnatws} (@command{gcc})
5611 This switch completely suppresses the
5612 output of all warning messages from the GNAT front end, including
5613 both warnings that can be controlled by switches described in this
5614 section, and those that are normally given unconditionally. The
5615 effect of this suppress action can only be cancelled by a subsequent
5616 use of the switch @option{-gnatwn}.
5617
5618 Note that switch @option{-gnatws} does not suppress
5619 warnings from the @command{gcc} back end.
5620 To suppress these back end warnings as well, use the switch @option{-w}
5621 in addition to @option{-gnatws}. Also this switch has no effect on the
5622 handling of style check messages.
5623
5624 @item -gnatw.s
5625 @emph{Activate warnings on overridden size clauses.}
5626 @cindex @option{-gnatw.s} (@command{gcc})
5627 @cindex Record Representation (component sizes)
5628 This switch activates warnings on component clauses in record
5629 representation clauses where the length given overrides that
5630 specified by an explicit size clause for the component type. A
5631 warning is similarly given in the array case if a specified
5632 component size overrides an explicit size clause for the array
5633 component type.
5634 Note that @option{-gnatwa} does not affect the setting of this warning option.
5635
5636 @item -gnatw.S
5637 @emph{Suppress warnings on overridden size clauses.}
5638 @cindex @option{-gnatw.S} (@command{gcc})
5639 This switch suppresses warnings on component clauses in record
5640 representation clauses that override size clauses, and similar
5641 warnings when an array component size overrides a size clause.
5642
5643 @item -gnatwt
5644 @emph{Activate warnings for tracking of deleted conditional code.}
5645 @cindex @option{-gnatwt} (@command{gcc})
5646 @cindex Deactivated code, warnings
5647 @cindex Deleted code, warnings
5648 This switch activates warnings for tracking of code in conditionals (IF and
5649 CASE statements) that is detected to be dead code which cannot be executed, and
5650 which is removed by the front end. This warning is off by default, and is not
5651 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5652 useful for detecting deactivated code in certified applications.
5653
5654 @item -gnatwT
5655 @emph{Suppress warnings for tracking of deleted conditional code.}
5656 @cindex @option{-gnatwT} (@command{gcc})
5657 This switch suppresses warnings for tracking of deleted conditional code.
5658
5659 @item -gnatw.t
5660 @emph{Activate warnings on suspicious contracts.}
5661 @cindex @option{-gnatw.t} (@command{gcc})
5662 This switch activates warnings on suspicious postconditions (whether a
5663 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012)
5664 and suspicious contract cases (pragma @code{Contract_Cases}). A
5665 function postcondition or contract case is suspicious when no postcondition
5666 or contract case for this function mentions the result of the function.
5667 A procedure postcondition or contract case is suspicious when it only
5668 refers to the pre-state of the procedure, because in that case it should
5669 rather be expressed as a precondition. The default is that such warnings
5670 are not generated. This warning can also be turned on using @option{-gnatwa}.
5671
5672 @item -gnatw.T
5673 @emph{Suppress warnings on suspicious contracts.}
5674 @cindex @option{-gnatw.T} (@command{gcc})
5675 This switch suppresses warnings on suspicious postconditions.
5676
5677 @item -gnatwu
5678 @emph{Activate warnings on unused entities.}
5679 @cindex @option{-gnatwu} (@command{gcc})
5680 This switch activates warnings to be generated for entities that
5681 are declared but not referenced, and for units that are @code{with}'ed
5682 and not
5683 referenced. In the case of packages, a warning is also generated if
5684 no entities in the package are referenced. This means that if a with'ed
5685 package is referenced but the only references are in @code{use}
5686 clauses or @code{renames}
5687 declarations, a warning is still generated. A warning is also generated
5688 for a generic package that is @code{with}'ed but never instantiated.
5689 In the case where a package or subprogram body is compiled, and there
5690 is a @code{with} on the corresponding spec
5691 that is only referenced in the body,
5692 a warning is also generated, noting that the
5693 @code{with} can be moved to the body. The default is that
5694 such warnings are not generated.
5695 This switch also activates warnings on unreferenced formals
5696 (it includes the effect of @option{-gnatwf}).
5697 This warning can also be turned on using @option{-gnatwa}.
5698
5699 @item -gnatwU
5700 @emph{Suppress warnings on unused entities.}
5701 @cindex @option{-gnatwU} (@command{gcc})
5702 This switch suppresses warnings for unused entities and packages.
5703 It also turns off warnings on unreferenced formals (and thus includes
5704 the effect of @option{-gnatwF}).
5705
5706 @item -gnatw.u
5707 @emph{Activate warnings on unordered enumeration types.}
5708 @cindex @option{-gnatw.u} (@command{gcc})
5709 This switch causes enumeration types to be considered as conceptually
5710 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5711 The effect is to generate warnings in clients that use explicit comparisons
5712 or subranges, since these constructs both treat objects of the type as
5713 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5714 which the type is declared, or its body or subunits.) Please refer to
5715 the description of pragma @code{Ordered} in the
5716 @cite{@value{EDITION} Reference Manual} for further details.
5717 The default is that such warnings are not generated.
5718 This warning is not automatically turned on by the use of @option{-gnatwa}.
5719
5720 @item -gnatw.U
5721 @emph{Deactivate warnings on unordered enumeration types.}
5722 @cindex @option{-gnatw.U} (@command{gcc})
5723 This switch causes all enumeration types to be considered as ordered, so
5724 that no warnings are given for comparisons or subranges for any type.
5725
5726 @item -gnatwv
5727 @emph{Activate warnings on unassigned variables.}
5728 @cindex @option{-gnatwv} (@command{gcc})
5729 @cindex Unassigned variable warnings
5730 This switch activates warnings for access to variables which
5731 may not be properly initialized. The default is that
5732 such warnings are generated.
5733 This warning can also be turned on using @option{-gnatwa}.
5734
5735 @item -gnatwV
5736 @emph{Suppress warnings on unassigned variables.}
5737 @cindex @option{-gnatwV} (@command{gcc})
5738 This switch suppresses warnings for access to variables which
5739 may not be properly initialized.
5740 For variables of a composite type, the warning can also be suppressed in
5741 Ada 2005 by using a default initialization with a box. For example, if
5742 Table is an array of records whose components are only partially uninitialized,
5743 then the following code:
5744
5745 @smallexample @c ada
5746 Tab : Table := (others => <>);
5747 @end smallexample
5748
5749 will suppress warnings on subsequent statements that access components
5750 of variable Tab.
5751
5752 @item -gnatw.v
5753 @emph{Activate info messages for non-default bit order.}
5754 @cindex @option{-gnatw.v} (@command{gcc})
5755 @cindex bit order warnings
5756 This switch activates messages (labeled "info", they are not warnings,
5757 just informational messages) about the effects of non-default bit-order
5758 on records to which a component clause is applied. The effect of specifying
5759 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
5760 these messages, which are given by default, are useful in understanding the
5761 exact consequences of using this feature. These messages
5762 can also be turned on using @option{-gnatwa}
5763
5764 @item -gnatw.V
5765 @emph{Suppress info messages for non-default bit order.}
5766 @cindex @option{-gnatw.V} (@command{gcc})
5767 This switch suppresses information messages for the effects of specifying
5768 non-default bit order on record components with component clauses.
5769
5770 @item -gnatww
5771 @emph{Activate warnings on wrong low bound assumption.}
5772 @cindex @option{-gnatww} (@command{gcc})
5773 @cindex String indexing warnings
5774 This switch activates warnings for indexing an unconstrained string parameter
5775 with a literal or S'Length. This is a case where the code is assuming that the
5776 low bound is one, which is in general not true (for example when a slice is
5777 passed). The default is that such warnings are generated.
5778 This warning can also be turned on using @option{-gnatwa}.
5779
5780 @item -gnatwW
5781 @emph{Suppress warnings on wrong low bound assumption.}
5782 @cindex @option{-gnatwW} (@command{gcc})
5783 This switch suppresses warnings for indexing an unconstrained string parameter
5784 with a literal or S'Length. Note that this warning can also be suppressed
5785 in a particular case by adding an
5786 assertion that the lower bound is 1,
5787 as shown in the following example.
5788
5789 @smallexample @c ada
5790 procedure K (S : String) is
5791 pragma Assert (S'First = 1);
5792 @dots{}
5793 @end smallexample
5794
5795 @item -gnatw.w
5796 @emph{Activate warnings on Warnings Off pragmas}
5797 @cindex @option{-gnatw.w} (@command{gcc})
5798 @cindex Warnings Off control
5799 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5800 where either the pragma is entirely useless (because it suppresses no
5801 warnings), or it could be replaced by @code{pragma Unreferenced} or
5802 @code{pragma Unmodified}. The default is that these warnings are not given.
5803 Note that this warning is not included in -gnatwa, it must be
5804 activated explicitly. Also activates warnings for the case of
5805 Warnings (Off, String), where either there is no matching
5806 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
5807
5808 @item -gnatw.W
5809 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5810 @cindex @option{-gnatw.W} (@command{gcc})
5811 This switch suppresses warnings for use of @code{pragma Warnings (Off, ...)}.
5812
5813 @item -gnatwx
5814 @emph{Activate warnings on Export/Import pragmas.}
5815 @cindex @option{-gnatwx} (@command{gcc})
5816 @cindex Export/Import pragma warnings
5817 This switch activates warnings on Export/Import pragmas when
5818 the compiler detects a possible conflict between the Ada and
5819 foreign language calling sequences. For example, the use of
5820 default parameters in a convention C procedure is dubious
5821 because the C compiler cannot supply the proper default, so
5822 a warning is issued. The default is that such warnings are
5823 generated.
5824 This warning can also be turned on using @option{-gnatwa}.
5825
5826 @item -gnatwX
5827 @emph{Suppress warnings on Export/Import pragmas.}
5828 @cindex @option{-gnatwX} (@command{gcc})
5829 This switch suppresses warnings on Export/Import pragmas.
5830 The sense of this is that you are telling the compiler that
5831 you know what you are doing in writing the pragma, and it
5832 should not complain at you.
5833
5834 @item -gnatw.x
5835 @emph{Activate warnings for No_Exception_Propagation mode.}
5836 @cindex @option{-gnatwm} (@command{gcc})
5837 This switch activates warnings for exception usage when pragma Restrictions
5838 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5839 explicit exception raises which are not covered by a local handler, and for
5840 exception handlers which do not cover a local raise. The default is that these
5841 warnings are not given.
5842
5843 @item -gnatw.X
5844 @emph{Disable warnings for No_Exception_Propagation mode.}
5845 This switch disables warnings for exception usage when pragma Restrictions
5846 (No_Exception_Propagation) is in effect.
5847
5848 @item -gnatwy
5849 @emph{Activate warnings for Ada compatibility issues.}
5850 @cindex @option{-gnatwy} (@command{gcc})
5851 @cindex Ada compatibility issues warnings
5852 For the most part, newer versions of Ada are upwards compatible
5853 with older versions. For example, Ada 2005 programs will almost
5854 always work when compiled as Ada 2012.
5855 However there are some exceptions (for example the fact that
5856 @code{some} is now a reserved word in Ada 2012). This
5857 switch activates several warnings to help in identifying
5858 and correcting such incompatibilities. The default is that
5859 these warnings are generated. Note that at one point Ada 2005
5860 was called Ada 0Y, hence the choice of character.
5861 This warning can also be turned on using @option{-gnatwa}.
5862
5863 @item -gnatwY
5864 @emph{Disable warnings for Ada compatibility issues.}
5865 @cindex @option{-gnatwY} (@command{gcc})
5866 @cindex Ada compatibility issues warnings
5867 This switch suppresses the warnings intended to help in identifying
5868 incompatibilities between Ada language versions.
5869
5870 @item -gnatw.y
5871 @emph{Activate information messages for why package spec needs body}
5872 @cindex @option{-gnatw.y} (@command{gcc})
5873 @cindex Package spec needing body
5874 There are a number of cases in which a package spec needs a body.
5875 For example, the use of pragma Elaborate_Body, or the declaration
5876 of a procedure specification requiring a completion. This switch
5877 causes information messages to be output showing why a package
5878 specification requires a body. This can be useful in the case of
5879 a large package specification which is unexpectedly requiring a
5880 body. The default is that such information messages are not output.
5881
5882 @item -gnatw.Y
5883 @emph{Disable information messages for why package spec needs body}
5884 @cindex @option{-gnatw.Y} (@command{gcc})
5885 @cindex No information messages for why package spec needs body
5886 This switch suppresses the output of information messages showing why
5887 a package specification needs a body.
5888
5889 @item -gnatwz
5890 @emph{Activate warnings on unchecked conversions.}
5891 @cindex @option{-gnatwz} (@command{gcc})
5892 @cindex Unchecked_Conversion warnings
5893 This switch activates warnings for unchecked conversions
5894 where the types are known at compile time to have different
5895 sizes. The default
5896 is that such warnings are generated. Warnings are also
5897 generated for subprogram pointers with different conventions,
5898 and, on VMS only, for data pointers with different conventions.
5899 This warning can also be turned on using @option{-gnatwa}.
5900
5901 @item -gnatwZ
5902 @emph{Suppress warnings on unchecked conversions.}
5903 @cindex @option{-gnatwZ} (@command{gcc})
5904 This switch suppresses warnings for unchecked conversions
5905 where the types are known at compile time to have different
5906 sizes or conventions.
5907
5908 @item -gnatw.z
5909 @emph{Activate warnings for size not a multiple of alignment.}
5910 @cindex @option{-gnatw.z} (@command{gcc})
5911 @cindex Size/Alignment warnings
5912 This switch activates warnings for cases of record types with
5913 specified @code{Size} and @code{Alignment} attributes where the
5914 size is not a multiple of the alignment, resulting in an object
5915 size that is greater than the specified size. The default
5916 is that such warnings are generated.
5917 This warning can also be turned on using @option{-gnatwa}.
5918
5919 @item -gnatw.Z
5920 @emph{Suppress warnings for size not a multiple of alignment.}
5921 @cindex @option{-gnatw.Z} (@command{gcc})
5922 @cindex Size/Alignment warnings
5923 This switch suppresses warnings for cases of record types with
5924 specified @code{Size} and @code{Alignment} attributes where the
5925 size is not a multiple of the alignment, resulting in an object
5926 size that is greater than the specified size.
5927 The warning can also be
5928 suppressed by giving an explicit @code{Object_Size} value.
5929
5930 @item ^-Wunused^WARNINGS=UNUSED^
5931 @cindex @option{-Wunused}
5932 The warnings controlled by the @option{-gnatw} switch are generated by
5933 the front end of the compiler. The @option{GCC} back end can provide
5934 additional warnings and they are controlled by the @option{-W} switch.
5935 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5936 warnings for entities that are declared but not referenced.
5937
5938 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5939 @cindex @option{-Wuninitialized}
5940 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5941 the back end warning for uninitialized variables. This switch must be
5942 used in conjunction with an optimization level greater than zero.
5943
5944 @item -Wstack-usage=@var{len}
5945 @cindex @option{-Wstack-usage}
5946 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5947 See @ref{Static Stack Usage Analysis} for details.
5948
5949 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5950 @cindex @option{-Wall}
5951 This switch enables most warnings from the @option{GCC} back end.
5952 The code generator detects a number of warning situations that are missed
5953 by the @option{GNAT} front end, and this switch can be used to activate them.
5954 The use of this switch also sets the default front end warning mode to
5955 @option{-gnatwa}, that is, most front end warnings activated as well.
5956
5957 @item ^-w^/NO_BACK_END_WARNINGS^
5958 @cindex @option{-w}
5959 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5960 The use of this switch also sets the default front end warning mode to
5961 @option{-gnatws}, that is, front end warnings suppressed as well.
5962
5963 @item -Werror
5964 @cindex @option{-Werror}
5965 This switch causes warnings from the @option{GCC} back end to be treated as
5966 errors. The warning string still appears, but the warning messages are
5967 counted as errors, and prevent the generation of an object file.
5968
5969 @end table
5970
5971 @noindent
5972 @ifclear vms
5973 A string of warning parameters can be used in the same parameter. For example:
5974
5975 @smallexample
5976 -gnatwaGe
5977 @end smallexample
5978
5979 @noindent
5980 will turn on all optional warnings except for unrecognized pragma warnings,
5981 and also specify that warnings should be treated as errors.
5982 @end ifclear
5983
5984 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5985
5986 @table @option
5987 @c !sort!
5988 @item -gnatw.a
5989 @item -gnatwB
5990 @item -gnatw.b
5991 @item -gnatwC
5992 @item -gnatw.C
5993 @item -gnatwD
5994 @item -gnatwF
5995 @item -gnatwg
5996 @item -gnatwH
5997 @item -gnatwi
5998 @item -gnatw.I
5999 @item -gnatwJ
6000 @item -gnatwK
6001 @item -gnatwL
6002 @item -gnatw.L
6003 @item -gnatwM
6004 @item -gnatw.m
6005 @item -gnatwn
6006 @item -gnatwo
6007 @item -gnatw.O
6008 @item -gnatwP
6009 @item -gnatw.P
6010 @item -gnatwq
6011 @item -gnatwR
6012 @item -gnatw.R
6013 @item -gnatw.S
6014 @item -gnatwT
6015 @item -gnatw.T
6016 @item -gnatwU
6017 @item -gnatwv
6018 @item -gnatww
6019 @item -gnatw.W
6020 @item -gnatwx
6021 @item -gnatw.X
6022 @item -gnatwy
6023 @item -gnatwz
6024
6025 @end table
6026
6027 @node Debugging and Assertion Control
6028 @subsection Debugging and Assertion Control
6029
6030 @table @option
6031 @item -gnata
6032 @cindex @option{-gnata} (@command{gcc})
6033 @findex Assert
6034 @findex Debug
6035 @cindex Assertions
6036
6037 @noindent
6038 The pragmas @code{Assert} and @code{Debug} normally have no effect and
6039 are ignored. This switch, where @samp{a} stands for assert, causes
6040 @code{Assert} and @code{Debug} pragmas to be activated.
6041
6042 The pragmas have the form:
6043
6044 @smallexample
6045 @cartouche
6046 @b{pragma} Assert (@var{Boolean-expression} @r{[},
6047 @var{static-string-expression}@r{]})
6048 @b{pragma} Debug (@var{procedure call})
6049 @end cartouche
6050 @end smallexample
6051
6052 @noindent
6053 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
6054 If the result is @code{True}, the pragma has no effect (other than
6055 possible side effects from evaluating the expression). If the result is
6056 @code{False}, the exception @code{Assert_Failure} declared in the package
6057 @code{System.Assertions} is
6058 raised (passing @var{static-string-expression}, if present, as the
6059 message associated with the exception). If no string expression is
6060 given the default is a string giving the file name and line number
6061 of the pragma.
6062
6063 The @code{Debug} pragma causes @var{procedure} to be called. Note that
6064 @code{pragma Debug} may appear within a declaration sequence, allowing
6065 debugging procedures to be called between declarations.
6066
6067 @ifset vms
6068 @item /DEBUG@r{[}=debug-level@r{]}
6069 @itemx /NODEBUG
6070 Specifies how much debugging information is to be included in
6071 the resulting object file where 'debug-level' is one of the following:
6072 @table @code
6073 @item TRACEBACK
6074 Include both debugger symbol records and traceback
6075 the object file.
6076 This is the default setting.
6077 @item ALL
6078 Include both debugger symbol records and traceback in
6079 object file.
6080 @item NONE
6081 Excludes both debugger symbol records and traceback
6082 the object file. Same as /NODEBUG.
6083 @item SYMBOLS
6084 Includes only debugger symbol records in the object
6085 file. Note that this doesn't include traceback information.
6086 @end table
6087 @end ifset
6088 @end table
6089
6090 @node Validity Checking
6091 @subsection Validity Checking
6092 @findex Validity Checking
6093
6094 @noindent
6095 The Ada Reference Manual defines the concept of invalid values (see
6096 RM 13.9.1). The primary source of invalid values is uninitialized
6097 variables. A scalar variable that is left uninitialized may contain
6098 an invalid value; the concept of invalid does not apply to access or
6099 composite types.
6100
6101 It is an error to read an invalid value, but the RM does not require
6102 run-time checks to detect such errors, except for some minimal
6103 checking to prevent erroneous execution (i.e. unpredictable
6104 behavior). This corresponds to the @option{-gnatVd} switch below,
6105 which is the default. For example, by default, if the expression of a
6106 case statement is invalid, it will raise Constraint_Error rather than
6107 causing a wild jump, and if an array index on the left-hand side of an
6108 assignment is invalid, it will raise Constraint_Error rather than
6109 overwriting an arbitrary memory location.
6110
6111 The @option{-gnatVa} may be used to enable additional validity checks,
6112 which are not required by the RM. These checks are often very
6113 expensive (which is why the RM does not require them). These checks
6114 are useful in tracking down uninitialized variables, but they are
6115 not usually recommended for production builds, and in particular
6116 we do not recommend using these extra validity checking options in
6117 combination with optimization, since this can confuse the optimizer.
6118 If performance is a consideration, leading to the need to optimize,
6119 then the validity checking options should not be used.
6120
6121 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
6122 control; you can enable whichever validity checks you desire. However,
6123 for most debugging purposes, @option{-gnatVa} is sufficient, and the
6124 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
6125 sufficient for non-debugging use.
6126
6127 The @option{-gnatB} switch tells the compiler to assume that all
6128 values are valid (that is, within their declared subtype range)
6129 except in the context of a use of the Valid attribute. This means
6130 the compiler can generate more efficient code, since the range
6131 of values is better known at compile time. However, an uninitialized
6132 variable can cause wild jumps and memory corruption in this mode.
6133
6134 The @option{-gnatV^@var{x}^^} switch allows control over the validity
6135 checking mode as described below.
6136 @ifclear vms
6137 The @code{x} argument is a string of letters that
6138 indicate validity checks that are performed or not performed in addition
6139 to the default checks required by Ada as described above.
6140 @end ifclear
6141 @ifset vms
6142 The options allowed for this qualifier
6143 indicate validity checks that are performed or not performed in addition
6144 to the default checks required by Ada as described above.
6145 @end ifset
6146
6147 @table @option
6148 @c !sort!
6149 @item -gnatVa
6150 @emph{All validity checks.}
6151 @cindex @option{-gnatVa} (@command{gcc})
6152 All validity checks are turned on.
6153 @ifclear vms
6154 That is, @option{-gnatVa} is
6155 equivalent to @option{gnatVcdfimorst}.
6156 @end ifclear
6157
6158 @item -gnatVc
6159 @emph{Validity checks for copies.}
6160 @cindex @option{-gnatVc} (@command{gcc})
6161 The right hand side of assignments, and the initializing values of
6162 object declarations are validity checked.
6163
6164 @item -gnatVd
6165 @emph{Default (RM) validity checks.}
6166 @cindex @option{-gnatVd} (@command{gcc})
6167 Some validity checks are done by default following normal Ada semantics
6168 (RM 13.9.1 (9-11)).
6169 A check is done in case statements that the expression is within the range
6170 of the subtype. If it is not, Constraint_Error is raised.
6171 For assignments to array components, a check is done that the expression used
6172 as index is within the range. If it is not, Constraint_Error is raised.
6173 Both these validity checks may be turned off using switch @option{-gnatVD}.
6174 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6175 switch @option{-gnatVd} will leave the checks turned on.
6176 Switch @option{-gnatVD} should be used only if you are sure that all such
6177 expressions have valid values. If you use this switch and invalid values
6178 are present, then the program is erroneous, and wild jumps or memory
6179 overwriting may occur.
6180
6181 @item -gnatVe
6182 @emph{Validity checks for elementary components.}
6183 @cindex @option{-gnatVe} (@command{gcc})
6184 In the absence of this switch, assignments to record or array components are
6185 not validity checked, even if validity checks for assignments generally
6186 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6187 require valid data, but assignment of individual components does. So for
6188 example, there is a difference between copying the elements of an array with a
6189 slice assignment, compared to assigning element by element in a loop. This
6190 switch allows you to turn off validity checking for components, even when they
6191 are assigned component by component.
6192
6193 @item -gnatVf
6194 @emph{Validity checks for floating-point values.}
6195 @cindex @option{-gnatVf} (@command{gcc})
6196 In the absence of this switch, validity checking occurs only for discrete
6197 values. If @option{-gnatVf} is specified, then validity checking also applies
6198 for floating-point values, and NaNs and infinities are considered invalid,
6199 as well as out of range values for constrained types. Note that this means
6200 that standard IEEE infinity mode is not allowed. The exact contexts
6201 in which floating-point values are checked depends on the setting of other
6202 options. For example,
6203 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6204 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6205 (the order does not matter) specifies that floating-point parameters of mode
6206 @code{in} should be validity checked.
6207
6208 @item -gnatVi
6209 @emph{Validity checks for @code{in} mode parameters}
6210 @cindex @option{-gnatVi} (@command{gcc})
6211 Arguments for parameters of mode @code{in} are validity checked in function
6212 and procedure calls at the point of call.
6213
6214 @item -gnatVm
6215 @emph{Validity checks for @code{in out} mode parameters.}
6216 @cindex @option{-gnatVm} (@command{gcc})
6217 Arguments for parameters of mode @code{in out} are validity checked in
6218 procedure calls at the point of call. The @code{'m'} here stands for
6219 modify, since this concerns parameters that can be modified by the call.
6220 Note that there is no specific option to test @code{out} parameters,
6221 but any reference within the subprogram will be tested in the usual
6222 manner, and if an invalid value is copied back, any reference to it
6223 will be subject to validity checking.
6224
6225 @item -gnatVn
6226 @emph{No validity checks.}
6227 @cindex @option{-gnatVn} (@command{gcc})
6228 This switch turns off all validity checking, including the default checking
6229 for case statements and left hand side subscripts. Note that the use of
6230 the switch @option{-gnatp} suppresses all run-time checks, including
6231 validity checks, and thus implies @option{-gnatVn}. When this switch
6232 is used, it cancels any other @option{-gnatV} previously issued.
6233
6234 @item -gnatVo
6235 @emph{Validity checks for operator and attribute operands.}
6236 @cindex @option{-gnatVo} (@command{gcc})
6237 Arguments for predefined operators and attributes are validity checked.
6238 This includes all operators in package @code{Standard},
6239 the shift operators defined as intrinsic in package @code{Interfaces}
6240 and operands for attributes such as @code{Pos}. Checks are also made
6241 on individual component values for composite comparisons, and on the
6242 expressions in type conversions and qualified expressions. Checks are
6243 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6244
6245 @item -gnatVp
6246 @emph{Validity checks for parameters.}
6247 @cindex @option{-gnatVp} (@command{gcc})
6248 This controls the treatment of parameters within a subprogram (as opposed
6249 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6250 of parameters on a call. If either of these call options is used, then
6251 normally an assumption is made within a subprogram that the input arguments
6252 have been validity checking at the point of call, and do not need checking
6253 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6254 is not made, and parameters are not assumed to be valid, so their validity
6255 will be checked (or rechecked) within the subprogram.
6256
6257 @item -gnatVr
6258 @emph{Validity checks for function returns.}
6259 @cindex @option{-gnatVr} (@command{gcc})
6260 The expression in @code{return} statements in functions is validity
6261 checked.
6262
6263 @item -gnatVs
6264 @emph{Validity checks for subscripts.}
6265 @cindex @option{-gnatVs} (@command{gcc})
6266 All subscripts expressions are checked for validity, whether they appear
6267 on the right side or left side (in default mode only left side subscripts
6268 are validity checked).
6269
6270 @item -gnatVt
6271 @emph{Validity checks for tests.}
6272 @cindex @option{-gnatVt} (@command{gcc})
6273 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6274 statements are checked, as well as guard expressions in entry calls.
6275
6276 @end table
6277
6278 @noindent
6279 The @option{-gnatV} switch may be followed by
6280 ^a string of letters^a list of options^
6281 to turn on a series of validity checking options.
6282 For example,
6283 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6284 specifies that in addition to the default validity checking, copies and
6285 function return expressions are to be validity checked.
6286 In order to make it easier
6287 to specify the desired combination of effects,
6288 @ifclear vms
6289 the upper case letters @code{CDFIMORST} may
6290 be used to turn off the corresponding lower case option.
6291 @end ifclear
6292 @ifset vms
6293 the prefix @code{NO} on an option turns off the corresponding validity
6294 checking:
6295 @itemize @bullet
6296 @item @code{NOCOPIES}
6297 @item @code{NODEFAULT}
6298 @item @code{NOFLOATS}
6299 @item @code{NOIN_PARAMS}
6300 @item @code{NOMOD_PARAMS}
6301 @item @code{NOOPERANDS}
6302 @item @code{NORETURNS}
6303 @item @code{NOSUBSCRIPTS}
6304 @item @code{NOTESTS}
6305 @end itemize
6306 @end ifset
6307 Thus
6308 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6309 turns on all validity checking options except for
6310 checking of @code{@b{in out}} procedure arguments.
6311
6312 The specification of additional validity checking generates extra code (and
6313 in the case of @option{-gnatVa} the code expansion can be substantial).
6314 However, these additional checks can be very useful in detecting
6315 uninitialized variables, incorrect use of unchecked conversion, and other
6316 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6317 is useful in conjunction with the extra validity checking, since this
6318 ensures that wherever possible uninitialized variables have invalid values.
6319
6320 See also the pragma @code{Validity_Checks} which allows modification of
6321 the validity checking mode at the program source level, and also allows for
6322 temporary disabling of validity checks.
6323
6324 @node Style Checking
6325 @subsection Style Checking
6326 @findex Style checking
6327
6328 @noindent
6329 The @option{-gnaty^x^(option,option,@dots{})^} switch
6330 @cindex @option{-gnaty} (@command{gcc})
6331 causes the compiler to
6332 enforce specified style rules. A limited set of style rules has been used
6333 in writing the GNAT sources themselves. This switch allows user programs
6334 to activate all or some of these checks. If the source program fails a
6335 specified style check, an appropriate message is given, preceded by
6336 the character sequence ``(style)''. This message does not prevent
6337 successful compilation (unless the @option{-gnatwe} switch is used).
6338
6339 Note that this is by no means intended to be a general facility for
6340 checking arbitrary coding standards. It is simply an embedding of the
6341 style rules we have chosen for the GNAT sources. If you are starting
6342 a project which does not have established style standards, you may
6343 find it useful to adopt the entire set of GNAT coding standards, or
6344 some subset of them.
6345 @ifclear FSFEDITION
6346 If you already have an established set of coding
6347 standards, then the selected style checking options may
6348 indeed correspond to choices you have made, but for general checking
6349 of an existing set of coding rules, you should look to the gnatcheck
6350 tool, which is designed for that purpose.
6351 @end ifclear
6352
6353 @ifset vms
6354 @code{(option,option,@dots{})} is a sequence of keywords
6355 @end ifset
6356 @ifclear vms
6357 The string @var{x} is a sequence of letters or digits
6358 @end ifclear
6359 indicating the particular style
6360 checks to be performed. The following checks are defined:
6361
6362 @table @option
6363 @c !sort!
6364 @item 0-9
6365 @emph{Specify indentation level.}
6366 If a digit from 1-9 appears
6367 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6368 then proper indentation is checked, with the digit indicating the
6369 indentation level required. A value of zero turns off this style check.
6370 The general style of required indentation is as specified by
6371 the examples in the Ada Reference Manual. Full line comments must be
6372 aligned with the @code{--} starting on a column that is a multiple of
6373 the alignment level, or they may be aligned the same way as the following
6374 non-blank line (this is useful when full line comments appear in the middle
6375 of a statement, or they may be aligned with the source line on the previous
6376 non-blank line.
6377
6378 @item ^a^ATTRIBUTE^
6379 @emph{Check attribute casing.}
6380 Attribute names, including the case of keywords such as @code{digits}
6381 used as attributes names, must be written in mixed case, that is, the
6382 initial letter and any letter following an underscore must be uppercase.
6383 All other letters must be lowercase.
6384
6385 @item ^A^ARRAY_INDEXES^
6386 @emph{Use of array index numbers in array attributes.}
6387 When using the array attributes First, Last, Range,
6388 or Length, the index number must be omitted for one-dimensional arrays
6389 and is required for multi-dimensional arrays.
6390
6391 @item ^b^BLANKS^
6392 @emph{Blanks not allowed at statement end.}
6393 Trailing blanks are not allowed at the end of statements. The purpose of this
6394 rule, together with h (no horizontal tabs), is to enforce a canonical format
6395 for the use of blanks to separate source tokens.
6396
6397 @item ^B^BOOLEAN_OPERATORS^
6398 @emph{Check Boolean operators.}
6399 The use of AND/OR operators is not permitted except in the cases of modular
6400 operands, array operands, and simple stand-alone boolean variables or
6401 boolean constants. In all other cases @code{and then}/@code{or else} are
6402 required.
6403
6404 @item ^c^COMMENTS^
6405 @emph{Check comments, double space.}
6406 Comments must meet the following set of rules:
6407
6408 @itemize @bullet
6409
6410 @item
6411 The ``@code{--}'' that starts the column must either start in column one,
6412 or else at least one blank must precede this sequence.
6413
6414 @item
6415 Comments that follow other tokens on a line must have at least one blank
6416 following the ``@code{--}'' at the start of the comment.
6417
6418 @item
6419 Full line comments must have at least two blanks following the
6420 ``@code{--}'' that starts the comment, with the following exceptions.
6421
6422 @item
6423 A line consisting only of the ``@code{--}'' characters, possibly preceded
6424 by blanks is permitted.
6425
6426 @item
6427 A comment starting with ``@code{--x}'' where @code{x} is a special character
6428 is permitted.
6429 This allows proper processing of the output generated by specialized tools
6430 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6431 annotation
6432 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6433 special character is defined as being in one of the ASCII ranges
6434 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6435 Note that this usage is not permitted
6436 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6437
6438 @item
6439 A line consisting entirely of minus signs, possibly preceded by blanks, is
6440 permitted. This allows the construction of box comments where lines of minus
6441 signs are used to form the top and bottom of the box.
6442
6443 @item
6444 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6445 least one blank follows the initial ``@code{--}''. Together with the preceding
6446 rule, this allows the construction of box comments, as shown in the following
6447 example:
6448 @smallexample
6449 ---------------------------
6450 -- This is a box comment --
6451 -- with two text lines. --
6452 ---------------------------
6453 @end smallexample
6454 @end itemize
6455
6456 @item ^C^COMMENTS1^
6457 @emph{Check comments, single space.}
6458 This is identical to @code{^c^COMMENTS^} except that only one space
6459 is required following the @code{--} of a comment instead of two.
6460
6461 @item ^d^DOS_LINE_ENDINGS^
6462 @emph{Check no DOS line terminators present.}
6463 All lines must be terminated by a single ASCII.LF
6464 character (in particular the DOS line terminator sequence CR/LF is not
6465 allowed).
6466
6467 @item ^e^END^
6468 @emph{Check end/exit labels.}
6469 Optional labels on @code{end} statements ending subprograms and on
6470 @code{exit} statements exiting named loops, are required to be present.
6471
6472 @item ^f^VTABS^
6473 @emph{No form feeds or vertical tabs.}
6474 Neither form feeds nor vertical tab characters are permitted
6475 in the source text.
6476
6477 @item ^g^GNAT^
6478 @emph{GNAT style mode.}
6479 The set of style check switches is set to match that used by the GNAT sources.
6480 This may be useful when developing code that is eventually intended to be
6481 incorporated into GNAT. Currently this is equivalent to @option{-gnatwydISux})
6482 but additional style switches may be added to this set in the future without
6483 advance notice.
6484
6485 @item ^h^HTABS^
6486 @emph{No horizontal tabs.}
6487 Horizontal tab characters are not permitted in the source text.
6488 Together with the b (no blanks at end of line) check, this
6489 enforces a canonical form for the use of blanks to separate
6490 source tokens.
6491
6492 @item ^i^IF_THEN^
6493 @emph{Check if-then layout.}
6494 The keyword @code{then} must appear either on the same
6495 line as corresponding @code{if}, or on a line on its own, lined
6496 up under the @code{if}.
6497
6498 @item ^I^IN_MODE^
6499 @emph{check mode IN keywords.}
6500 Mode @code{in} (the default mode) is not
6501 allowed to be given explicitly. @code{in out} is fine,
6502 but not @code{in} on its own.
6503
6504 @item ^k^KEYWORD^
6505 @emph{Check keyword casing.}
6506 All keywords must be in lower case (with the exception of keywords
6507 such as @code{digits} used as attribute names to which this check
6508 does not apply).
6509
6510 @item ^l^LAYOUT^
6511 @emph{Check layout.}
6512 Layout of statement and declaration constructs must follow the
6513 recommendations in the Ada Reference Manual, as indicated by the
6514 form of the syntax rules. For example an @code{else} keyword must
6515 be lined up with the corresponding @code{if} keyword.
6516
6517 There are two respects in which the style rule enforced by this check
6518 option are more liberal than those in the Ada Reference Manual. First
6519 in the case of record declarations, it is permissible to put the
6520 @code{record} keyword on the same line as the @code{type} keyword, and
6521 then the @code{end} in @code{end record} must line up under @code{type}.
6522 This is also permitted when the type declaration is split on two lines.
6523 For example, any of the following three layouts is acceptable:
6524
6525 @smallexample @c ada
6526 @cartouche
6527 type q is record
6528 a : integer;
6529 b : integer;
6530 end record;
6531
6532 type q is
6533 record
6534 a : integer;
6535 b : integer;
6536 end record;
6537
6538 type q is
6539 record
6540 a : integer;
6541 b : integer;
6542 end record;
6543
6544 @end cartouche
6545 @end smallexample
6546
6547 @noindent
6548 Second, in the case of a block statement, a permitted alternative
6549 is to put the block label on the same line as the @code{declare} or
6550 @code{begin} keyword, and then line the @code{end} keyword up under
6551 the block label. For example both the following are permitted:
6552
6553 @smallexample @c ada
6554 @cartouche
6555 Block : declare
6556 A : Integer := 3;
6557 begin
6558 Proc (A, A);
6559 end Block;
6560
6561 Block :
6562 declare
6563 A : Integer := 3;
6564 begin
6565 Proc (A, A);
6566 end Block;
6567 @end cartouche
6568 @end smallexample
6569
6570 @noindent
6571 The same alternative format is allowed for loops. For example, both of
6572 the following are permitted:
6573
6574 @smallexample @c ada
6575 @cartouche
6576 Clear : while J < 10 loop
6577 A (J) := 0;
6578 end loop Clear;
6579
6580 Clear :
6581 while J < 10 loop
6582 A (J) := 0;
6583 end loop Clear;
6584 @end cartouche
6585 @end smallexample
6586
6587 @item ^Lnnn^MAX_NESTING=nnn^
6588 @emph{Set maximum nesting level.}
6589 The maximum level of nesting of constructs (including subprograms, loops,
6590 blocks, packages, and conditionals) may not exceed the given value
6591 @option{nnn}. A value of zero disconnects this style check.
6592
6593 @item ^m^LINE_LENGTH^
6594 @emph{Check maximum line length.}
6595 The length of source lines must not exceed 79 characters, including
6596 any trailing blanks. The value of 79 allows convenient display on an
6597 80 character wide device or window, allowing for possible special
6598 treatment of 80 character lines. Note that this count is of
6599 characters in the source text. This means that a tab character counts
6600 as one character in this count and a wide character sequence counts as
6601 a single character (however many bytes are needed in the encoding).
6602
6603 @item ^Mnnn^MAX_LENGTH=nnn^
6604 @emph{Set maximum line length.}
6605 The length of lines must not exceed the
6606 given value @option{nnn}. The maximum value that can be specified is 32767.
6607 If neither style option for setting the line length is used, then the
6608 default is 255. This also controls the maximum length of lexical elements,
6609 where the only restriction is that they must fit on a single line.
6610
6611 @item ^n^STANDARD_CASING^
6612 @emph{Check casing of entities in Standard.}
6613 Any identifier from Standard must be cased
6614 to match the presentation in the Ada Reference Manual (for example,
6615 @code{Integer} and @code{ASCII.NUL}).
6616
6617 @item ^N^NONE^
6618 @emph{Turn off all style checks.}
6619 All style check options are turned off.
6620
6621 @item ^o^ORDERED_SUBPROGRAMS^
6622 @emph{Check order of subprogram bodies.}
6623 All subprogram bodies in a given scope
6624 (e.g.@: a package body) must be in alphabetical order. The ordering
6625 rule uses normal Ada rules for comparing strings, ignoring casing
6626 of letters, except that if there is a trailing numeric suffix, then
6627 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6628 before Junk10).
6629
6630 @item ^O^OVERRIDING_INDICATORS^
6631 @emph{Check that overriding subprograms are explicitly marked as such.}
6632 The declaration of a primitive operation of a type extension that overrides
6633 an inherited operation must carry an overriding indicator.
6634
6635 @item ^p^PRAGMA^
6636 @emph{Check pragma casing.}
6637 Pragma names must be written in mixed case, that is, the
6638 initial letter and any letter following an underscore must be uppercase.
6639 All other letters must be lowercase. An exception is that SPARK_Mode is
6640 allowed as an alternative for Spark_Mode.
6641
6642 @item ^r^REFERENCES^
6643 @emph{Check references.}
6644 All identifier references must be cased in the same way as the
6645 corresponding declaration. No specific casing style is imposed on
6646 identifiers. The only requirement is for consistency of references
6647 with declarations.
6648
6649 @item ^s^SPECS^
6650 @emph{Check separate specs.}
6651 Separate declarations (``specs'') are required for subprograms (a
6652 body is not allowed to serve as its own declaration). The only
6653 exception is that parameterless library level procedures are
6654 not required to have a separate declaration. This exception covers
6655 the most frequent form of main program procedures.
6656
6657 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6658 @emph{Check no statements after @code{then}/@code{else}.}
6659 No statements are allowed
6660 on the same line as a @code{then} or @code{else} keyword following the
6661 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6662 affected, and a special exception allows a pragma to appear after @code{else}.
6663
6664 @item ^t^TOKEN^
6665 @emph{Check token spacing.}
6666 The following token spacing rules are enforced:
6667
6668 @itemize @bullet
6669
6670 @item
6671 The keywords @code{abs} and @code{not} must be followed by a space.
6672
6673 @item
6674 The token @code{=>} must be surrounded by spaces.
6675
6676 @item
6677 The token @code{<>} must be preceded by a space or a left parenthesis.
6678
6679 @item
6680 Binary operators other than @code{**} must be surrounded by spaces.
6681 There is no restriction on the layout of the @code{**} binary operator.
6682
6683 @item
6684 Colon must be surrounded by spaces.
6685
6686 @item
6687 Colon-equal (assignment, initialization) must be surrounded by spaces.
6688
6689 @item
6690 Comma must be the first non-blank character on the line, or be
6691 immediately preceded by a non-blank character, and must be followed
6692 by a space.
6693
6694 @item
6695 If the token preceding a left parenthesis ends with a letter or digit, then
6696 a space must separate the two tokens.
6697
6698 @item
6699 if the token following a right parenthesis starts with a letter or digit, then
6700 a space must separate the two tokens.
6701
6702 @item
6703 A right parenthesis must either be the first non-blank character on
6704 a line, or it must be preceded by a non-blank character.
6705
6706 @item
6707 A semicolon must not be preceded by a space, and must not be followed by
6708 a non-blank character.
6709
6710 @item
6711 A unary plus or minus may not be followed by a space.
6712
6713 @item
6714 A vertical bar must be surrounded by spaces.
6715 @end itemize
6716
6717 @item
6718 Exactly one blank (and no other white space) must appear between
6719 a @code{not} token and a following @code{in} token.
6720
6721 @item ^u^UNNECESSARY_BLANK_LINES^
6722 @emph{Check unnecessary blank lines.}
6723 Unnecessary blank lines are not allowed. A blank line is considered
6724 unnecessary if it appears at the end of the file, or if more than
6725 one blank line occurs in sequence.
6726
6727 @item ^x^XTRA_PARENS^
6728 @emph{Check extra parentheses.}
6729 Unnecessary extra level of parentheses (C-style) are not allowed
6730 around conditions in @code{if} statements, @code{while} statements and
6731 @code{exit} statements.
6732
6733 @item ^y^ALL_BUILTIN^
6734 @emph{Set all standard style check options}
6735 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6736 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6737 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6738 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6739
6740 @ifclear vms
6741 @item -
6742 @emph{Remove style check options}
6743 This causes any subsequent options in the string to act as canceling the
6744 corresponding style check option. To cancel maximum nesting level control,
6745 use @option{L} parameter witout any integer value after that, because any
6746 digit following @option{-} in the parameter string of the @option{-gnaty}
6747 option will be threated as canceling indentation check. The same is true
6748 for @option{M} parameter. @option{y} and @option{N} parameters are not
6749 allowed after @option{-}.
6750
6751 @item +
6752 This causes any subsequent options in the string to enable the corresponding
6753 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6754 if any.
6755 @end ifclear
6756
6757 @ifset vms
6758 @item NOxxx
6759 @emph{Removing style check options}
6760 If the name of a style check is preceded by @option{NO} then the corresponding
6761 style check is turned off. For example @option{NOCOMMENTS} turns off style
6762 checking for comments.
6763 @end ifset
6764 @end table
6765
6766 @noindent
6767 In the above rules, appearing in column one is always permitted, that is,
6768 counts as meeting either a requirement for a required preceding space,
6769 or as meeting a requirement for no preceding space.
6770
6771 Appearing at the end of a line is also always permitted, that is, counts
6772 as meeting either a requirement for a following space, or as meeting
6773 a requirement for no following space.
6774
6775 @noindent
6776 If any of these style rules is violated, a message is generated giving
6777 details on the violation. The initial characters of such messages are
6778 always ``@code{(style)}''. Note that these messages are treated as warning
6779 messages, so they normally do not prevent the generation of an object
6780 file. The @option{-gnatwe} switch can be used to treat warning messages,
6781 including style messages, as fatal errors.
6782
6783 The switch
6784 @ifclear vms
6785 @option{-gnaty} on its own (that is not
6786 followed by any letters or digits) is equivalent
6787 to the use of @option{-gnatyy} as described above, that is all
6788 built-in standard style check options are enabled.
6789
6790 @end ifclear
6791 @ifset vms
6792 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6793 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6794 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6795 @end ifset
6796
6797 The switch
6798 @ifclear vms
6799 @option{-gnatyN}
6800 @end ifclear
6801 @ifset vms
6802 /STYLE_CHECKS=NONE
6803 @end ifset
6804 clears any previously set style checks.
6805
6806 @node Run-Time Checks
6807 @subsection Run-Time Checks
6808 @cindex Division by zero
6809 @cindex Access before elaboration
6810 @cindex Checks, division by zero
6811 @cindex Checks, access before elaboration
6812 @cindex Checks, stack overflow checking
6813
6814 @noindent
6815 By default, the following checks are suppressed: integer overflow
6816 checks, stack overflow checks, and checks for access before
6817 elaboration on subprogram calls. All other checks, including range
6818 checks and array bounds checks, are turned on by default. The
6819 following @command{gcc} switches refine this default behavior.
6820
6821 @table @option
6822 @c !sort!
6823 @item -gnatp
6824 @cindex @option{-gnatp} (@command{gcc})
6825 @cindex Suppressing checks
6826 @cindex Checks, suppressing
6827 @findex Suppress
6828 This switch causes the unit to be compiled
6829 as though @code{pragma Suppress (All_checks)}
6830 had been present in the source. Validity checks are also eliminated (in
6831 other words @option{-gnatp} also implies @option{-gnatVn}.
6832 Use this switch to improve the performance
6833 of the code at the expense of safety in the presence of invalid data or
6834 program bugs.
6835
6836 Note that when checks are suppressed, the compiler is allowed, but not
6837 required, to omit the checking code. If the run-time cost of the
6838 checking code is zero or near-zero, the compiler will generate it even
6839 if checks are suppressed. In particular, if the compiler can prove
6840 that a certain check will necessarily fail, it will generate code to
6841 do an unconditional ``raise'', even if checks are suppressed. The
6842 compiler warns in this case. Another case in which checks may not be
6843 eliminated is when they are embedded in certain run time routines such
6844 as math library routines.
6845
6846 Of course, run-time checks are omitted whenever the compiler can prove
6847 that they will not fail, whether or not checks are suppressed.
6848
6849 Note that if you suppress a check that would have failed, program
6850 execution is erroneous, which means the behavior is totally
6851 unpredictable. The program might crash, or print wrong answers, or
6852 do anything else. It might even do exactly what you wanted it to do
6853 (and then it might start failing mysteriously next week or next
6854 year). The compiler will generate code based on the assumption that
6855 the condition being checked is true, which can result in erroneous
6856 execution if that assumption is wrong.
6857
6858 The checks subject to suppression include all the checks defined by
6859 the Ada standard, the additional implementation defined checks
6860 @code{Alignment_Check},
6861 @code{Duplicated_Tag_Check}, @code{Predicate_Check}, and
6862 @code{Validity_Check}, as well as any checks introduced using
6863 @code{pragma Check_Name}. Note that @code{Atomic_Synchronization}
6864 is not automatically suppressed by use of this option.
6865
6866 If the code depends on certain checks being active, you can use
6867 pragma @code{Unsuppress} either as a configuration pragma or as
6868 a local pragma to make sure that a specified check is performed
6869 even if @option{gnatp} is specified.
6870
6871 The @option{-gnatp} switch has no effect if a subsequent
6872 @option{-gnat-p} switch appears.
6873
6874 @item -gnat-p
6875 @cindex @option{-gnat-p} (@command{gcc})
6876 @cindex Suppressing checks
6877 @cindex Checks, suppressing
6878 @findex Suppress
6879 This switch cancels the effect of a previous @option{gnatp} switch.
6880
6881 @item -gnato??
6882 @cindex @option{-gnato??} (@command{gcc})
6883 @cindex Overflow checks
6884 @cindex Overflow mode
6885 @cindex Check, overflow
6886 This switch controls the mode used for computing intermediate
6887 arithmetic integer operations, and also enables overflow checking.
6888 For a full description of overflow mode and checking control, see
6889 the ``Overflow Check Handling in GNAT'' appendix in this
6890 User's Guide.
6891
6892 Overflow checks are always enabled by this switch. The argument
6893 controls the mode, using the codes
6894
6895 @itemize
6896 @item 1 = STRICT
6897 In STRICT mode, intermediate operations are always done using the
6898 base type, and overflow checking ensures that the result is within
6899 the base type range.
6900
6901 @item 2 = MINIMIZED
6902 In MINIMIZED mode, overflows in intermediate operations are avoided
6903 where possible by using a larger integer type for the computation
6904 (typically @code{Long_Long_Integer}). Overflow checking ensures that
6905 the result fits in this larger integer type.
6906
6907 @item 3 = ELIMINATED
6908 In ELIMINATED mode, overflows in intermediate operations are avoided
6909 by using multi-precision arithmetic. In this case, overflow checking
6910 has no effect on intermediate operations (since overflow is impossible).
6911 @end itemize
6912
6913 If two digits are present after @option{-gnato} then the first digit
6914 sets the mode for expressions outside assertions, and the second digit
6915 sets the mode for expressions within assertions. Here assertions is used
6916 in the technical sense (which includes for example precondition and
6917 postcondition expressions).
6918
6919 If one digit is present, the corresponding mode is applicable to both
6920 expressions within and outside assertion expressions.
6921
6922 If no digits are present, the default is to enable overflow checks
6923 and set STRICT mode for both kinds of expressions. This is compatible
6924 with the use of @option{-gnato} in previous versions of GNAT.
6925
6926 @findex Machine_Overflows
6927 Note that the @option{-gnato??} switch does not affect the code generated
6928 for any floating-point operations; it applies only to integer semantics.
6929 For floating-point, @value{EDITION} has the @code{Machine_Overflows}
6930 attribute set to @code{False} and the normal mode of operation is to
6931 generate IEEE NaN and infinite values on overflow or invalid operations
6932 (such as dividing 0.0 by 0.0).
6933
6934 The reason that we distinguish overflow checking from other kinds of
6935 range constraint checking is that a failure of an overflow check, unlike
6936 for example the failure of a range check, can result in an incorrect
6937 value, but cannot cause random memory destruction (like an out of range
6938 subscript), or a wild jump (from an out of range case value). Overflow
6939 checking is also quite expensive in time and space, since in general it
6940 requires the use of double length arithmetic.
6941
6942 Note again that the default is @option{^-gnato00^/OVERFLOW_CHECKS=00^},
6943 so overflow checking is not performed in default mode. This means that out of
6944 the box, with the default settings, @value{EDITION} does not do all the checks
6945 expected from the language description in the Ada Reference Manual.
6946 If you want all constraint checks to be performed, as described in this Manual,
6947 then you must explicitly use the @option{-gnato??}
6948 switch either on the @command{gnatmake} or @command{gcc} command.
6949
6950 @item -gnatE
6951 @cindex @option{-gnatE} (@command{gcc})
6952 @cindex Elaboration checks
6953 @cindex Check, elaboration
6954 Enables dynamic checks for access-before-elaboration
6955 on subprogram calls and generic instantiations.
6956 Note that @option{-gnatE} is not necessary for safety, because in the
6957 default mode, GNAT ensures statically that the checks would not fail.
6958 For full details of the effect and use of this switch,
6959 @xref{Compiling with gcc}.
6960
6961 @item -fstack-check
6962 @cindex @option{-fstack-check} (@command{gcc})
6963 @cindex Stack Overflow Checking
6964 @cindex Checks, stack overflow checking
6965 Activates stack overflow checking. For full details of the effect and use of
6966 this switch see @ref{Stack Overflow Checking}.
6967 @end table
6968
6969 @findex Unsuppress
6970 @noindent
6971 The setting of these switches only controls the default setting of the
6972 checks. You may modify them using either @code{Suppress} (to remove
6973 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6974 the program source.
6975
6976 @node Using gcc for Syntax Checking
6977 @subsection Using @command{gcc} for Syntax Checking
6978 @table @option
6979 @item -gnats
6980 @cindex @option{-gnats} (@command{gcc})
6981 @ifclear vms
6982
6983 @noindent
6984 The @code{s} stands for ``syntax''.
6985 @end ifclear
6986
6987 Run GNAT in syntax checking only mode. For
6988 example, the command
6989
6990 @smallexample
6991 $ gcc -c -gnats x.adb
6992 @end smallexample
6993
6994 @noindent
6995 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6996 series of files in a single command
6997 @ifclear vms
6998 , and can use wild cards to specify such a group of files.
6999 Note that you must specify the @option{-c} (compile
7000 only) flag in addition to the @option{-gnats} flag.
7001 @end ifclear
7002 .
7003 You may use other switches in conjunction with @option{-gnats}. In
7004 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
7005 format of any generated error messages.
7006
7007 When the source file is empty or contains only empty lines and/or comments,
7008 the output is a warning:
7009
7010 @smallexample
7011 $ gcc -c -gnats -x ada toto.txt
7012 toto.txt:1:01: warning: empty file, contains no compilation units
7013 $
7014 @end smallexample
7015
7016 Otherwise, the output is simply the error messages, if any. No object file or
7017 ALI file is generated by a syntax-only compilation. Also, no units other
7018 than the one specified are accessed. For example, if a unit @code{X}
7019 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
7020 check only mode does not access the source file containing unit
7021 @code{Y}.
7022
7023 @cindex Multiple units, syntax checking
7024 Normally, GNAT allows only a single unit in a source file. However, this
7025 restriction does not apply in syntax-check-only mode, and it is possible
7026 to check a file containing multiple compilation units concatenated
7027 together. This is primarily used by the @code{gnatchop} utility
7028 (@pxref{Renaming Files with gnatchop}).
7029 @end table
7030
7031 @node Using gcc for Semantic Checking
7032 @subsection Using @command{gcc} for Semantic Checking
7033 @table @option
7034 @item -gnatc
7035 @cindex @option{-gnatc} (@command{gcc})
7036
7037 @ifclear vms
7038 @noindent
7039 The @code{c} stands for ``check''.
7040 @end ifclear
7041 Causes the compiler to operate in semantic check mode,
7042 with full checking for all illegalities specified in the
7043 Ada Reference Manual, but without generation of any object code
7044 (no object file is generated).
7045
7046 Because dependent files must be accessed, you must follow the GNAT
7047 semantic restrictions on file structuring to operate in this mode:
7048
7049 @itemize @bullet
7050 @item
7051 The needed source files must be accessible
7052 (@pxref{Search Paths and the Run-Time Library (RTL)}).
7053
7054 @item
7055 Each file must contain only one compilation unit.
7056
7057 @item
7058 The file name and unit name must match (@pxref{File Naming Rules}).
7059 @end itemize
7060
7061 The output consists of error messages as appropriate. No object file is
7062 generated. An @file{ALI} file is generated for use in the context of
7063 cross-reference tools, but this file is marked as not being suitable
7064 for binding (since no object file is generated).
7065 The checking corresponds exactly to the notion of
7066 legality in the Ada Reference Manual.
7067
7068 Any unit can be compiled in semantics-checking-only mode, including
7069 units that would not normally be compiled (subunits,
7070 and specifications where a separate body is present).
7071 @end table
7072
7073 @node Compiling Different Versions of Ada
7074 @subsection Compiling Different Versions of Ada
7075
7076 @noindent
7077 The switches described in this section allow you to explicitly specify
7078 the version of the Ada language that your programs are written in.
7079 The default mode is Ada 2012,
7080 but you can also specify Ada 95, Ada 2005 mode, or
7081 indicate Ada 83 compatibility mode.
7082
7083 @table @option
7084 @cindex Compatibility with Ada 83
7085
7086 @item -gnat83 (Ada 83 Compatibility Mode)
7087 @cindex @option{-gnat83} (@command{gcc})
7088 @cindex ACVC, Ada 83 tests
7089 @cindex Ada 83 mode
7090
7091 @noindent
7092 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
7093 specifies that the program is to be compiled in Ada 83 mode. With
7094 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
7095 semantics where this can be done easily.
7096 It is not possible to guarantee this switch does a perfect
7097 job; some subtle tests, such as are
7098 found in earlier ACVC tests (and that have been removed from the ACATS suite
7099 for Ada 95), might not compile correctly.
7100 Nevertheless, this switch may be useful in some circumstances, for example
7101 where, due to contractual reasons, existing code needs to be maintained
7102 using only Ada 83 features.
7103
7104 With few exceptions (most notably the need to use @code{<>} on
7105 @cindex Generic formal parameters
7106 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
7107 reserved words, and the use of packages
7108 with optional bodies), it is not necessary to specify the
7109 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
7110 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
7111 a correct Ada 83 program is usually also a correct program
7112 in these later versions of the language standard.
7113 For further information, please refer to @ref{Compatibility and Porting Guide}.
7114
7115 @item -gnat95 (Ada 95 mode)
7116 @cindex @option{-gnat95} (@command{gcc})
7117 @cindex Ada 95 mode
7118
7119 @noindent
7120 This switch directs the compiler to implement the Ada 95 version of the
7121 language.
7122 Since Ada 95 is almost completely upwards
7123 compatible with Ada 83, Ada 83 programs may generally be compiled using
7124 this switch (see the description of the @option{-gnat83} switch for further
7125 information about Ada 83 mode).
7126 If an Ada 2005 program is compiled in Ada 95 mode,
7127 uses of the new Ada 2005 features will cause error
7128 messages or warnings.
7129
7130 This switch also can be used to cancel the effect of a previous
7131 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
7132 switch earlier in the command line.
7133
7134 @item -gnat05 or -gnat2005 (Ada 2005 mode)
7135 @cindex @option{-gnat05} (@command{gcc})
7136 @cindex @option{-gnat2005} (@command{gcc})
7137 @cindex Ada 2005 mode
7138
7139 @noindent
7140 This switch directs the compiler to implement the Ada 2005 version of the
7141 language, as documented in the official Ada standards document.
7142 Since Ada 2005 is almost completely upwards
7143 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
7144 may generally be compiled using this switch (see the description of the
7145 @option{-gnat83} and @option{-gnat95} switches for further
7146 information).
7147
7148 @item -gnat12 or -gnat2012 (Ada 2012 mode)
7149 @cindex @option{-gnat12} (@command{gcc})
7150 @cindex @option{-gnat2012} (@command{gcc})
7151 @cindex Ada 2012 mode
7152
7153 @noindent
7154 This switch directs the compiler to implement the Ada 2012 version of the
7155 language (also the default).
7156 Since Ada 2012 is almost completely upwards
7157 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
7158 Ada 83 and Ada 95 programs
7159 may generally be compiled using this switch (see the description of the
7160 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
7161 for further information).
7162
7163 @item -gnatX (Enable GNAT Extensions)
7164 @cindex @option{-gnatX} (@command{gcc})
7165 @cindex Ada language extensions
7166 @cindex GNAT extensions
7167
7168 @noindent
7169 This switch directs the compiler to implement the latest version of the
7170 language (currently Ada 2012) and also to enable certain GNAT implementation
7171 extensions that are not part of any Ada standard. For a full list of these
7172 extensions, see the GNAT reference manual.
7173
7174 @end table
7175
7176 @node Character Set Control
7177 @subsection Character Set Control
7178 @table @option
7179 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7180 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7181
7182 @noindent
7183 Normally GNAT recognizes the Latin-1 character set in source program
7184 identifiers, as described in the Ada Reference Manual.
7185 This switch causes
7186 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7187 single character ^^or word^ indicating the character set, as follows:
7188
7189 @table @code
7190 @item 1
7191 ISO 8859-1 (Latin-1) identifiers
7192
7193 @item 2
7194 ISO 8859-2 (Latin-2) letters allowed in identifiers
7195
7196 @item 3
7197 ISO 8859-3 (Latin-3) letters allowed in identifiers
7198
7199 @item 4
7200 ISO 8859-4 (Latin-4) letters allowed in identifiers
7201
7202 @item 5
7203 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7204
7205 @item 9
7206 ISO 8859-15 (Latin-9) letters allowed in identifiers
7207
7208 @item ^p^PC^
7209 IBM PC letters (code page 437) allowed in identifiers
7210
7211 @item ^8^PC850^
7212 IBM PC letters (code page 850) allowed in identifiers
7213
7214 @item ^f^FULL_UPPER^
7215 Full upper-half codes allowed in identifiers
7216
7217 @item ^n^NO_UPPER^
7218 No upper-half codes allowed in identifiers
7219
7220 @item ^w^WIDE^
7221 Wide-character codes (that is, codes greater than 255)
7222 allowed in identifiers
7223 @end table
7224
7225 @xref{Foreign Language Representation}, for full details on the
7226 implementation of these character sets.
7227
7228 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7229 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7230 Specify the method of encoding for wide characters.
7231 @var{e} is one of the following:
7232
7233 @table @code
7234
7235 @item ^h^HEX^
7236 Hex encoding (brackets coding also recognized)
7237
7238 @item ^u^UPPER^
7239 Upper half encoding (brackets encoding also recognized)
7240
7241 @item ^s^SHIFT_JIS^
7242 Shift/JIS encoding (brackets encoding also recognized)
7243
7244 @item ^e^EUC^
7245 EUC encoding (brackets encoding also recognized)
7246
7247 @item ^8^UTF8^
7248 UTF-8 encoding (brackets encoding also recognized)
7249
7250 @item ^b^BRACKETS^
7251 Brackets encoding only (default value)
7252 @end table
7253 For full details on these encoding
7254 methods see @ref{Wide Character Encodings}.
7255 Note that brackets coding is always accepted, even if one of the other
7256 options is specified, so for example @option{-gnatW8} specifies that both
7257 brackets and UTF-8 encodings will be recognized. The units that are
7258 with'ed directly or indirectly will be scanned using the specified
7259 representation scheme, and so if one of the non-brackets scheme is
7260 used, it must be used consistently throughout the program. However,
7261 since brackets encoding is always recognized, it may be conveniently
7262 used in standard libraries, allowing these libraries to be used with
7263 any of the available coding schemes.
7264
7265 Note that brackets encoding only applies to program text. Within comments,
7266 brackets are considered to be normal graphic characters, and bracket sequences
7267 are never recognized as wide characters.
7268
7269 If no @option{-gnatW?} parameter is present, then the default
7270 representation is normally Brackets encoding only. However, if the
7271 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7272 byte order mark or BOM for UTF-8), then these three characters are
7273 skipped and the default representation for the file is set to UTF-8.
7274
7275 Note that the wide character representation that is specified (explicitly
7276 or by default) for the main program also acts as the default encoding used
7277 for Wide_Text_IO files if not specifically overridden by a WCEM form
7278 parameter.
7279
7280 @end table
7281
7282 When no @option{-gnatW?} is specified, then characters (other than wide
7283 characters represented using brackets notation) are treated as 8-bit
7284 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
7285 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
7286 characters in the range 16#00#..16#1F# are not accepted in program text
7287 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
7288 in program text, but allowed and ignored in comments. Note in particular
7289 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
7290 as an end of line in this default mode. If your source program contains
7291 instances of the NEL character used as a line terminator,
7292 you must use UTF-8 encoding for the whole
7293 source program. In default mode, all lines must be ended by a standard
7294 end of line sequence (CR, CR/LF, or LF).
7295
7296 Note that the convention of simply accepting all upper half characters in
7297 comments means that programs that use standard ASCII for program text, but
7298 UTF-8 encoding for comments are accepted in default mode, providing that the
7299 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
7300 This is a common mode for many programs with foreign language comments.
7301
7302 @node File Naming Control
7303 @subsection File Naming Control
7304
7305 @table @option
7306 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7307 @cindex @option{-gnatk} (@command{gcc})
7308 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7309 1-999, indicates the maximum allowable length of a file name (not
7310 including the @file{.ads} or @file{.adb} extension). The default is not
7311 to enable file name krunching.
7312
7313 For the source file naming rules, @xref{File Naming Rules}.
7314 @end table
7315
7316 @node Subprogram Inlining Control
7317 @subsection Subprogram Inlining Control
7318
7319 @table @option
7320 @c !sort!
7321 @item -gnatn[12]
7322 @cindex @option{-gnatn} (@command{gcc})
7323 @ifclear vms
7324 The @code{n} here is intended to suggest the first syllable of the
7325 word ``inline''.
7326 @end ifclear
7327 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7328 inlining to actually occur, optimization must be enabled and, in order
7329 to enable inlining of subprograms specified by pragma @code{Inline},
7330 you must also specify this switch.
7331 In the absence of this switch, GNAT does not attempt
7332 inlining and does not need to access the bodies of
7333 subprograms for which @code{pragma Inline} is specified if they are not
7334 in the current unit.
7335
7336 You can optionally specify the inlining level: 1 for moderate inlining across
7337 modules, which is a good compromise between compilation times and performances
7338 at run time, or 2 for full inlining across modules, which may bring about
7339 longer compilation times. If no inlining level is specified, the compiler will
7340 pick it based on the optimization level: 1 for @option{-O1}, @option{-O2} or
7341 @option{-Os} and 2 for @option{-O3}.
7342
7343 If you specify this switch the compiler will access these bodies,
7344 creating an extra source dependency for the resulting object file, and
7345 where possible, the call will be inlined.
7346 For further details on when inlining is possible
7347 see @ref{Inlining of Subprograms}.
7348
7349 @item -gnatN
7350 @cindex @option{-gnatN} (@command{gcc})
7351 This switch activates front-end inlining which also
7352 generates additional dependencies.
7353
7354 When using a gcc-based back end (in practice this means using any version
7355 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7356 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7357 Historically front end inlining was more extensive than the gcc back end
7358 inlining, but that is no longer the case.
7359 @end table
7360
7361 @node Auxiliary Output Control
7362 @subsection Auxiliary Output Control
7363
7364 @table @option
7365 @item -gnatt
7366 @cindex @option{-gnatt} (@command{gcc})
7367 @cindex Writing internal trees
7368 @cindex Internal trees, writing to file
7369 Causes GNAT to write the internal tree for a unit to a file (with the
7370 extension @file{.adt}.
7371 This not normally required, but is used by separate analysis tools.
7372 Typically
7373 these tools do the necessary compilations automatically, so you should
7374 not have to specify this switch in normal operation.
7375 Note that the combination of switches @option{-gnatct}
7376 generates a tree in the form required by ASIS applications.
7377
7378 @item -gnatu
7379 @cindex @option{-gnatu} (@command{gcc})
7380 Print a list of units required by this compilation on @file{stdout}.
7381 The listing includes all units on which the unit being compiled depends
7382 either directly or indirectly.
7383
7384 @ifclear vms
7385 @item -pass-exit-codes
7386 @cindex @option{-pass-exit-codes} (@command{gcc})
7387 If this switch is not used, the exit code returned by @command{gcc} when
7388 compiling multiple files indicates whether all source files have
7389 been successfully used to generate object files or not.
7390
7391 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7392 exit status and allows an integrated development environment to better
7393 react to a compilation failure. Those exit status are:
7394
7395 @table @asis
7396 @item 5
7397 There was an error in at least one source file.
7398 @item 3
7399 At least one source file did not generate an object file.
7400 @item 2
7401 The compiler died unexpectedly (internal error for example).
7402 @item 0
7403 An object file has been generated for every source file.
7404 @end table
7405 @end ifclear
7406 @end table
7407
7408 @node Debugging Control
7409 @subsection Debugging Control
7410
7411 @table @option
7412 @c !sort!
7413 @cindex Debugging options
7414 @ifclear vms
7415 @item -gnatd@var{x}
7416 @cindex @option{-gnatd} (@command{gcc})
7417 Activate internal debugging switches. @var{x} is a letter or digit, or
7418 string of letters or digits, which specifies the type of debugging
7419 outputs desired. Normally these are used only for internal development
7420 or system debugging purposes. You can find full documentation for these
7421 switches in the body of the @code{Debug} unit in the compiler source
7422 file @file{debug.adb}.
7423 @end ifclear
7424
7425 @item -gnatG[=nn]
7426 @cindex @option{-gnatG} (@command{gcc})
7427 This switch causes the compiler to generate auxiliary output containing
7428 a pseudo-source listing of the generated expanded code. Like most Ada
7429 compilers, GNAT works by first transforming the high level Ada code into
7430 lower level constructs. For example, tasking operations are transformed
7431 into calls to the tasking run-time routines. A unique capability of GNAT
7432 is to list this expanded code in a form very close to normal Ada source.
7433 This is very useful in understanding the implications of various Ada
7434 usage on the efficiency of the generated code. There are many cases in
7435 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7436 generate a lot of run-time code. By using @option{-gnatG} you can identify
7437 these cases, and consider whether it may be desirable to modify the coding
7438 approach to improve efficiency.
7439
7440 The optional parameter @code{nn} if present after -gnatG specifies an
7441 alternative maximum line length that overrides the normal default of 72.
7442 This value is in the range 40-999999, values less than 40 being silently
7443 reset to 40. The equal sign is optional.
7444
7445 The format of the output is very similar to standard Ada source, and is
7446 easily understood by an Ada programmer. The following special syntactic
7447 additions correspond to low level features used in the generated code that
7448 do not have any exact analogies in pure Ada source form. The following
7449 is a partial list of these special constructions. See the spec
7450 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7451
7452 If the switch @option{-gnatL} is used in conjunction with
7453 @cindex @option{-gnatL} (@command{gcc})
7454 @option{-gnatG}, then the original source lines are interspersed
7455 in the expanded source (as comment lines with the original line number).
7456
7457 @table @code
7458 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7459 Shows the storage pool being used for an allocator.
7460
7461 @item at end @var{procedure-name};
7462 Shows the finalization (cleanup) procedure for a scope.
7463
7464 @item (if @var{expr} then @var{expr} else @var{expr})
7465 Conditional expression equivalent to the @code{x?y:z} construction in C.
7466
7467 @item @var{target}^^^(@var{source})
7468 A conversion with floating-point truncation instead of rounding.
7469
7470 @item @var{target}?(@var{source})
7471 A conversion that bypasses normal Ada semantic checking. In particular
7472 enumeration types and fixed-point types are treated simply as integers.
7473
7474 @item @var{target}?^^^(@var{source})
7475 Combines the above two cases.
7476
7477 @item @var{x} #/ @var{y}
7478 @itemx @var{x} #mod @var{y}
7479 @itemx @var{x} #* @var{y}
7480 @itemx @var{x} #rem @var{y}
7481 A division or multiplication of fixed-point values which are treated as
7482 integers without any kind of scaling.
7483
7484 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7485 Shows the storage pool associated with a @code{free} statement.
7486
7487 @item [subtype or type declaration]
7488 Used to list an equivalent declaration for an internally generated
7489 type that is referenced elsewhere in the listing.
7490
7491 @c @item freeze @var{type-name} @ovar{actions}
7492 @c Expanding @ovar macro inline (explanation in macro def comments)
7493 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7494 Shows the point at which @var{type-name} is frozen, with possible
7495 associated actions to be performed at the freeze point.
7496
7497 @item reference @var{itype}
7498 Reference (and hence definition) to internal type @var{itype}.
7499
7500 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7501 Intrinsic function call.
7502
7503 @item @var{label-name} : label
7504 Declaration of label @var{labelname}.
7505
7506 @item #$ @var{subprogram-name}
7507 An implicit call to a run-time support routine
7508 (to meet the requirement of H.3.1(9) in a
7509 convenient manner).
7510
7511 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7512 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7513 @var{expr}, but handled more efficiently).
7514
7515 @item [constraint_error]
7516 Raise the @code{Constraint_Error} exception.
7517
7518 @item @var{expression}'reference
7519 A pointer to the result of evaluating @var{expression}.
7520
7521 @item @var{target-type}!(@var{source-expression})
7522 An unchecked conversion of @var{source-expression} to @var{target-type}.
7523
7524 @item [@var{numerator}/@var{denominator}]
7525 Used to represent internal real literals (that) have no exact
7526 representation in base 2-16 (for example, the result of compile time
7527 evaluation of the expression 1.0/27.0).
7528 @end table
7529
7530 @item -gnatD[=nn]
7531 @cindex @option{-gnatD} (@command{gcc})
7532 When used in conjunction with @option{-gnatG}, this switch causes
7533 the expanded source, as described above for
7534 @option{-gnatG} to be written to files with names
7535 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7536 instead of to the standard output file. For
7537 example, if the source file name is @file{hello.adb}, then a file
7538 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
7539 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7540 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7541 you to do source level debugging using the generated code which is
7542 sometimes useful for complex code, for example to find out exactly
7543 which part of a complex construction raised an exception. This switch
7544 also suppress generation of cross-reference information (see
7545 @option{-gnatx}) since otherwise the cross-reference information
7546 would refer to the @file{^.dg^.DG^} file, which would cause
7547 confusion since this is not the original source file.
7548
7549 Note that @option{-gnatD} actually implies @option{-gnatG}
7550 automatically, so it is not necessary to give both options.
7551 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7552
7553 If the switch @option{-gnatL} is used in conjunction with
7554 @cindex @option{-gnatL} (@command{gcc})
7555 @option{-gnatDG}, then the original source lines are interspersed
7556 in the expanded source (as comment lines with the original line number).
7557
7558 The optional parameter @code{nn} if present after -gnatD specifies an
7559 alternative maximum line length that overrides the normal default of 72.
7560 This value is in the range 40-999999, values less than 40 being silently
7561 reset to 40. The equal sign is optional.
7562
7563 @item -gnatr
7564 @cindex @option{-gnatr} (@command{gcc})
7565 @cindex pragma Restrictions
7566 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7567 so that violation of restrictions causes warnings rather than illegalities.
7568 This is useful during the development process when new restrictions are added
7569 or investigated. The switch also causes pragma Profile to be treated as
7570 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7571 restriction warnings rather than restrictions.
7572
7573 @ifclear vms
7574 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7575 @cindex @option{-gnatR} (@command{gcc})
7576 This switch controls output from the compiler of a listing showing
7577 representation information for declared types and objects. For
7578 @option{-gnatR0}, no information is output (equivalent to omitting
7579 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7580 so @option{-gnatR} with no parameter has the same effect), size and alignment
7581 information is listed for declared array and record types. For
7582 @option{-gnatR2}, size and alignment information is listed for all
7583 declared types and objects. The @code{Linker_Section} is also listed for any
7584 entity for which the @code{Linker_Section} is set explicitly or implicitly (the
7585 latter case occurs for objects of a type for which a @code{Linker_Section}
7586 is set).
7587
7588 Finally @option{-gnatR3} includes symbolic
7589 expressions for values that are computed at run time for
7590 variant records. These symbolic expressions have a mostly obvious
7591 format with #n being used to represent the value of the n'th
7592 discriminant. See source files @file{repinfo.ads/adb} in the
7593 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7594 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7595 the output is to a file with the name @file{^file.rep^file_REP^} where
7596 file is the name of the corresponding source file.
7597
7598 @item -gnatRm[s]
7599 This form of the switch controls output of subprogram conventions
7600 and parameter passing mechanisms for all subprograms. A following
7601 @code{s} means output to a file as described above.
7602 @end ifclear
7603 @ifset vms
7604 @item /REPRESENTATION_INFO
7605 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7606 This qualifier controls output from the compiler of a listing showing
7607 representation information for declared types and objects. For
7608 @option{/REPRESENTATION_INFO=NONE}, no information is output
7609 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7610 @option{/REPRESENTATION_INFO} without option is equivalent to
7611 @option{/REPRESENTATION_INFO=ARRAYS}.
7612 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7613 information is listed for declared array and record types. For
7614 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7615 is listed for all expression information for values that are computed
7616 at run time for variant records. These symbolic expressions have a mostly
7617 obvious format with #n being used to represent the value of the n'th
7618 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7619 @code{GNAT} sources for full details on the format of
7620 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7621 If _FILE is added at the end of an option
7622 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7623 then the output is to a file with the name @file{file_REP} where
7624 file is the name of the corresponding source file.
7625
7626 @item /REPRESENTATION_INFO=MECHANISMS
7627 This qualifier form controls output of subprogram conventions
7628 and parameter passing mechanisms for all subprograms. It is
7629 possible to append _FILE as described above to cause information
7630 to be written to a file.
7631 @end ifset
7632
7633 Note that it is possible for record components to have zero size. In
7634 this case, the component clause uses an obvious extension of permitted
7635 Ada syntax, for example @code{at 0 range 0 .. -1}.
7636
7637 Representation information requires that code be generated (since it is the
7638 code generator that lays out complex data structures). If an attempt is made
7639 to output representation information when no code is generated, for example
7640 when a subunit is compiled on its own, then no information can be generated
7641 and the compiler outputs a message to this effect.
7642
7643 @item -gnatS
7644 @cindex @option{-gnatS} (@command{gcc})
7645 The use of the switch @option{-gnatS} for an
7646 Ada compilation will cause the compiler to output a
7647 representation of package Standard in a form very
7648 close to standard Ada. It is not quite possible to
7649 do this entirely in standard Ada (since new
7650 numeric base types cannot be created in standard
7651 Ada), but the output is easily
7652 readable to any Ada programmer, and is useful to
7653 determine the characteristics of target dependent
7654 types in package Standard.
7655
7656 @item -gnatx
7657 @cindex @option{-gnatx} (@command{gcc})
7658 Normally the compiler generates full cross-referencing information in
7659 the @file{ALI} file. This information is used by a number of tools,
7660 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7661 suppresses this information. This saves some space and may slightly
7662 speed up compilation, but means that these tools cannot be used.
7663 @end table
7664
7665 @node Exception Handling Control
7666 @subsection Exception Handling Control
7667
7668 @noindent
7669 GNAT uses two methods for handling exceptions at run-time. The
7670 @code{setjmp/longjmp} method saves the context when entering
7671 a frame with an exception handler. Then when an exception is
7672 raised, the context can be restored immediately, without the
7673 need for tracing stack frames. This method provides very fast
7674 exception propagation, but introduces significant overhead for
7675 the use of exception handlers, even if no exception is raised.
7676
7677 The other approach is called ``zero cost'' exception handling.
7678 With this method, the compiler builds static tables to describe
7679 the exception ranges. No dynamic code is required when entering
7680 a frame containing an exception handler. When an exception is
7681 raised, the tables are used to control a back trace of the
7682 subprogram invocation stack to locate the required exception
7683 handler. This method has considerably poorer performance for
7684 the propagation of exceptions, but there is no overhead for
7685 exception handlers if no exception is raised. Note that in this
7686 mode and in the context of mixed Ada and C/C++ programming,
7687 to propagate an exception through a C/C++ code, the C/C++ code
7688 must be compiled with the @option{-funwind-tables} GCC's
7689 option.
7690
7691 The following switches may be used to control which of the
7692 two exception handling methods is used.
7693
7694 @table @option
7695 @c !sort!
7696
7697 @item --RTS=sjlj
7698 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7699 This switch causes the setjmp/longjmp run-time (when available) to be used
7700 for exception handling. If the default
7701 mechanism for the target is zero cost exceptions, then
7702 this switch can be used to modify this default, and must be
7703 used for all units in the partition.
7704 This option is rarely used. One case in which it may be
7705 advantageous is if you have an application where exception
7706 raising is common and the overall performance of the
7707 application is improved by favoring exception propagation.
7708
7709 @item --RTS=zcx
7710 @cindex @option{--RTS=zcx} (@command{gnatmake})
7711 @cindex Zero Cost Exceptions
7712 This switch causes the zero cost approach to be used
7713 for exception handling. If this is the default mechanism for the
7714 target (see below), then this switch is unneeded. If the default
7715 mechanism for the target is setjmp/longjmp exceptions, then
7716 this switch can be used to modify this default, and must be
7717 used for all units in the partition.
7718 This option can only be used if the zero cost approach
7719 is available for the target in use, otherwise it will generate an error.
7720 @end table
7721
7722 @noindent
7723 The same option @option{--RTS} must be used both for @command{gcc}
7724 and @command{gnatbind}. Passing this option to @command{gnatmake}
7725 (@pxref{Switches for gnatmake}) will ensure the required consistency
7726 through the compilation and binding steps.
7727
7728 @node Units to Sources Mapping Files
7729 @subsection Units to Sources Mapping Files
7730
7731 @table @option
7732
7733 @item -gnatem=@var{path}
7734 @cindex @option{-gnatem} (@command{gcc})
7735 A mapping file is a way to communicate to the compiler two mappings:
7736 from unit names to file names (without any directory information) and from
7737 file names to path names (with full directory information). These mappings
7738 are used by the compiler to short-circuit the path search.
7739
7740 The use of mapping files is not required for correct operation of the
7741 compiler, but mapping files can improve efficiency, particularly when
7742 sources are read over a slow network connection. In normal operation,
7743 you need not be concerned with the format or use of mapping files,
7744 and the @option{-gnatem} switch is not a switch that you would use
7745 explicitly. It is intended primarily for use by automatic tools such as
7746 @command{gnatmake} running under the project file facility. The
7747 description here of the format of mapping files is provided
7748 for completeness and for possible use by other tools.
7749
7750 A mapping file is a sequence of sets of three lines. In each set, the
7751 first line is the unit name, in lower case, with @code{%s} appended
7752 for specs and @code{%b} appended for bodies; the second line is the
7753 file name; and the third line is the path name.
7754
7755 Example:
7756 @smallexample
7757 main%b
7758 main.2.ada
7759 /gnat/project1/sources/main.2.ada
7760 @end smallexample
7761
7762 When the switch @option{-gnatem} is specified, the compiler will
7763 create in memory the two mappings from the specified file. If there is
7764 any problem (nonexistent file, truncated file or duplicate entries),
7765 no mapping will be created.
7766
7767 Several @option{-gnatem} switches may be specified; however, only the
7768 last one on the command line will be taken into account.
7769
7770 When using a project file, @command{gnatmake} creates a temporary
7771 mapping file and communicates it to the compiler using this switch.
7772
7773 @end table
7774
7775 @node Integrated Preprocessing
7776 @subsection Integrated Preprocessing
7777
7778 @noindent
7779 GNAT sources may be preprocessed immediately before compilation.
7780 In this case, the actual
7781 text of the source is not the text of the source file, but is derived from it
7782 through a process called preprocessing. Integrated preprocessing is specified
7783 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7784 indicates, through a text file, the preprocessing data to be used.
7785 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7786 Note that integrated preprocessing applies only to Ada source files, it is
7787 not available for configuration pragma files.
7788
7789 @noindent
7790 Note that when integrated preprocessing is used, the output from the
7791 preprocessor is not written to any external file. Instead it is passed
7792 internally to the compiler. If you need to preserve the result of
7793 preprocessing in a file, then you should use @command{gnatprep}
7794 to perform the desired preprocessing in stand-alone mode.
7795
7796 @noindent
7797 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7798 used when Integrated Preprocessing is used. The reason is that preprocessing
7799 with another Preprocessing Data file without changing the sources will
7800 not trigger recompilation without this switch.
7801
7802 @noindent
7803 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7804 always trigger recompilation for sources that are preprocessed,
7805 because @command{gnatmake} cannot compute the checksum of the source after
7806 preprocessing.
7807
7808 @noindent
7809 The actual preprocessing function is described in details in section
7810 @ref{Preprocessing with gnatprep}. This section only describes how integrated
7811 preprocessing is triggered and parameterized.
7812
7813 @table @code
7814
7815 @item -gnatep=@var{file}
7816 @cindex @option{-gnatep} (@command{gcc})
7817 This switch indicates to the compiler the file name (without directory
7818 information) of the preprocessor data file to use. The preprocessor data file
7819 should be found in the source directories. Note that when the compiler is
7820 called by a builder such as (@command{gnatmake} with a project
7821 file, if the object directory is not also a source directory, the builder needs
7822 to be called with @option{-x}.
7823
7824 @noindent
7825 A preprocessing data file is a text file with significant lines indicating
7826 how should be preprocessed either a specific source or all sources not
7827 mentioned in other lines. A significant line is a nonempty, non-comment line.
7828 Comments are similar to Ada comments.
7829
7830 @noindent
7831 Each significant line starts with either a literal string or the character '*'.
7832 A literal string is the file name (without directory information) of the source
7833 to preprocess. A character '*' indicates the preprocessing for all the sources
7834 that are not specified explicitly on other lines (order of the lines is not
7835 significant). It is an error to have two lines with the same file name or two
7836 lines starting with the character '*'.
7837
7838 @noindent
7839 After the file name or the character '*', another optional literal string
7840 indicating the file name of the definition file to be used for preprocessing
7841 (@pxref{Form of Definitions File}). The definition files are found by the
7842 compiler in one of the source directories. In some cases, when compiling
7843 a source in a directory other than the current directory, if the definition
7844 file is in the current directory, it may be necessary to add the current
7845 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7846 the compiler would not find the definition file.
7847
7848 @noindent
7849 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7850 be found. Those ^switches^switches^ are:
7851
7852 @table @code
7853
7854 @item -b
7855 Causes both preprocessor lines and the lines deleted by
7856 preprocessing to be replaced by blank lines, preserving the line number.
7857 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7858 it cancels the effect of @option{-c}.
7859
7860 @item -c
7861 Causes both preprocessor lines and the lines deleted
7862 by preprocessing to be retained as comments marked
7863 with the special string ``@code{--! }''.
7864
7865 @item -Dsymbol=value
7866 Define or redefine a symbol, associated with value. A symbol is an Ada
7867 identifier, or an Ada reserved word, with the exception of @code{if},
7868 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7869 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7870 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7871 same name defined in a definition file.
7872
7873 @item -s
7874 Causes a sorted list of symbol names and values to be
7875 listed on the standard output file.
7876
7877 @item -u
7878 Causes undefined symbols to be treated as having the value @code{FALSE}
7879 in the context
7880 of a preprocessor test. In the absence of this option, an undefined symbol in
7881 a @code{#if} or @code{#elsif} test will be treated as an error.
7882
7883 @end table
7884
7885 @noindent
7886 Examples of valid lines in a preprocessor data file:
7887
7888 @smallexample
7889 "toto.adb" "prep.def" -u
7890 -- preprocess "toto.adb", using definition file "prep.def",
7891 -- undefined symbol are False.
7892
7893 * -c -DVERSION=V101
7894 -- preprocess all other sources without a definition file;
7895 -- suppressed lined are commented; symbol VERSION has the value V101.
7896
7897 "titi.adb" "prep2.def" -s
7898 -- preprocess "titi.adb", using definition file "prep2.def";
7899 -- list all symbols with their values.
7900 @end smallexample
7901
7902 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7903 @cindex @option{-gnateD} (@command{gcc})
7904 Define or redefine a preprocessing symbol, associated with value. If no value
7905 is given on the command line, then the value of the symbol is @code{True}.
7906 A symbol is an identifier, following normal Ada (case-insensitive)
7907 rules for its syntax, and value is either an arbitrary string between double
7908 quotes or any sequence (including an empty sequence) of characters from the
7909 set (letters, digits, period, underline).
7910 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7911 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7912
7913 @ifclear vms
7914 @noindent
7915 Examples:
7916
7917 @smallexample
7918 -gnateDToto=Titi
7919 -gnateDFoo
7920 -gnateDFoo=\"Foo-Bar\"
7921 @end smallexample
7922 @end ifclear
7923
7924 @noindent
7925 A symbol declared with this ^switch^switch^ on the command line replaces a
7926 symbol with the same name either in a definition file or specified with a
7927 ^switch^switch^ -D in the preprocessor data file.
7928
7929 @noindent
7930 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7931
7932 @item -gnateG
7933 When integrated preprocessing is performed and the preprocessor modifies
7934 the source text, write the result of this preprocessing into a file
7935 <source>^.prep^_prep^.
7936
7937 @end table
7938
7939 @node Code Generation Control
7940 @subsection Code Generation Control
7941
7942 @noindent
7943
7944 The GCC technology provides a wide range of target dependent
7945 @option{-m} switches for controlling
7946 details of code generation with respect to different versions of
7947 architectures. This includes variations in instruction sets (e.g.@:
7948 different members of the power pc family), and different requirements
7949 for optimal arrangement of instructions (e.g.@: different members of
7950 the x86 family). The list of available @option{-m} switches may be
7951 found in the GCC documentation.
7952
7953 Use of these @option{-m} switches may in some cases result in improved
7954 code performance.
7955
7956 The @value{EDITION} technology is tested and qualified without any
7957 @option{-m} switches,
7958 so generally the most reliable approach is to avoid the use of these
7959 switches. However, we generally expect most of these switches to work
7960 successfully with @value{EDITION}, and many customers have reported successful
7961 use of these options.
7962
7963 Our general advice is to avoid the use of @option{-m} switches unless
7964 special needs lead to requirements in this area. In particular,
7965 there is no point in using @option{-m} switches to improve performance
7966 unless you actually see a performance improvement.
7967
7968 @ifset vms
7969 @node Return Codes
7970 @subsection Return Codes
7971 @cindex Return Codes
7972 @cindex @option{/RETURN_CODES=VMS}
7973
7974 @noindent
7975 On VMS, GNAT compiled programs return POSIX-style codes by default,
7976 e.g.@: @option{/RETURN_CODES=POSIX}.
7977
7978 To enable VMS style return codes, use GNAT BIND and LINK with the option
7979 @option{/RETURN_CODES=VMS}. For example:
7980
7981 @smallexample
7982 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7983 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7984 @end smallexample
7985
7986 @noindent
7987 Programs built with /RETURN_CODES=VMS are suitable to be called in
7988 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7989 are suitable for spawning with appropriate GNAT RTL routines.
7990
7991 @end ifset
7992
7993 @node Search Paths and the Run-Time Library (RTL)
7994 @section Search Paths and the Run-Time Library (RTL)
7995
7996 @noindent
7997 With the GNAT source-based library system, the compiler must be able to
7998 find source files for units that are needed by the unit being compiled.
7999 Search paths are used to guide this process.
8000
8001 The compiler compiles one source file whose name must be given
8002 explicitly on the command line. In other words, no searching is done
8003 for this file. To find all other source files that are needed (the most
8004 common being the specs of units), the compiler examines the following
8005 directories, in the following order:
8006
8007 @enumerate
8008 @item
8009 The directory containing the source file of the main unit being compiled
8010 (the file name on the command line).
8011
8012 @item
8013 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
8014 @command{gcc} command line, in the order given.
8015
8016 @item
8017 @findex ADA_PRJ_INCLUDE_FILE
8018 Each of the directories listed in the text file whose name is given
8019 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
8020
8021 @noindent
8022 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8023 driver when project files are used. It should not normally be set
8024 by other means.
8025
8026 @item
8027 @findex ADA_INCLUDE_PATH
8028 Each of the directories listed in the value of the
8029 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
8030 @ifclear vms
8031 Construct this value
8032 exactly as the @env{PATH} environment variable: a list of directory
8033 names separated by colons (semicolons when working with the NT version).
8034 @end ifclear
8035 @ifset vms
8036 Normally, define this value as a logical name containing a comma separated
8037 list of directory names.
8038
8039 This variable can also be defined by means of an environment string
8040 (an argument to the HP C exec* set of functions).
8041
8042 Logical Name:
8043 @smallexample
8044 DEFINE ANOTHER_PATH FOO:[BAG]
8045 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8046 @end smallexample
8047
8048 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8049 first, followed by the standard Ada
8050 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
8051 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8052 (Text_IO, Sequential_IO, etc)
8053 instead of the standard Ada packages. Thus, in order to get the standard Ada
8054 packages by default, ADA_INCLUDE_PATH must be redefined.
8055 @end ifset
8056
8057 @item
8058 The content of the @file{ada_source_path} file which is part of the GNAT
8059 installation tree and is used to store standard libraries such as the
8060 GNAT Run Time Library (RTL) source files.
8061 @ifclear vms
8062 @ref{Installing a library}
8063 @end ifclear
8064 @end enumerate
8065
8066 @noindent
8067 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
8068 inhibits the use of the directory
8069 containing the source file named in the command line. You can still
8070 have this directory on your search path, but in this case it must be
8071 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
8072
8073 Specifying the switch @option{-nostdinc}
8074 inhibits the search of the default location for the GNAT Run Time
8075 Library (RTL) source files.
8076
8077 The compiler outputs its object files and ALI files in the current
8078 working directory.
8079 @ifclear vms
8080 Caution: The object file can be redirected with the @option{-o} switch;
8081 however, @command{gcc} and @code{gnat1} have not been coordinated on this
8082 so the @file{ALI} file will not go to the right place. Therefore, you should
8083 avoid using the @option{-o} switch.
8084 @end ifclear
8085
8086 @findex System.IO
8087 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8088 children make up the GNAT RTL, together with the simple @code{System.IO}
8089 package used in the @code{"Hello World"} example. The sources for these units
8090 are needed by the compiler and are kept together in one directory. Not
8091 all of the bodies are needed, but all of the sources are kept together
8092 anyway. In a normal installation, you need not specify these directory
8093 names when compiling or binding. Either the environment variables or
8094 the built-in defaults cause these files to be found.
8095
8096 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8097 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8098 consisting of child units of @code{GNAT}. This is a collection of generally
8099 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
8100 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
8101
8102 Besides simplifying access to the RTL, a major use of search paths is
8103 in compiling sources from multiple directories. This can make
8104 development environments much more flexible.
8105
8106 @node Order of Compilation Issues
8107 @section Order of Compilation Issues
8108
8109 @noindent
8110 If, in our earlier example, there was a spec for the @code{hello}
8111 procedure, it would be contained in the file @file{hello.ads}; yet this
8112 file would not have to be explicitly compiled. This is the result of the
8113 model we chose to implement library management. Some of the consequences
8114 of this model are as follows:
8115
8116 @itemize @bullet
8117 @item
8118 There is no point in compiling specs (except for package
8119 specs with no bodies) because these are compiled as needed by clients. If
8120 you attempt a useless compilation, you will receive an error message.
8121 It is also useless to compile subunits because they are compiled as needed
8122 by the parent.
8123
8124 @item
8125 There are no order of compilation requirements: performing a
8126 compilation never obsoletes anything. The only way you can obsolete
8127 something and require recompilations is to modify one of the
8128 source files on which it depends.
8129
8130 @item
8131 There is no library as such, apart from the ALI files
8132 (@pxref{The Ada Library Information Files}, for information on the format
8133 of these files). For now we find it convenient to create separate ALI files,
8134 but eventually the information therein may be incorporated into the object
8135 file directly.
8136
8137 @item
8138 When you compile a unit, the source files for the specs of all units
8139 that it @code{with}'s, all its subunits, and the bodies of any generics it
8140 instantiates must be available (reachable by the search-paths mechanism
8141 described above), or you will receive a fatal error message.
8142 @end itemize
8143
8144 @node Examples
8145 @section Examples
8146
8147 @noindent
8148 The following are some typical Ada compilation command line examples:
8149
8150 @table @code
8151 @item $ gcc -c xyz.adb
8152 Compile body in file @file{xyz.adb} with all default options.
8153
8154 @ifclear vms
8155 @item $ gcc -c -O2 -gnata xyz-def.adb
8156 @end ifclear
8157 @ifset vms
8158 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
8159 @end ifset
8160
8161 Compile the child unit package in file @file{xyz-def.adb} with extensive
8162 optimizations, and pragma @code{Assert}/@code{Debug} statements
8163 enabled.
8164
8165 @item $ gcc -c -gnatc abc-def.adb
8166 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
8167 mode.
8168 @end table
8169
8170 @node Binding with gnatbind
8171 @chapter Binding with @code{gnatbind}
8172 @findex gnatbind
8173
8174 @menu
8175 * Running gnatbind::
8176 * Switches for gnatbind::
8177 * Command-Line Access::
8178 * Search Paths for gnatbind::
8179 * Examples of gnatbind Usage::
8180 @end menu
8181
8182 @noindent
8183 This chapter describes the GNAT binder, @code{gnatbind}, which is used
8184 to bind compiled GNAT objects.
8185
8186 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
8187 driver (see @ref{The GNAT Driver and Project Files}).
8188
8189 The @code{gnatbind} program performs four separate functions:
8190
8191 @enumerate
8192 @item
8193 Checks that a program is consistent, in accordance with the rules in
8194 Chapter 10 of the Ada Reference Manual. In particular, error
8195 messages are generated if a program uses inconsistent versions of a
8196 given unit.
8197
8198 @item
8199 Checks that an acceptable order of elaboration exists for the program
8200 and issues an error message if it cannot find an order of elaboration
8201 that satisfies the rules in Chapter 10 of the Ada Language Manual.
8202
8203 @item
8204 Generates a main program incorporating the given elaboration order.
8205 This program is a small Ada package (body and spec) that
8206 must be subsequently compiled
8207 using the GNAT compiler. The necessary compilation step is usually
8208 performed automatically by @command{gnatlink}. The two most important
8209 functions of this program
8210 are to call the elaboration routines of units in an appropriate order
8211 and to call the main program.
8212
8213 @item
8214 Determines the set of object files required by the given main program.
8215 This information is output in the forms of comments in the generated program,
8216 to be read by the @command{gnatlink} utility used to link the Ada application.
8217 @end enumerate
8218
8219 @node Running gnatbind
8220 @section Running @code{gnatbind}
8221
8222 @noindent
8223 The form of the @code{gnatbind} command is
8224
8225 @smallexample
8226 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8227 @c Expanding @ovar macro inline (explanation in macro def comments)
8228 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8229 @end smallexample
8230
8231 @noindent
8232 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8233 unit body. @code{gnatbind} constructs an Ada
8234 package in two files whose names are
8235 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8236 For example, if given the
8237 parameter @file{hello.ali}, for a main program contained in file
8238 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8239 and @file{b~hello.adb}.
8240
8241 When doing consistency checking, the binder takes into consideration
8242 any source files it can locate. For example, if the binder determines
8243 that the given main program requires the package @code{Pack}, whose
8244 @file{.ALI}
8245 file is @file{pack.ali} and whose corresponding source spec file is
8246 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8247 (using the same search path conventions as previously described for the
8248 @command{gcc} command). If it can locate this source file, it checks that
8249 the time stamps
8250 or source checksums of the source and its references to in @file{ALI} files
8251 match. In other words, any @file{ALI} files that mentions this spec must have
8252 resulted from compiling this version of the source file (or in the case
8253 where the source checksums match, a version close enough that the
8254 difference does not matter).
8255
8256 @cindex Source files, use by binder
8257 The effect of this consistency checking, which includes source files, is
8258 that the binder ensures that the program is consistent with the latest
8259 version of the source files that can be located at bind time. Editing a
8260 source file without compiling files that depend on the source file cause
8261 error messages to be generated by the binder.
8262
8263 For example, suppose you have a main program @file{hello.adb} and a
8264 package @code{P}, from file @file{p.ads} and you perform the following
8265 steps:
8266
8267 @enumerate
8268 @item
8269 Enter @code{gcc -c hello.adb} to compile the main program.
8270
8271 @item
8272 Enter @code{gcc -c p.ads} to compile package @code{P}.
8273
8274 @item
8275 Edit file @file{p.ads}.
8276
8277 @item
8278 Enter @code{gnatbind hello}.
8279 @end enumerate
8280
8281 @noindent
8282 At this point, the file @file{p.ali} contains an out-of-date time stamp
8283 because the file @file{p.ads} has been edited. The attempt at binding
8284 fails, and the binder generates the following error messages:
8285
8286 @smallexample
8287 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8288 error: "p.ads" has been modified and must be recompiled
8289 @end smallexample
8290
8291 @noindent
8292 Now both files must be recompiled as indicated, and then the bind can
8293 succeed, generating a main program. You need not normally be concerned
8294 with the contents of this file, but for reference purposes a sample
8295 binder output file is given in @ref{Example of Binder Output File}.
8296
8297 In most normal usage, the default mode of @command{gnatbind} which is to
8298 generate the main package in Ada, as described in the previous section.
8299 In particular, this means that any Ada programmer can read and understand
8300 the generated main program. It can also be debugged just like any other
8301 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8302 @command{gnatbind} and @command{gnatlink}.
8303
8304 @node Switches for gnatbind
8305 @section Switches for @command{gnatbind}
8306
8307 @noindent
8308 The following switches are available with @code{gnatbind}; details will
8309 be presented in subsequent sections.
8310
8311 @menu
8312 * Consistency-Checking Modes::
8313 * Binder Error Message Control::
8314 * Elaboration Control::
8315 * Output Control::
8316 * Dynamic Allocation Control::
8317 * Binding with Non-Ada Main Programs::
8318 * Binding Programs with No Main Subprogram::
8319 @end menu
8320
8321 @table @option
8322 @c !sort!
8323
8324 @item --version
8325 @cindex @option{--version} @command{gnatbind}
8326 Display Copyright and version, then exit disregarding all other options.
8327
8328 @item --help
8329 @cindex @option{--help} @command{gnatbind}
8330 If @option{--version} was not used, display usage, then exit disregarding
8331 all other options.
8332
8333 @item -a
8334 @cindex @option{-a} @command{gnatbind}
8335 Indicates that, if supported by the platform, the adainit procedure should
8336 be treated as an initialisation routine by the linker (a constructor). This
8337 is intended to be used by the Project Manager to automatically initialize
8338 shared Stand-Alone Libraries.
8339
8340 @item ^-aO^/OBJECT_SEARCH^
8341 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8342 Specify directory to be searched for ALI files.
8343
8344 @item ^-aI^/SOURCE_SEARCH^
8345 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8346 Specify directory to be searched for source file.
8347
8348 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8349 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8350 Output ALI list (to standard output or to the named file).
8351
8352 @item ^-b^/REPORT_ERRORS=BRIEF^
8353 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8354 Generate brief messages to @file{stderr} even if verbose mode set.
8355
8356 @item ^-c^/NOOUTPUT^
8357 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8358 Check only, no generation of binder output file.
8359
8360 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8361 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8362 This switch can be used to change the default task stack size value
8363 to a specified size @var{nn}, which is expressed in bytes by default, or
8364 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8365 with @var{m}.
8366 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8367 in effect, to completing all task specs with
8368 @smallexample @c ada
8369 pragma Storage_Size (nn);
8370 @end smallexample
8371 When they do not already have such a pragma.
8372
8373 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8374 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8375 This switch can be used to change the default secondary stack size value
8376 to a specified size @var{nn}, which is expressed in bytes by default, or
8377 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8378 with @var{m}.
8379
8380 The secondary stack is used to deal with functions that return a variable
8381 sized result, for example a function returning an unconstrained
8382 String. There are two ways in which this secondary stack is allocated.
8383
8384 For most targets, the secondary stack is growing on demand and is allocated
8385 as a chain of blocks in the heap. The -D option is not very
8386 relevant. It only give some control over the size of the allocated
8387 blocks (whose size is the minimum of the default secondary stack size value,
8388 and the actual size needed for the current allocation request).
8389
8390 For certain targets, notably VxWorks 653,
8391 the secondary stack is allocated by carving off a fixed ratio chunk of the
8392 primary task stack. The -D option is used to define the
8393 size of the environment task's secondary stack.
8394
8395 @item ^-e^/ELABORATION_DEPENDENCIES^
8396 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8397 Output complete list of elaboration-order dependencies.
8398
8399 @item ^-E^/STORE_TRACEBACKS^
8400 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8401 Store tracebacks in exception occurrences when the target supports it.
8402 @ignore
8403 @c The following may get moved to an appendix
8404 This option is currently supported on the following targets:
8405 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8406 @end ignore
8407 See also the packages @code{GNAT.Traceback} and
8408 @code{GNAT.Traceback.Symbolic} for more information.
8409 @ifclear vms
8410 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8411 @command{gcc} option.
8412 @end ifclear
8413
8414 @item ^-F^/FORCE_ELABS_FLAGS^
8415 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8416 Force the checks of elaboration flags. @command{gnatbind} does not normally
8417 generate checks of elaboration flags for the main executable, except when
8418 a Stand-Alone Library is used. However, there are cases when this cannot be
8419 detected by gnatbind. An example is importing an interface of a Stand-Alone
8420 Library through a pragma Import and only specifying through a linker switch
8421 this Stand-Alone Library. This switch is used to guarantee that elaboration
8422 flag checks are generated.
8423
8424 @item ^-h^/HELP^
8425 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8426 Output usage (help) information
8427
8428 @item ^-H32^/32_MALLOC^
8429 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8430 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8431 For further details see @ref{Dynamic Allocation Control}.
8432
8433 @item ^-H64^/64_MALLOC^
8434 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8435 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8436 @cindex @code{__gnat_malloc}
8437 For further details see @ref{Dynamic Allocation Control}.
8438
8439 @item ^-I^/SEARCH^
8440 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8441 Specify directory to be searched for source and ALI files.
8442
8443 @item ^-I-^/NOCURRENT_DIRECTORY^
8444 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8445 Do not look for sources in the current directory where @code{gnatbind} was
8446 invoked, and do not look for ALI files in the directory containing the
8447 ALI file named in the @code{gnatbind} command line.
8448
8449 @item ^-l^/ORDER_OF_ELABORATION^
8450 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8451 Output chosen elaboration order.
8452
8453 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8454 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8455 Bind the units for library building. In this case the adainit and
8456 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8457 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8458 ^@var{xxx}final^@var{XXX}FINAL^.
8459 Implies ^-n^/NOCOMPILE^.
8460 @ifclear vms
8461 (@xref{GNAT and Libraries}, for more details.)
8462 @end ifclear
8463 @ifset vms
8464 On OpenVMS, these init and final procedures are exported in uppercase
8465 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8466 the init procedure will be "TOTOINIT" and the exported name of the final
8467 procedure will be "TOTOFINAL".
8468 @end ifset
8469
8470 @item ^-Mxyz^/RENAME_MAIN=xyz^
8471 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8472 Rename generated main program from main to xyz. This option is
8473 supported on cross environments only.
8474
8475 @item ^-m^/ERROR_LIMIT=^@var{n}
8476 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8477 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8478 in the range 1..999999. The default value if no switch is
8479 given is 9999. If the number of warnings reaches this limit, then a
8480 message is output and further warnings are suppressed, the bind
8481 continues in this case. If the number of errors reaches this
8482 limit, then a message is output and the bind is abandoned.
8483 A value of zero means that no limit is enforced. The equal
8484 sign is optional.
8485
8486 @item ^-n^/NOMAIN^
8487 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8488 No main program.
8489
8490 @item -nostdinc
8491 @cindex @option{-nostdinc} (@command{gnatbind})
8492 Do not look for sources in the system default directory.
8493
8494 @item -nostdlib
8495 @cindex @option{-nostdlib} (@command{gnatbind})
8496 Do not look for library files in the system default directory.
8497
8498 @item --RTS=@var{rts-path}
8499 @cindex @option{--RTS} (@code{gnatbind})
8500 Specifies the default location of the runtime library. Same meaning as the
8501 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8502
8503 @item ^-o ^/OUTPUT=^@var{file}
8504 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8505 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8506 Note that if this option is used, then linking must be done manually,
8507 gnatlink cannot be used.
8508
8509 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8510 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8511 Output object list (to standard output or to the named file).
8512
8513 @item ^-p^/PESSIMISTIC_ELABORATION^
8514 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8515 Pessimistic (worst-case) elaboration order
8516
8517 @item ^-P^-P^
8518 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8519 Generate binder file suitable for CodePeer.
8520
8521 @item ^-R^-R^
8522 @cindex @option{^-R^-R^} (@command{gnatbind})
8523 Output closure source list, which includes all non-time-units that are
8524 included in the bind.
8525
8526 @item ^-Ra^-Ra^
8527 @cindex @option{^-Ra^-Ra^} (@command{gnatbind})
8528 Like @option{-R} but the list includes run-time units.
8529
8530 @item ^-s^/READ_SOURCES=ALL^
8531 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8532 Require all source files to be present.
8533
8534 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8535 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8536 Specifies the value to be used when detecting uninitialized scalar
8537 objects with pragma Initialize_Scalars.
8538 The @var{xxx} ^string specified with the switch^option^ may be either
8539 @itemize @bullet
8540 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8541 @item ``@option{^lo^LOW^}'' for the lowest possible value
8542 @item ``@option{^hi^HIGH^}'' for the highest possible value
8543 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8544 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8545 @end itemize
8546
8547 In addition, you can specify @option{-Sev} to indicate that the value is
8548 to be set at run time. In this case, the program will look for an environment
8549 @cindex GNAT_INIT_SCALARS
8550 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8551 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8552 If no environment variable is found, or if it does not have a valid value,
8553 then the default is @option{in} (invalid values).
8554
8555 @ifclear vms
8556 @item -static
8557 @cindex @option{-static} (@code{gnatbind})
8558 Link against a static GNAT run time.
8559
8560 @item -shared
8561 @cindex @option{-shared} (@code{gnatbind})
8562 Link against a shared GNAT run time when available.
8563 @end ifclear
8564
8565 @item ^-t^/NOTIME_STAMP_CHECK^
8566 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8567 Tolerate time stamp and other consistency errors
8568
8569 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8570 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8571 Set the time slice value to @var{n} milliseconds. If the system supports
8572 the specification of a specific time slice value, then the indicated value
8573 is used. If the system does not support specific time slice values, but
8574 does support some general notion of round-robin scheduling, then any
8575 nonzero value will activate round-robin scheduling.
8576
8577 A value of zero is treated specially. It turns off time
8578 slicing, and in addition, indicates to the tasking run time that the
8579 semantics should match as closely as possible the Annex D
8580 requirements of the Ada RM, and in particular sets the default
8581 scheduling policy to @code{FIFO_Within_Priorities}.
8582
8583 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8584 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8585 Enable dynamic stack usage, with @var{n} results stored and displayed
8586 at program termination. A result is generated when a task
8587 terminates. Results that can't be stored are displayed on the fly, at
8588 task termination. This option is currently not supported on Itanium
8589 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8590
8591 @item ^-v^/REPORT_ERRORS=VERBOSE^
8592 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8593 Verbose mode. Write error messages, header, summary output to
8594 @file{stdout}.
8595
8596 @ifclear vms
8597 @item -w@var{x}
8598 @cindex @option{-w} (@code{gnatbind})
8599 Warning mode (@var{x}=s/e for suppress/treat as error)
8600 @end ifclear
8601
8602 @ifset vms
8603 @item /WARNINGS=NORMAL
8604 @cindex @option{/WARNINGS} (@code{gnatbind})
8605 Normal warnings mode. Warnings are issued but ignored
8606
8607 @item /WARNINGS=SUPPRESS
8608 @cindex @option{/WARNINGS} (@code{gnatbind})
8609 All warning messages are suppressed
8610
8611 @item /WARNINGS=ERROR
8612 @cindex @option{/WARNINGS} (@code{gnatbind})
8613 Warning messages are treated as fatal errors
8614 @end ifset
8615
8616 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8617 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8618 Override default wide character encoding for standard Text_IO files.
8619
8620 @item ^-x^/READ_SOURCES=NONE^
8621 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8622 Exclude source files (check object consistency only).
8623
8624 @ifset vms
8625 @item /READ_SOURCES=AVAILABLE
8626 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8627 Default mode, in which sources are checked for consistency only if
8628 they are available.
8629 @end ifset
8630
8631 @item ^-X@var{nnn}^/RETURN_CODES=POSIX^
8632 @cindex @option{^-X@var{nnn}^/RETURN_CODES=POSIX^} (@code{gnatbind})
8633 Set default exit status value, normally 0 for POSIX compliance.
8634
8635 @ifset vms
8636 @item /RETURN_CODES=VMS
8637 @cindex @option{/RETURN_CODES=VMS} (@code{gnatbind})
8638 VMS default normal successful return value is 1.
8639 @end ifset
8640
8641 @item ^-y^/ENABLE_LEAP_SECONDS^
8642 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8643 Enable leap seconds support in @code{Ada.Calendar} and its children.
8644
8645 @item ^-z^/ZERO_MAIN^
8646 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8647 No main subprogram.
8648 @end table
8649
8650 @ifclear vms
8651 @noindent
8652 You may obtain this listing of switches by running @code{gnatbind} with
8653 no arguments.
8654 @end ifclear
8655
8656 @node Consistency-Checking Modes
8657 @subsection Consistency-Checking Modes
8658
8659 @noindent
8660 As described earlier, by default @code{gnatbind} checks
8661 that object files are consistent with one another and are consistent
8662 with any source files it can locate. The following switches control binder
8663 access to sources.
8664
8665 @table @option
8666 @c !sort!
8667 @item ^-s^/READ_SOURCES=ALL^
8668 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8669 Require source files to be present. In this mode, the binder must be
8670 able to locate all source files that are referenced, in order to check
8671 their consistency. In normal mode, if a source file cannot be located it
8672 is simply ignored. If you specify this switch, a missing source
8673 file is an error.
8674
8675 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8676 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8677 Override default wide character encoding for standard Text_IO files.
8678 Normally the default wide character encoding method used for standard
8679 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8680 the main source input (see description of switch
8681 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8682 use of this switch for the binder (which has the same set of
8683 possible arguments) overrides this default as specified.
8684
8685 @item ^-x^/READ_SOURCES=NONE^
8686 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8687 Exclude source files. In this mode, the binder only checks that ALI
8688 files are consistent with one another. Source files are not accessed.
8689 The binder runs faster in this mode, and there is still a guarantee that
8690 the resulting program is self-consistent.
8691 If a source file has been edited since it was last compiled, and you
8692 specify this switch, the binder will not detect that the object
8693 file is out of date with respect to the source file. Note that this is the
8694 mode that is automatically used by @command{gnatmake} because in this
8695 case the checking against sources has already been performed by
8696 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8697
8698 @ifset vms
8699 @item /READ_SOURCES=AVAILABLE
8700 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8701 This is the default mode in which source files are checked if they are
8702 available, and ignored if they are not available.
8703 @end ifset
8704 @end table
8705
8706 @node Binder Error Message Control
8707 @subsection Binder Error Message Control
8708
8709 @noindent
8710 The following switches provide control over the generation of error
8711 messages from the binder:
8712
8713 @table @option
8714 @c !sort!
8715 @item ^-v^/REPORT_ERRORS=VERBOSE^
8716 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8717 Verbose mode. In the normal mode, brief error messages are generated to
8718 @file{stderr}. If this switch is present, a header is written
8719 to @file{stdout} and any error messages are directed to @file{stdout}.
8720 All that is written to @file{stderr} is a brief summary message.
8721
8722 @item ^-b^/REPORT_ERRORS=BRIEF^
8723 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8724 Generate brief error messages to @file{stderr} even if verbose mode is
8725 specified. This is relevant only when used with the
8726 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8727
8728 @ifclear vms
8729 @item -m@var{n}
8730 @cindex @option{-m} (@code{gnatbind})
8731 Limits the number of error messages to @var{n}, a decimal integer in the
8732 range 1-999. The binder terminates immediately if this limit is reached.
8733
8734 @item -M@var{xxx}
8735 @cindex @option{-M} (@code{gnatbind})
8736 Renames the generated main program from @code{main} to @code{xxx}.
8737 This is useful in the case of some cross-building environments, where
8738 the actual main program is separate from the one generated
8739 by @code{gnatbind}.
8740 @end ifclear
8741
8742 @item ^-ws^/WARNINGS=SUPPRESS^
8743 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8744 @cindex Warnings
8745 Suppress all warning messages.
8746
8747 @item ^-we^/WARNINGS=ERROR^
8748 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8749 Treat any warning messages as fatal errors.
8750
8751 @ifset vms
8752 @item /WARNINGS=NORMAL
8753 Standard mode with warnings generated, but warnings do not get treated
8754 as errors.
8755 @end ifset
8756
8757 @item ^-t^/NOTIME_STAMP_CHECK^
8758 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8759 @cindex Time stamp checks, in binder
8760 @cindex Binder consistency checks
8761 @cindex Consistency checks, in binder
8762 The binder performs a number of consistency checks including:
8763
8764 @itemize @bullet
8765 @item
8766 Check that time stamps of a given source unit are consistent
8767 @item
8768 Check that checksums of a given source unit are consistent
8769 @item
8770 Check that consistent versions of @code{GNAT} were used for compilation
8771 @item
8772 Check consistency of configuration pragmas as required
8773 @end itemize
8774
8775 @noindent
8776 Normally failure of such checks, in accordance with the consistency
8777 requirements of the Ada Reference Manual, causes error messages to be
8778 generated which abort the binder and prevent the output of a binder
8779 file and subsequent link to obtain an executable.
8780
8781 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8782 into warnings, so that
8783 binding and linking can continue to completion even in the presence of such
8784 errors. The result may be a failed link (due to missing symbols), or a
8785 non-functional executable which has undefined semantics.
8786 @emph{This means that
8787 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8788 with extreme care.}
8789 @end table
8790
8791 @node Elaboration Control
8792 @subsection Elaboration Control
8793
8794 @noindent
8795 The following switches provide additional control over the elaboration
8796 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8797
8798 @table @option
8799 @item ^-p^/PESSIMISTIC_ELABORATION^
8800 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8801 Normally the binder attempts to choose an elaboration order that is
8802 likely to minimize the likelihood of an elaboration order error resulting
8803 in raising a @code{Program_Error} exception. This switch reverses the
8804 action of the binder, and requests that it deliberately choose an order
8805 that is likely to maximize the likelihood of an elaboration error.
8806 This is useful in ensuring portability and avoiding dependence on
8807 accidental fortuitous elaboration ordering.
8808
8809 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8810 switch if dynamic
8811 elaboration checking is used (@option{-gnatE} switch used for compilation).
8812 This is because in the default static elaboration mode, all necessary
8813 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8814 These implicit pragmas are still respected by the binder in
8815 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8816 safe elaboration order is assured.
8817
8818 Note that @option{^-p^/PESSIMISTIC_ELABORATION^} is not intended for
8819 production use; it is more for debugging/experimental use.
8820 @end table
8821
8822 @node Output Control
8823 @subsection Output Control
8824
8825 @noindent
8826 The following switches allow additional control over the output
8827 generated by the binder.
8828
8829 @table @option
8830 @c !sort!
8831
8832 @item ^-c^/NOOUTPUT^
8833 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8834 Check only. Do not generate the binder output file. In this mode the
8835 binder performs all error checks but does not generate an output file.
8836
8837 @item ^-e^/ELABORATION_DEPENDENCIES^
8838 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8839 Output complete list of elaboration-order dependencies, showing the
8840 reason for each dependency. This output can be rather extensive but may
8841 be useful in diagnosing problems with elaboration order. The output is
8842 written to @file{stdout}.
8843
8844 @item ^-h^/HELP^
8845 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8846 Output usage information. The output is written to @file{stdout}.
8847
8848 @item ^-K^/LINKER_OPTION_LIST^
8849 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8850 Output linker options to @file{stdout}. Includes library search paths,
8851 contents of pragmas Ident and Linker_Options, and libraries added
8852 by @code{gnatbind}.
8853
8854 @item ^-l^/ORDER_OF_ELABORATION^
8855 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8856 Output chosen elaboration order. The output is written to @file{stdout}.
8857
8858 @item ^-O^/OBJECT_LIST^
8859 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8860 Output full names of all the object files that must be linked to provide
8861 the Ada component of the program. The output is written to @file{stdout}.
8862 This list includes the files explicitly supplied and referenced by the user
8863 as well as implicitly referenced run-time unit files. The latter are
8864 omitted if the corresponding units reside in shared libraries. The
8865 directory names for the run-time units depend on the system configuration.
8866
8867 @item ^-o ^/OUTPUT=^@var{file}
8868 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8869 Set name of output file to @var{file} instead of the normal
8870 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8871 binder generated body filename.
8872 Note that if this option is used, then linking must be done manually.
8873 It is not possible to use gnatlink in this case, since it cannot locate
8874 the binder file.
8875
8876 @item ^-r^/RESTRICTION_LIST^
8877 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8878 Generate list of @code{pragma Restrictions} that could be applied to
8879 the current unit. This is useful for code audit purposes, and also may
8880 be used to improve code generation in some cases.
8881
8882 @end table
8883
8884 @node Dynamic Allocation Control
8885 @subsection Dynamic Allocation Control
8886
8887 @noindent
8888 The heap control switches -- @option{-H32} and @option{-H64} --
8889 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8890 They only affect compiler-generated allocations via @code{__gnat_malloc};
8891 explicit calls to @code{malloc} and related functions from the C
8892 run-time library are unaffected.
8893
8894 @table @option
8895 @item -H32
8896 Allocate memory on 32-bit heap
8897
8898 @item -H64
8899 Allocate memory on 64-bit heap. This is the default
8900 unless explicitly overridden by a @code{'Size} clause on the access type.
8901 @end table
8902
8903 @ifset vms
8904 @noindent
8905 See also @ref{Access types and 32/64-bit allocation}.
8906 @end ifset
8907 @ifclear vms
8908 @noindent
8909 These switches are only effective on VMS platforms.
8910 @end ifclear
8911
8912
8913 @node Binding with Non-Ada Main Programs
8914 @subsection Binding with Non-Ada Main Programs
8915
8916 @noindent
8917 In our description so far we have assumed that the main
8918 program is in Ada, and that the task of the binder is to generate a
8919 corresponding function @code{main} that invokes this Ada main
8920 program. GNAT also supports the building of executable programs where
8921 the main program is not in Ada, but some of the called routines are
8922 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8923 The following switch is used in this situation:
8924
8925 @table @option
8926 @item ^-n^/NOMAIN^
8927 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8928 No main program. The main program is not in Ada.
8929 @end table
8930
8931 @noindent
8932 In this case, most of the functions of the binder are still required,
8933 but instead of generating a main program, the binder generates a file
8934 containing the following callable routines:
8935
8936 @table @code
8937 @item adainit
8938 @findex adainit
8939 You must call this routine to initialize the Ada part of the program by
8940 calling the necessary elaboration routines. A call to @code{adainit} is
8941 required before the first call to an Ada subprogram.
8942
8943 Note that it is assumed that the basic execution environment must be setup
8944 to be appropriate for Ada execution at the point where the first Ada
8945 subprogram is called. In particular, if the Ada code will do any
8946 floating-point operations, then the FPU must be setup in an appropriate
8947 manner. For the case of the x86, for example, full precision mode is
8948 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8949 that the FPU is in the right state.
8950
8951 @item adafinal
8952 @findex adafinal
8953 You must call this routine to perform any library-level finalization
8954 required by the Ada subprograms. A call to @code{adafinal} is required
8955 after the last call to an Ada subprogram, and before the program
8956 terminates.
8957 @end table
8958
8959 @noindent
8960 If the @option{^-n^/NOMAIN^} switch
8961 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8962 @cindex Binder, multiple input files
8963 is given, more than one ALI file may appear on
8964 the command line for @code{gnatbind}. The normal @dfn{closure}
8965 calculation is performed for each of the specified units. Calculating
8966 the closure means finding out the set of units involved by tracing
8967 @code{with} references. The reason it is necessary to be able to
8968 specify more than one ALI file is that a given program may invoke two or
8969 more quite separate groups of Ada units.
8970
8971 The binder takes the name of its output file from the last specified ALI
8972 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8973 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8974 The output is an Ada unit in source form that can be compiled with GNAT.
8975 This compilation occurs automatically as part of the @command{gnatlink}
8976 processing.
8977
8978 Currently the GNAT run time requires a FPU using 80 bits mode
8979 precision. Under targets where this is not the default it is required to
8980 call GNAT.Float_Control.Reset before using floating point numbers (this
8981 include float computation, float input and output) in the Ada code. A
8982 side effect is that this could be the wrong mode for the foreign code
8983 where floating point computation could be broken after this call.
8984
8985 @node Binding Programs with No Main Subprogram
8986 @subsection Binding Programs with No Main Subprogram
8987
8988 @noindent
8989 It is possible to have an Ada program which does not have a main
8990 subprogram. This program will call the elaboration routines of all the
8991 packages, then the finalization routines.
8992
8993 The following switch is used to bind programs organized in this manner:
8994
8995 @table @option
8996 @item ^-z^/ZERO_MAIN^
8997 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8998 Normally the binder checks that the unit name given on the command line
8999 corresponds to a suitable main subprogram. When this switch is used,
9000 a list of ALI files can be given, and the execution of the program
9001 consists of elaboration of these units in an appropriate order. Note
9002 that the default wide character encoding method for standard Text_IO
9003 files is always set to Brackets if this switch is set (you can use
9004 the binder switch
9005 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
9006 @end table
9007
9008 @node Command-Line Access
9009 @section Command-Line Access
9010
9011 @noindent
9012 The package @code{Ada.Command_Line} provides access to the command-line
9013 arguments and program name. In order for this interface to operate
9014 correctly, the two variables
9015
9016 @smallexample
9017 @group
9018 int gnat_argc;
9019 char **gnat_argv;
9020 @end group
9021 @end smallexample
9022
9023 @noindent
9024 @findex gnat_argv
9025 @findex gnat_argc
9026 are declared in one of the GNAT library routines. These variables must
9027 be set from the actual @code{argc} and @code{argv} values passed to the
9028 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
9029 generates the C main program to automatically set these variables.
9030 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
9031 set these variables. If they are not set, the procedures in
9032 @code{Ada.Command_Line} will not be available, and any attempt to use
9033 them will raise @code{Constraint_Error}. If command line access is
9034 required, your main program must set @code{gnat_argc} and
9035 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
9036 it.
9037
9038 @node Search Paths for gnatbind
9039 @section Search Paths for @code{gnatbind}
9040
9041 @noindent
9042 The binder takes the name of an ALI file as its argument and needs to
9043 locate source files as well as other ALI files to verify object consistency.
9044
9045 For source files, it follows exactly the same search rules as @command{gcc}
9046 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
9047 directories searched are:
9048
9049 @enumerate
9050 @item
9051 The directory containing the ALI file named in the command line, unless
9052 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
9053
9054 @item
9055 All directories specified by @option{^-I^/SEARCH^}
9056 switches on the @code{gnatbind}
9057 command line, in the order given.
9058
9059 @item
9060 @findex ADA_PRJ_OBJECTS_FILE
9061 Each of the directories listed in the text file whose name is given
9062 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
9063
9064 @noindent
9065 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
9066 driver when project files are used. It should not normally be set
9067 by other means.
9068
9069 @item
9070 @findex ADA_OBJECTS_PATH
9071 Each of the directories listed in the value of the
9072 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
9073 @ifset unw
9074 Construct this value
9075 exactly as the @env{PATH} environment variable: a list of directory
9076 names separated by colons (semicolons when working with the NT version
9077 of GNAT).
9078 @end ifset
9079 @ifset vms
9080 Normally, define this value as a logical name containing a comma separated
9081 list of directory names.
9082
9083 This variable can also be defined by means of an environment string
9084 (an argument to the HP C exec* set of functions).
9085
9086 Logical Name:
9087 @smallexample
9088 DEFINE ANOTHER_PATH FOO:[BAG]
9089 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
9090 @end smallexample
9091
9092 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
9093 first, followed by the standard Ada
9094 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
9095 If this is not redefined, the user will obtain the HP Ada 83 IO packages
9096 (Text_IO, Sequential_IO, etc)
9097 instead of the standard Ada packages. Thus, in order to get the standard Ada
9098 packages by default, ADA_OBJECTS_PATH must be redefined.
9099 @end ifset
9100
9101 @item
9102 The content of the @file{ada_object_path} file which is part of the GNAT
9103 installation tree and is used to store standard libraries such as the
9104 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
9105 specified.
9106 @ifclear vms
9107 @ref{Installing a library}
9108 @end ifclear
9109 @end enumerate
9110
9111 @noindent
9112 In the binder the switch @option{^-I^/SEARCH^}
9113 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
9114 is used to specify both source and
9115 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9116 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
9117 instead if you want to specify
9118 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
9119 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
9120 if you want to specify library paths
9121 only. This means that for the binder
9122 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
9123 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
9124 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
9125 The binder generates the bind file (a C language source file) in the
9126 current working directory.
9127
9128 @findex Ada
9129 @findex System
9130 @findex Interfaces
9131 @findex GNAT
9132 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
9133 children make up the GNAT Run-Time Library, together with the package
9134 GNAT and its children, which contain a set of useful additional
9135 library functions provided by GNAT. The sources for these units are
9136 needed by the compiler and are kept together in one directory. The ALI
9137 files and object files generated by compiling the RTL are needed by the
9138 binder and the linker and are kept together in one directory, typically
9139 different from the directory containing the sources. In a normal
9140 installation, you need not specify these directory names when compiling
9141 or binding. Either the environment variables or the built-in defaults
9142 cause these files to be found.
9143
9144 Besides simplifying access to the RTL, a major use of search paths is
9145 in compiling sources from multiple directories. This can make
9146 development environments much more flexible.
9147
9148 @node Examples of gnatbind Usage
9149 @section Examples of @code{gnatbind} Usage
9150
9151 @noindent
9152 This section contains a number of examples of using the GNAT binding
9153 utility @code{gnatbind}.
9154
9155 @table @code
9156 @item gnatbind hello
9157 The main program @code{Hello} (source program in @file{hello.adb}) is
9158 bound using the standard switch settings. The generated main program is
9159 @file{b~hello.adb}. This is the normal, default use of the binder.
9160
9161 @ifclear vms
9162 @item gnatbind hello -o mainprog.adb
9163 @end ifclear
9164 @ifset vms
9165 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
9166 @end ifset
9167 The main program @code{Hello} (source program in @file{hello.adb}) is
9168 bound using the standard switch settings. The generated main program is
9169 @file{mainprog.adb} with the associated spec in
9170 @file{mainprog.ads}. Note that you must specify the body here not the
9171 spec. Note that if this option is used, then linking must be done manually,
9172 since gnatlink will not be able to find the generated file.
9173 @end table
9174
9175 @c ------------------------------------
9176 @node Linking with gnatlink
9177 @chapter Linking with @command{gnatlink}
9178 @c ------------------------------------
9179 @findex gnatlink
9180
9181 @noindent
9182 This chapter discusses @command{gnatlink}, a tool that links
9183 an Ada program and builds an executable file. This utility
9184 invokes the system linker ^(via the @command{gcc} command)^^
9185 with a correct list of object files and library references.
9186 @command{gnatlink} automatically determines the list of files and
9187 references for the Ada part of a program. It uses the binder file
9188 generated by the @command{gnatbind} to determine this list.
9189
9190 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
9191 driver (see @ref{The GNAT Driver and Project Files}).
9192
9193 @menu
9194 * Running gnatlink::
9195 * Switches for gnatlink::
9196 @end menu
9197
9198 @node Running gnatlink
9199 @section Running @command{gnatlink}
9200
9201 @noindent
9202 The form of the @command{gnatlink} command is
9203
9204 @smallexample
9205 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
9206 @c @ovar{non-Ada objects} @ovar{linker options}
9207 @c Expanding @ovar macro inline (explanation in macro def comments)
9208 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
9209 @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
9210
9211 @end smallexample
9212
9213 @noindent
9214 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
9215 non-Ada objects
9216 or linker options) may be in any order, provided that no non-Ada object may
9217 be mistaken for a main @file{ALI} file.
9218 Any file name @file{F} without the @file{.ali}
9219 extension will be taken as the main @file{ALI} file if a file exists
9220 whose name is the concatenation of @file{F} and @file{.ali}.
9221
9222 @noindent
9223 @file{@var{mainprog}.ali} references the ALI file of the main program.
9224 The @file{.ali} extension of this file can be omitted. From this
9225 reference, @command{gnatlink} locates the corresponding binder file
9226 @file{b~@var{mainprog}.adb} and, using the information in this file along
9227 with the list of non-Ada objects and linker options, constructs a
9228 linker command file to create the executable.
9229
9230 The arguments other than the @command{gnatlink} switches and the main
9231 @file{ALI} file are passed to the linker uninterpreted.
9232 They typically include the names of
9233 object files for units written in other languages than Ada and any library
9234 references required to resolve references in any of these foreign language
9235 units, or in @code{Import} pragmas in any Ada units.
9236
9237 @var{linker options} is an optional list of linker specific
9238 switches.
9239 The default linker called by gnatlink is @command{gcc} which in
9240 turn calls the appropriate system linker.
9241
9242 One useful option for the linker is @option{-s}: it reduces the size of the
9243 executable by removing all symbol table and relocation information from the
9244 executable.
9245
9246 Standard options for the linker such as @option{-lmy_lib} or
9247 @option{-Ldir} can be added as is.
9248 For options that are not recognized by
9249 @command{gcc} as linker options, use the @command{gcc} switches
9250 @option{-Xlinker} or @option{-Wl,}.
9251
9252 Refer to the GCC documentation for
9253 details.
9254
9255 Here is an example showing how to generate a linker map:
9256
9257 @smallexample
9258 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9259 @end smallexample
9260
9261 Using @var{linker options} it is possible to set the program stack and
9262 heap size.
9263 @ifset unw
9264 See @ref{Setting Stack Size from gnatlink} and
9265 @ref{Setting Heap Size from gnatlink}.
9266 @end ifset
9267
9268 @command{gnatlink} determines the list of objects required by the Ada
9269 program and prepends them to the list of objects passed to the linker.
9270 @command{gnatlink} also gathers any arguments set by the use of
9271 @code{pragma Linker_Options} and adds them to the list of arguments
9272 presented to the linker.
9273
9274 @ifset vms
9275 @command{gnatlink} accepts the following types of extra files on the command
9276 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9277 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9278 handled according to their extension.
9279 @end ifset
9280
9281 @node Switches for gnatlink
9282 @section Switches for @command{gnatlink}
9283
9284 @noindent
9285 The following switches are available with the @command{gnatlink} utility:
9286
9287 @table @option
9288 @c !sort!
9289
9290 @item --version
9291 @cindex @option{--version} @command{gnatlink}
9292 Display Copyright and version, then exit disregarding all other options.
9293
9294 @item --help
9295 @cindex @option{--help} @command{gnatlink}
9296 If @option{--version} was not used, display usage, then exit disregarding
9297 all other options.
9298
9299 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9300 @cindex Command line length
9301 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9302 On some targets, the command line length is limited, and @command{gnatlink}
9303 will generate a separate file for the linker if the list of object files
9304 is too long.
9305 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9306 to be generated even if
9307 the limit is not exceeded. This is useful in some cases to deal with
9308 special situations where the command line length is exceeded.
9309
9310 @item ^-g^/DEBUG^
9311 @cindex Debugging information, including
9312 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9313 The option to include debugging information causes the Ada bind file (in
9314 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9315 @option{^-g^/DEBUG^}.
9316 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9317 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9318 Without @option{^-g^/DEBUG^}, the binder removes these files by
9319 default. The same procedure apply if a C bind file was generated using
9320 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9321 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9322
9323 @item ^-n^/NOCOMPILE^
9324 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9325 Do not compile the file generated by the binder. This may be used when
9326 a link is rerun with different options, but there is no need to recompile
9327 the binder file.
9328
9329 @item ^-v^/VERBOSE^
9330 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9331 Causes additional information to be output, including a full list of the
9332 included object files. This switch option is most useful when you want
9333 to see what set of object files are being used in the link step.
9334
9335 @item ^-v -v^/VERBOSE/VERBOSE^
9336 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9337 Very verbose mode. Requests that the compiler operate in verbose mode when
9338 it compiles the binder file, and that the system linker run in verbose mode.
9339
9340 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9341 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9342 @var{exec-name} specifies an alternate name for the generated
9343 executable program. If this switch is omitted, the executable has the same
9344 name as the main unit. For example, @code{gnatlink try.ali} creates
9345 an executable called @file{^try^TRY.EXE^}.
9346
9347 @ifclear vms
9348 @item -b @var{target}
9349 @cindex @option{-b} (@command{gnatlink})
9350 Compile your program to run on @var{target}, which is the name of a
9351 system configuration. You must have a GNAT cross-compiler built if
9352 @var{target} is not the same as your host system.
9353
9354 @item -B@var{dir}
9355 @cindex @option{-B} (@command{gnatlink})
9356 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9357 from @var{dir} instead of the default location. Only use this switch
9358 when multiple versions of the GNAT compiler are available.
9359 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9360 for further details. You would normally use the @option{-b} or
9361 @option{-V} switch instead.
9362
9363 @item -M
9364 When linking an executable, create a map file. The name of the map file
9365 has the same name as the executable with extension ".map".
9366
9367 @item -M=mapfile
9368 When linking an executable, create a map file. The name of the map file is
9369 "mapfile".
9370
9371 @item --GCC=@var{compiler_name}
9372 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9373 Program used for compiling the binder file. The default is
9374 @command{gcc}. You need to use quotes around @var{compiler_name} if
9375 @code{compiler_name} contains spaces or other separator characters.
9376 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9377 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9378 inserted after your command name. Thus in the above example the compiler
9379 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9380 A limitation of this syntax is that the name and path name of the executable
9381 itself must not include any embedded spaces. If the compiler executable is
9382 different from the default one (gcc or <prefix>-gcc), then the back-end
9383 switches in the ALI file are not used to compile the binder generated source.
9384 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9385 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9386 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9387 is taken into account. However, all the additional switches are also taken
9388 into account. Thus,
9389 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9390 @option{--GCC="bar -x -y -z -t"}.
9391
9392 @item --LINK=@var{name}
9393 @cindex @option{--LINK=} (@command{gnatlink})
9394 @var{name} is the name of the linker to be invoked. This is especially
9395 useful in mixed language programs since languages such as C++ require
9396 their own linker to be used. When this switch is omitted, the default
9397 name for the linker is @command{gcc}. When this switch is used, the
9398 specified linker is called instead of @command{gcc} with exactly the same
9399 parameters that would have been passed to @command{gcc} so if the desired
9400 linker requires different parameters it is necessary to use a wrapper
9401 script that massages the parameters before invoking the real linker. It
9402 may be useful to control the exact invocation by using the verbose
9403 switch.
9404
9405 @end ifclear
9406
9407 @ifset vms
9408 @item /DEBUG=TRACEBACK
9409 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9410 This qualifier causes sufficient information to be included in the
9411 executable file to allow a traceback, but does not include the full
9412 symbol information needed by the debugger.
9413
9414 @item /IDENTIFICATION="<string>"
9415 @code{"<string>"} specifies the string to be stored in the image file
9416 identification field in the image header.
9417 It overrides any pragma @code{Ident} specified string.
9418
9419 @item /NOINHIBIT-EXEC
9420 Generate the executable file even if there are linker warnings.
9421
9422 @item /NOSTART_FILES
9423 Don't link in the object file containing the ``main'' transfer address.
9424 Used when linking with a foreign language main program compiled with an
9425 HP compiler.
9426
9427 @item /STATIC
9428 Prefer linking with object libraries over sharable images, even without
9429 /DEBUG.
9430 @end ifset
9431
9432 @end table
9433
9434 @node The GNAT Make Program gnatmake
9435 @chapter The GNAT Make Program @command{gnatmake}
9436 @findex gnatmake
9437
9438 @menu
9439 * Running gnatmake::
9440 * Switches for gnatmake::
9441 * Mode Switches for gnatmake::
9442 * Notes on the Command Line::
9443 * How gnatmake Works::
9444 * Examples of gnatmake Usage::
9445 @end menu
9446 @noindent
9447 A typical development cycle when working on an Ada program consists of
9448 the following steps:
9449
9450 @enumerate
9451 @item
9452 Edit some sources to fix bugs.
9453
9454 @item
9455 Add enhancements.
9456
9457 @item
9458 Compile all sources affected.
9459
9460 @item
9461 Rebind and relink.
9462
9463 @item
9464 Test.
9465 @end enumerate
9466
9467 @noindent
9468 The third step can be tricky, because not only do the modified files
9469 @cindex Dependency rules
9470 have to be compiled, but any files depending on these files must also be
9471 recompiled. The dependency rules in Ada can be quite complex, especially
9472 in the presence of overloading, @code{use} clauses, generics and inlined
9473 subprograms.
9474
9475 @command{gnatmake} automatically takes care of the third and fourth steps
9476 of this process. It determines which sources need to be compiled,
9477 compiles them, and binds and links the resulting object files.
9478
9479 Unlike some other Ada make programs, the dependencies are always
9480 accurately recomputed from the new sources. The source based approach of
9481 the GNAT compilation model makes this possible. This means that if
9482 changes to the source program cause corresponding changes in
9483 dependencies, they will always be tracked exactly correctly by
9484 @command{gnatmake}.
9485
9486 @node Running gnatmake
9487 @section Running @command{gnatmake}
9488
9489 @noindent
9490 The usual form of the @command{gnatmake} command is
9491
9492 @smallexample
9493 @c $ gnatmake @ovar{switches} @var{file_name}
9494 @c @ovar{file_names} @ovar{mode_switches}
9495 @c Expanding @ovar macro inline (explanation in macro def comments)
9496 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9497 @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9498 @end smallexample
9499
9500 @noindent
9501 The only required argument is one @var{file_name}, which specifies
9502 a compilation unit that is a main program. Several @var{file_names} can be
9503 specified: this will result in several executables being built.
9504 If @code{switches} are present, they can be placed before the first
9505 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9506 If @var{mode_switches} are present, they must always be placed after
9507 the last @var{file_name} and all @code{switches}.
9508
9509 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9510 extension may be omitted from the @var{file_name} arguments. However, if
9511 you are using non-standard extensions, then it is required that the
9512 extension be given. A relative or absolute directory path can be
9513 specified in a @var{file_name}, in which case, the input source file will
9514 be searched for in the specified directory only. Otherwise, the input
9515 source file will first be searched in the directory where
9516 @command{gnatmake} was invoked and if it is not found, it will be search on
9517 the source path of the compiler as described in
9518 @ref{Search Paths and the Run-Time Library (RTL)}.
9519
9520 All @command{gnatmake} output (except when you specify
9521 @option{^-M^/DEPENDENCIES_LIST^}) is to
9522 @file{stderr}. The output produced by the
9523 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9524 @file{stdout}.
9525
9526 @node Switches for gnatmake
9527 @section Switches for @command{gnatmake}
9528
9529 @noindent
9530 You may specify any of the following switches to @command{gnatmake}:
9531
9532 @table @option
9533 @c !sort!
9534
9535 @item --version
9536 @cindex @option{--version} @command{gnatmake}
9537 Display Copyright and version, then exit disregarding all other options.
9538
9539 @item --help
9540 @cindex @option{--help} @command{gnatmake}
9541 If @option{--version} was not used, display usage, then exit disregarding
9542 all other options.
9543
9544 @ifclear vms
9545 @item --GCC=@var{compiler_name}
9546 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9547 Program used for compiling. The default is `@command{gcc}'. You need to use
9548 quotes around @var{compiler_name} if @code{compiler_name} contains
9549 spaces or other separator characters. As an example @option{--GCC="foo -x
9550 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9551 compiler. A limitation of this syntax is that the name and path name of
9552 the executable itself must not include any embedded spaces. Note that
9553 switch @option{-c} is always inserted after your command name. Thus in the
9554 above example the compiler command that will be used by @command{gnatmake}
9555 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9556 used, only the last @var{compiler_name} is taken into account. However,
9557 all the additional switches are also taken into account. Thus,
9558 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9559 @option{--GCC="bar -x -y -z -t"}.
9560
9561 @item --GNATBIND=@var{binder_name}
9562 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9563 Program used for binding. The default is `@code{gnatbind}'. You need to
9564 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9565 or other separator characters. As an example @option{--GNATBIND="bar -x
9566 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9567 binder. Binder switches that are normally appended by @command{gnatmake}
9568 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9569 A limitation of this syntax is that the name and path name of the executable
9570 itself must not include any embedded spaces.
9571
9572 @item --GNATLINK=@var{linker_name}
9573 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9574 Program used for linking. The default is `@command{gnatlink}'. You need to
9575 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9576 or other separator characters. As an example @option{--GNATLINK="lan -x
9577 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9578 linker. Linker switches that are normally appended by @command{gnatmake} to
9579 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9580 A limitation of this syntax is that the name and path name of the executable
9581 itself must not include any embedded spaces.
9582
9583 @end ifclear
9584
9585 @item ^--subdirs^/SUBDIRS^=subdir
9586 Actual object directory of each project file is the subdirectory subdir of the
9587 object directory specified or defaulted in the project file.
9588
9589 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9590 Disallow simultaneous compilations in the same object directory when
9591 project files are used.
9592
9593 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9594 By default, shared library projects are not allowed to import static library
9595 projects. When this switch is used on the command line, this restriction is
9596 relaxed.
9597
9598 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9599 Specify a source info file. This switch is active only when project files
9600 are used. If the source info file is specified as a relative path, then it is
9601 relative to the object directory of the main project. If the source info file
9602 does not exist, then after the Project Manager has successfully parsed and
9603 processed the project files and found the sources, it creates the source info
9604 file. If the source info file already exists and can be read successfully,
9605 then the Project Manager will get all the needed information about the sources
9606 from the source info file and will not look for them. This reduces the time
9607 to process the project files, especially when looking for sources that take a
9608 long time. If the source info file exists but cannot be parsed successfully,
9609 the Project Manager will attempt to recreate it. If the Project Manager fails
9610 to create the source info file, a message is issued, but gnatmake does not
9611 fail. @command{gnatmake} "trusts" the source info file. This means that
9612 if the source files have changed (addition, deletion, moving to a different
9613 source directory), then the source info file need to be deleted and recreated.
9614
9615 @ifclear vms
9616 @item --create-map-file
9617 When linking an executable, create a map file. The name of the map file
9618 has the same name as the executable with extension ".map".
9619
9620 @item --create-map-file=mapfile
9621 When linking an executable, create a map file. The name of the map file is
9622 "mapfile".
9623
9624 @end ifclear
9625
9626 @item ^-a^/ALL_FILES^
9627 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9628 Consider all files in the make process, even the GNAT internal system
9629 files (for example, the predefined Ada library files), as well as any
9630 locked files. Locked files are files whose ALI file is write-protected.
9631 By default,
9632 @command{gnatmake} does not check these files,
9633 because the assumption is that the GNAT internal files are properly up
9634 to date, and also that any write protected ALI files have been properly
9635 installed. Note that if there is an installation problem, such that one
9636 of these files is not up to date, it will be properly caught by the
9637 binder.
9638 You may have to specify this switch if you are working on GNAT
9639 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9640 in conjunction with @option{^-f^/FORCE_COMPILE^}
9641 if you need to recompile an entire application,
9642 including run-time files, using special configuration pragmas,
9643 such as a @code{Normalize_Scalars} pragma.
9644
9645 By default
9646 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9647 internal files with
9648 @ifclear vms
9649 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9650 @end ifclear
9651 @ifset vms
9652 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9653 @end ifset
9654
9655 @item ^-b^/ACTIONS=BIND^
9656 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9657 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9658 compilation and binding, but no link.
9659 Can be combined with @option{^-l^/ACTIONS=LINK^}
9660 to do binding and linking. When not combined with
9661 @option{^-c^/ACTIONS=COMPILE^}
9662 all the units in the closure of the main program must have been previously
9663 compiled and must be up to date. The root unit specified by @var{file_name}
9664 may be given without extension, with the source extension or, if no GNAT
9665 Project File is specified, with the ALI file extension.
9666
9667 @item ^-c^/ACTIONS=COMPILE^
9668 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9669 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9670 is also specified. Do not perform linking, except if both
9671 @option{^-b^/ACTIONS=BIND^} and
9672 @option{^-l^/ACTIONS=LINK^} are also specified.
9673 If the root unit specified by @var{file_name} is not a main unit, this is the
9674 default. Otherwise @command{gnatmake} will attempt binding and linking
9675 unless all objects are up to date and the executable is more recent than
9676 the objects.
9677
9678 @item ^-C^/MAPPING^
9679 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9680 Use a temporary mapping file. A mapping file is a way to communicate
9681 to the compiler two mappings: from unit names to file names (without
9682 any directory information) and from file names to path names (with
9683 full directory information). A mapping file can make the compiler's
9684 file searches faster, especially if there are many source directories,
9685 or the sources are read over a slow network connection. If
9686 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9687 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9688 is initially populated based on the project file. If
9689 @option{^-C^/MAPPING^} is used without
9690 @option{^-P^/PROJECT_FILE^},
9691 the mapping file is initially empty. Each invocation of the compiler
9692 will add any newly accessed sources to the mapping file.
9693
9694 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9695 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9696 Use a specific mapping file. The file, specified as a path name (absolute or
9697 relative) by this switch, should already exist, otherwise the switch is
9698 ineffective. The specified mapping file will be communicated to the compiler.
9699 This switch is not compatible with a project file
9700 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9701 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9702
9703 @item ^-d^/DISPLAY_PROGRESS^
9704 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9705 Display progress for each source, up to date or not, as a single line
9706
9707 @smallexample
9708 completed x out of y (zz%)
9709 @end smallexample
9710
9711 If the file needs to be compiled this is displayed after the invocation of
9712 the compiler. These lines are displayed even in quiet output mode.
9713
9714 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9715 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9716 Put all object files and ALI file in directory @var{dir}.
9717 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9718 and ALI files go in the current working directory.
9719
9720 This switch cannot be used when using a project file.
9721
9722 @item -eInnn
9723 @cindex @option{-eI} (@command{gnatmake})
9724 Indicates that the main source is a multi-unit source and the rank of the unit
9725 in the source file is nnn. nnn needs to be a positive number and a valid
9726 index in the source. This switch cannot be used when @command{gnatmake} is
9727 invoked for several mains.
9728
9729 @ifclear vms
9730 @item -eL
9731 @cindex @option{-eL} (@command{gnatmake})
9732 @cindex symbolic links
9733 Follow all symbolic links when processing project files.
9734 This should be used if your project uses symbolic links for files or
9735 directories, but is not needed in other cases.
9736
9737 @cindex naming scheme
9738 This also assumes that no directory matches the naming scheme for files (for
9739 instance that you do not have a directory called "sources.ads" when using the
9740 default GNAT naming scheme).
9741
9742 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9743 save a lot of system calls (several per source file and object file), which
9744 can result in a significant speed up to load and manipulate a project file,
9745 especially when using source files from a remote system.
9746
9747 @end ifclear
9748
9749 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9750 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9751 Output the commands for the compiler, the binder and the linker
9752 on ^standard output^SYS$OUTPUT^,
9753 instead of ^standard error^SYS$ERROR^.
9754
9755 @item ^-f^/FORCE_COMPILE^
9756 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9757 Force recompilations. Recompile all sources, even though some object
9758 files may be up to date, but don't recompile predefined or GNAT internal
9759 files or locked files (files with a write-protected ALI file),
9760 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9761
9762 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9763 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9764 When using project files, if some errors or warnings are detected during
9765 parsing and verbose mode is not in effect (no use of switch
9766 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9767 file, rather than its simple file name.
9768
9769 @item ^-g^/DEBUG^
9770 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9771 Enable debugging. This switch is simply passed to the compiler and to the
9772 linker.
9773
9774 @item ^-i^/IN_PLACE^
9775 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9776 In normal mode, @command{gnatmake} compiles all object files and ALI files
9777 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9778 then instead object files and ALI files that already exist are overwritten
9779 in place. This means that once a large project is organized into separate
9780 directories in the desired manner, then @command{gnatmake} will automatically
9781 maintain and update this organization. If no ALI files are found on the
9782 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9783 the new object and ALI files are created in the
9784 directory containing the source being compiled. If another organization
9785 is desired, where objects and sources are kept in different directories,
9786 a useful technique is to create dummy ALI files in the desired directories.
9787 When detecting such a dummy file, @command{gnatmake} will be forced to
9788 recompile the corresponding source file, and it will be put the resulting
9789 object and ALI files in the directory where it found the dummy file.
9790
9791 @item ^-j^/PROCESSES=^@var{n}
9792 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9793 @cindex Parallel make
9794 Use @var{n} processes to carry out the (re)compilations. On a multiprocessor
9795 machine compilations will occur in parallel. If @var{n} is 0, then the
9796 maximum number of parallel compilations is the number of core processors
9797 on the platform. In the event of compilation errors, messages from various
9798 compilations might get interspersed (but @command{gnatmake} will give you the
9799 full ordered list of failing compiles at the end). If this is problematic,
9800 rerun the make process with n set to 1 to get a clean list of messages.
9801
9802 @item ^-k^/CONTINUE_ON_ERROR^
9803 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9804 Keep going. Continue as much as possible after a compilation error. To
9805 ease the programmer's task in case of compilation errors, the list of
9806 sources for which the compile fails is given when @command{gnatmake}
9807 terminates.
9808
9809 If @command{gnatmake} is invoked with several @file{file_names} and with this
9810 switch, if there are compilation errors when building an executable,
9811 @command{gnatmake} will not attempt to build the following executables.
9812
9813 @item ^-l^/ACTIONS=LINK^
9814 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9815 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9816 and linking. Linking will not be performed if combined with
9817 @option{^-c^/ACTIONS=COMPILE^}
9818 but not with @option{^-b^/ACTIONS=BIND^}.
9819 When not combined with @option{^-b^/ACTIONS=BIND^}
9820 all the units in the closure of the main program must have been previously
9821 compiled and must be up to date, and the main program needs to have been bound.
9822 The root unit specified by @var{file_name}
9823 may be given without extension, with the source extension or, if no GNAT
9824 Project File is specified, with the ALI file extension.
9825
9826 @item ^-m^/MINIMAL_RECOMPILATION^
9827 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9828 Specify that the minimum necessary amount of recompilations
9829 be performed. In this mode @command{gnatmake} ignores time
9830 stamp differences when the only
9831 modifications to a source file consist in adding/removing comments,
9832 empty lines, spaces or tabs. This means that if you have changed the
9833 comments in a source file or have simply reformatted it, using this
9834 switch will tell @command{gnatmake} not to recompile files that depend on it
9835 (provided other sources on which these files depend have undergone no
9836 semantic modifications). Note that the debugging information may be
9837 out of date with respect to the sources if the @option{-m} switch causes
9838 a compilation to be switched, so the use of this switch represents a
9839 trade-off between compilation time and accurate debugging information.
9840
9841 @item ^-M^/DEPENDENCIES_LIST^
9842 @cindex Dependencies, producing list
9843 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9844 Check if all objects are up to date. If they are, output the object
9845 dependences to @file{stdout} in a form that can be directly exploited in
9846 a @file{Makefile}. By default, each source file is prefixed with its
9847 (relative or absolute) directory name. This name is whatever you
9848 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9849 and @option{^-I^/SEARCH^} switches. If you use
9850 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9851 @option{^-q^/QUIET^}
9852 (see below), only the source file names,
9853 without relative paths, are output. If you just specify the
9854 @option{^-M^/DEPENDENCIES_LIST^}
9855 switch, dependencies of the GNAT internal system files are omitted. This
9856 is typically what you want. If you also specify
9857 the @option{^-a^/ALL_FILES^} switch,
9858 dependencies of the GNAT internal files are also listed. Note that
9859 dependencies of the objects in external Ada libraries (see switch
9860 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9861 are never reported.
9862
9863 @item ^-n^/DO_OBJECT_CHECK^
9864 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9865 Don't compile, bind, or link. Checks if all objects are up to date.
9866 If they are not, the full name of the first file that needs to be
9867 recompiled is printed.
9868 Repeated use of this option, followed by compiling the indicated source
9869 file, will eventually result in recompiling all required units.
9870
9871 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9872 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9873 Output executable name. The name of the final executable program will be
9874 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9875 name for the executable will be the name of the input file in appropriate form
9876 for an executable file on the host system.
9877
9878 This switch cannot be used when invoking @command{gnatmake} with several
9879 @file{file_names}.
9880
9881 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9882 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9883 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9884 automatically missing object directories, library directories and exec
9885 directories.
9886
9887 @item ^-P^/PROJECT_FILE=^@var{project}
9888 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9889 Use project file @var{project}. Only one such switch can be used.
9890 @xref{gnatmake and Project Files}.
9891
9892 @item ^-q^/QUIET^
9893 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9894 Quiet. When this flag is not set, the commands carried out by
9895 @command{gnatmake} are displayed.
9896
9897 @item ^-s^/SWITCH_CHECK/^
9898 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9899 Recompile if compiler switches have changed since last compilation.
9900 All compiler switches but -I and -o are taken into account in the
9901 following way:
9902 orders between different ``first letter'' switches are ignored, but
9903 orders between same switches are taken into account. For example,
9904 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9905 is equivalent to @option{-O -g}.
9906
9907 This switch is recommended when Integrated Preprocessing is used.
9908
9909 @item ^-u^/UNIQUE^
9910 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9911 Unique. Recompile at most the main files. It implies -c. Combined with
9912 -f, it is equivalent to calling the compiler directly. Note that using
9913 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9914 (@pxref{Project Files and Main Subprograms}).
9915
9916 @item ^-U^/ALL_PROJECTS^
9917 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9918 When used without a project file or with one or several mains on the command
9919 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9920 on the command line, all sources of all project files are checked and compiled
9921 if not up to date, and libraries are rebuilt, if necessary.
9922
9923 @item ^-v^/REASONS^
9924 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9925 Verbose. Display the reason for all recompilations @command{gnatmake}
9926 decides are necessary, with the highest verbosity level.
9927
9928 @item ^-vl^/LOW_VERBOSITY^
9929 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9930 Verbosity level Low. Display fewer lines than in verbosity Medium.
9931
9932 @item ^-vm^/MEDIUM_VERBOSITY^
9933 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9934 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9935
9936 @item ^-vh^/HIGH_VERBOSITY^
9937 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9938 Verbosity level High. Equivalent to ^-v^/REASONS^.
9939
9940 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9941 Indicate the verbosity of the parsing of GNAT project files.
9942 @xref{Switches Related to Project Files}.
9943
9944 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9945 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9946 Indicate that sources that are not part of any Project File may be compiled.
9947 Normally, when using Project Files, only sources that are part of a Project
9948 File may be compile. When this switch is used, a source outside of all Project
9949 Files may be compiled. The ALI file and the object file will be put in the
9950 object directory of the main Project. The compilation switches used will only
9951 be those specified on the command line. Even when
9952 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9953 command line need to be sources of a project file.
9954
9955 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9956 Indicate that external variable @var{name} has the value @var{value}.
9957 The Project Manager will use this value for occurrences of
9958 @code{external(name)} when parsing the project file.
9959 @xref{Switches Related to Project Files}.
9960
9961 @item ^-z^/NOMAIN^
9962 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9963 No main subprogram. Bind and link the program even if the unit name
9964 given on the command line is a package name. The resulting executable
9965 will execute the elaboration routines of the package and its closure,
9966 then the finalization routines.
9967
9968 @end table
9969
9970 @table @asis
9971 @item @command{gcc} @asis{switches}
9972 @ifclear vms
9973 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9974 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9975 @end ifclear
9976 @ifset vms
9977 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9978 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9979 automatically treated as a compiler switch, and passed on to all
9980 compilations that are carried out.
9981 @end ifset
9982 @end table
9983
9984 @noindent
9985 Source and library search path switches:
9986
9987 @table @option
9988 @c !sort!
9989 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9990 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9991 When looking for source files also look in directory @var{dir}.
9992 The order in which source files search is undertaken is
9993 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9994
9995 @item ^-aL^/SKIP_MISSING=^@var{dir}
9996 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9997 Consider @var{dir} as being an externally provided Ada library.
9998 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9999 files have been located in directory @var{dir}. This allows you to have
10000 missing bodies for the units in @var{dir} and to ignore out of date bodies
10001 for the same units. You still need to specify
10002 the location of the specs for these units by using the switches
10003 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
10004 or @option{^-I^/SEARCH=^@var{dir}}.
10005 Note: this switch is provided for compatibility with previous versions
10006 of @command{gnatmake}. The easier method of causing standard libraries
10007 to be excluded from consideration is to write-protect the corresponding
10008 ALI files.
10009
10010 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
10011 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
10012 When searching for library and object files, look in directory
10013 @var{dir}. The order in which library files are searched is described in
10014 @ref{Search Paths for gnatbind}.
10015
10016 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
10017 @cindex Search paths, for @command{gnatmake}
10018 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
10019 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
10020 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
10021
10022 @item ^-I^/SEARCH=^@var{dir}
10023 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
10024 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
10025 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
10026
10027 @item ^-I-^/NOCURRENT_DIRECTORY^
10028 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
10029 @cindex Source files, suppressing search
10030 Do not look for source files in the directory containing the source
10031 file named in the command line.
10032 Do not look for ALI or object files in the directory
10033 where @command{gnatmake} was invoked.
10034
10035 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
10036 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
10037 @cindex Linker libraries
10038 Add directory @var{dir} to the list of directories in which the linker
10039 will search for libraries. This is equivalent to
10040 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
10041 @ifclear vms
10042 Furthermore, under Windows, the sources pointed to by the libraries path
10043 set in the registry are not searched for.
10044 @end ifclear
10045
10046 @item -nostdinc
10047 @cindex @option{-nostdinc} (@command{gnatmake})
10048 Do not look for source files in the system default directory.
10049
10050 @item -nostdlib
10051 @cindex @option{-nostdlib} (@command{gnatmake})
10052 Do not look for library files in the system default directory.
10053
10054 @item --RTS=@var{rts-path}
10055 @cindex @option{--RTS} (@command{gnatmake})
10056 Specifies the default location of the runtime library. GNAT looks for the
10057 runtime
10058 in the following directories, and stops as soon as a valid runtime is found
10059 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
10060 @file{ada_object_path} present):
10061
10062 @itemize @bullet
10063 @item <current directory>/$rts_path
10064
10065 @item <default-search-dir>/$rts_path
10066
10067 @item <default-search-dir>/rts-$rts_path
10068 @end itemize
10069
10070 @noindent
10071 The selected path is handled like a normal RTS path.
10072
10073 @end table
10074
10075 @node Mode Switches for gnatmake
10076 @section Mode Switches for @command{gnatmake}
10077
10078 @noindent
10079 The mode switches (referred to as @code{mode_switches}) allow the
10080 inclusion of switches that are to be passed to the compiler itself, the
10081 binder or the linker. The effect of a mode switch is to cause all
10082 subsequent switches up to the end of the switch list, or up to the next
10083 mode switch, to be interpreted as switches to be passed on to the
10084 designated component of GNAT.
10085
10086 @table @option
10087 @c !sort!
10088 @item -cargs @var{switches}
10089 @cindex @option{-cargs} (@command{gnatmake})
10090 Compiler switches. Here @var{switches} is a list of switches
10091 that are valid switches for @command{gcc}. They will be passed on to
10092 all compile steps performed by @command{gnatmake}.
10093
10094 @item -bargs @var{switches}
10095 @cindex @option{-bargs} (@command{gnatmake})
10096 Binder switches. Here @var{switches} is a list of switches
10097 that are valid switches for @code{gnatbind}. They will be passed on to
10098 all bind steps performed by @command{gnatmake}.
10099
10100 @item -largs @var{switches}
10101 @cindex @option{-largs} (@command{gnatmake})
10102 Linker switches. Here @var{switches} is a list of switches
10103 that are valid switches for @command{gnatlink}. They will be passed on to
10104 all link steps performed by @command{gnatmake}.
10105
10106 @item -margs @var{switches}
10107 @cindex @option{-margs} (@command{gnatmake})
10108 Make switches. The switches are directly interpreted by @command{gnatmake},
10109 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
10110 or @option{-largs}.
10111 @end table
10112
10113 @node Notes on the Command Line
10114 @section Notes on the Command Line
10115
10116 @noindent
10117 This section contains some additional useful notes on the operation
10118 of the @command{gnatmake} command.
10119
10120 @itemize @bullet
10121 @item
10122 @cindex Recompilation, by @command{gnatmake}
10123 If @command{gnatmake} finds no ALI files, it recompiles the main program
10124 and all other units required by the main program.
10125 This means that @command{gnatmake}
10126 can be used for the initial compile, as well as during subsequent steps of
10127 the development cycle.
10128
10129 @item
10130 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
10131 is a subunit or body of a generic unit, @command{gnatmake} recompiles
10132 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
10133 warning.
10134
10135 @item
10136 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
10137 is used to specify both source and
10138 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
10139 instead if you just want to specify
10140 source paths only and @option{^-aO^/OBJECT_SEARCH^}
10141 if you want to specify library paths
10142 only.
10143
10144 @item
10145 @command{gnatmake} will ignore any files whose ALI file is write-protected.
10146 This may conveniently be used to exclude standard libraries from
10147 consideration and in particular it means that the use of the
10148 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
10149 unless @option{^-a^/ALL_FILES^} is also specified.
10150
10151 @item
10152 @command{gnatmake} has been designed to make the use of Ada libraries
10153 particularly convenient. Assume you have an Ada library organized
10154 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
10155 of your Ada compilation units,
10156 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
10157 specs of these units, but no bodies. Then to compile a unit
10158 stored in @code{main.adb}, which uses this Ada library you would just type
10159
10160 @smallexample
10161 @ifclear vms
10162 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
10163 @end ifclear
10164 @ifset vms
10165 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
10166 /SKIP_MISSING=@i{[OBJ_DIR]} main
10167 @end ifset
10168 @end smallexample
10169
10170 @item
10171 Using @command{gnatmake} along with the
10172 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
10173 switch provides a mechanism for avoiding unnecessary recompilations. Using
10174 this switch,
10175 you can update the comments/format of your
10176 source files without having to recompile everything. Note, however, that
10177 adding or deleting lines in a source files may render its debugging
10178 info obsolete. If the file in question is a spec, the impact is rather
10179 limited, as that debugging info will only be useful during the
10180 elaboration phase of your program. For bodies the impact can be more
10181 significant. In all events, your debugger will warn you if a source file
10182 is more recent than the corresponding object, and alert you to the fact
10183 that the debugging information may be out of date.
10184 @end itemize
10185
10186 @node How gnatmake Works
10187 @section How @command{gnatmake} Works
10188
10189 @noindent
10190 Generally @command{gnatmake} automatically performs all necessary
10191 recompilations and you don't need to worry about how it works. However,
10192 it may be useful to have some basic understanding of the @command{gnatmake}
10193 approach and in particular to understand how it uses the results of
10194 previous compilations without incorrectly depending on them.
10195
10196 First a definition: an object file is considered @dfn{up to date} if the
10197 corresponding ALI file exists and if all the source files listed in the
10198 dependency section of this ALI file have time stamps matching those in
10199 the ALI file. This means that neither the source file itself nor any
10200 files that it depends on have been modified, and hence there is no need
10201 to recompile this file.
10202
10203 @command{gnatmake} works by first checking if the specified main unit is up
10204 to date. If so, no compilations are required for the main unit. If not,
10205 @command{gnatmake} compiles the main program to build a new ALI file that
10206 reflects the latest sources. Then the ALI file of the main unit is
10207 examined to find all the source files on which the main program depends,
10208 and @command{gnatmake} recursively applies the above procedure on all these
10209 files.
10210
10211 This process ensures that @command{gnatmake} only trusts the dependencies
10212 in an existing ALI file if they are known to be correct. Otherwise it
10213 always recompiles to determine a new, guaranteed accurate set of
10214 dependencies. As a result the program is compiled ``upside down'' from what may
10215 be more familiar as the required order of compilation in some other Ada
10216 systems. In particular, clients are compiled before the units on which
10217 they depend. The ability of GNAT to compile in any order is critical in
10218 allowing an order of compilation to be chosen that guarantees that
10219 @command{gnatmake} will recompute a correct set of new dependencies if
10220 necessary.
10221
10222 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
10223 imported by several of the executables, it will be recompiled at most once.
10224
10225 Note: when using non-standard naming conventions
10226 (@pxref{Using Other File Names}), changing through a configuration pragmas
10227 file the version of a source and invoking @command{gnatmake} to recompile may
10228 have no effect, if the previous version of the source is still accessible
10229 by @command{gnatmake}. It may be necessary to use the switch
10230 ^-f^/FORCE_COMPILE^.
10231
10232 @node Examples of gnatmake Usage
10233 @section Examples of @command{gnatmake} Usage
10234
10235 @table @code
10236 @item gnatmake hello.adb
10237 Compile all files necessary to bind and link the main program
10238 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
10239 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
10240
10241 @item gnatmake main1 main2 main3
10242 Compile all files necessary to bind and link the main programs
10243 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
10244 (containing unit @code{Main2}) and @file{main3.adb}
10245 (containing unit @code{Main3}) and bind and link the resulting object files
10246 to generate three executable files @file{^main1^MAIN1.EXE^},
10247 @file{^main2^MAIN2.EXE^}
10248 and @file{^main3^MAIN3.EXE^}.
10249
10250 @ifclear vms
10251 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10252 @end ifclear
10253
10254 @ifset vms
10255 @item gnatmake Main_Unit /QUIET
10256 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10257 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10258 @end ifset
10259 Compile all files necessary to bind and link the main program unit
10260 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10261 be done with optimization level 2 and the order of elaboration will be
10262 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10263 displaying commands it is executing.
10264 @end table
10265
10266 @c *************************
10267 @node Improving Performance
10268 @chapter Improving Performance
10269 @cindex Improving performance
10270
10271 @noindent
10272 This chapter presents several topics related to program performance.
10273 It first describes some of the tradeoffs that need to be considered
10274 and some of the techniques for making your program run faster.
10275 It then documents
10276 @ifclear FSFEDITION
10277 the @command{gnatelim} tool and
10278 @end ifclear
10279 unused subprogram/data
10280 elimination feature, which can reduce the size of program executables.
10281
10282 @ifnottex
10283 @menu
10284 * Performance Considerations::
10285 * Text_IO Suggestions::
10286 @ifclear FSFEDITION
10287 * Reducing Size of Ada Executables with gnatelim::
10288 @end ifclear
10289 * Reducing Size of Executables with unused subprogram/data elimination::
10290 @end menu
10291 @end ifnottex
10292
10293 @c *****************************
10294 @node Performance Considerations
10295 @section Performance Considerations
10296
10297 @noindent
10298 The GNAT system provides a number of options that allow a trade-off
10299 between
10300
10301 @itemize @bullet
10302 @item
10303 performance of the generated code
10304
10305 @item
10306 speed of compilation
10307
10308 @item
10309 minimization of dependences and recompilation
10310
10311 @item
10312 the degree of run-time checking.
10313 @end itemize
10314
10315 @noindent
10316 The defaults (if no options are selected) aim at improving the speed
10317 of compilation and minimizing dependences, at the expense of performance
10318 of the generated code:
10319
10320 @itemize @bullet
10321 @item
10322 no optimization
10323
10324 @item
10325 no inlining of subprogram calls
10326
10327 @item
10328 all run-time checks enabled except overflow and elaboration checks
10329 @end itemize
10330
10331 @noindent
10332 These options are suitable for most program development purposes. This
10333 chapter describes how you can modify these choices, and also provides
10334 some guidelines on debugging optimized code.
10335
10336 @menu
10337 * Controlling Run-Time Checks::
10338 * Use of Restrictions::
10339 * Optimization Levels::
10340 * Debugging Optimized Code::
10341 * Inlining of Subprograms::
10342 * Vectorization of loops::
10343 * Other Optimization Switches::
10344 * Optimization and Strict Aliasing::
10345 * Aliased Variables and Optimization::
10346 * Atomic Variables and Optimization::
10347 * Passive Task Optimization::
10348
10349 @ifset vms
10350 * Coverage Analysis::
10351 @end ifset
10352 @end menu
10353
10354 @node Controlling Run-Time Checks
10355 @subsection Controlling Run-Time Checks
10356
10357 @noindent
10358 By default, GNAT generates all run-time checks, except integer overflow
10359 checks, stack overflow checks, and checks for access before elaboration on
10360 subprogram calls. The latter are not required in default mode, because all
10361 necessary checking is done at compile time.
10362 @cindex @option{-gnatp} (@command{gcc})
10363 @cindex @option{-gnato} (@command{gcc})
10364 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10365 be modified. @xref{Run-Time Checks}.
10366
10367 Our experience is that the default is suitable for most development
10368 purposes.
10369
10370 We treat integer overflow specially because these
10371 are quite expensive and in our experience are not as important as other
10372 run-time checks in the development process. Note that division by zero
10373 is not considered an overflow check, and divide by zero checks are
10374 generated where required by default.
10375
10376 Elaboration checks are off by default, and also not needed by default, since
10377 GNAT uses a static elaboration analysis approach that avoids the need for
10378 run-time checking. This manual contains a full chapter discussing the issue
10379 of elaboration checks, and if the default is not satisfactory for your use,
10380 you should read this chapter.
10381
10382 For validity checks, the minimal checks required by the Ada Reference
10383 Manual (for case statements and assignments to array elements) are on
10384 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10385 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10386 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10387 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10388 are also suppressed entirely if @option{-gnatp} is used.
10389
10390 @cindex Overflow checks
10391 @cindex Checks, overflow
10392 @findex Suppress
10393 @findex Unsuppress
10394 @cindex pragma Suppress
10395 @cindex pragma Unsuppress
10396 Note that the setting of the switches controls the default setting of
10397 the checks. They may be modified using either @code{pragma Suppress} (to
10398 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10399 checks) in the program source.
10400
10401 @node Use of Restrictions
10402 @subsection Use of Restrictions
10403
10404 @noindent
10405 The use of pragma Restrictions allows you to control which features are
10406 permitted in your program. Apart from the obvious point that if you avoid
10407 relatively expensive features like finalization (enforceable by the use
10408 of pragma Restrictions (No_Finalization), the use of this pragma does not
10409 affect the generated code in most cases.
10410
10411 One notable exception to this rule is that the possibility of task abort
10412 results in some distributed overhead, particularly if finalization or
10413 exception handlers are used. The reason is that certain sections of code
10414 have to be marked as non-abortable.
10415
10416 If you use neither the @code{abort} statement, nor asynchronous transfer
10417 of control (@code{select @dots{} then abort}), then this distributed overhead
10418 is removed, which may have a general positive effect in improving
10419 overall performance. Especially code involving frequent use of tasking
10420 constructs and controlled types will show much improved performance.
10421 The relevant restrictions pragmas are
10422
10423 @smallexample @c ada
10424 pragma Restrictions (No_Abort_Statements);
10425 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10426 @end smallexample
10427
10428 @noindent
10429 It is recommended that these restriction pragmas be used if possible. Note
10430 that this also means that you can write code without worrying about the
10431 possibility of an immediate abort at any point.
10432
10433 @node Optimization Levels
10434 @subsection Optimization Levels
10435 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10436
10437 @noindent
10438 Without any optimization ^option,^qualifier,^
10439 the compiler's goal is to reduce the cost of
10440 compilation and to make debugging produce the expected results.
10441 Statements are independent: if you stop the program with a breakpoint between
10442 statements, you can then assign a new value to any variable or change
10443 the program counter to any other statement in the subprogram and get exactly
10444 the results you would expect from the source code.
10445
10446 Turning on optimization makes the compiler attempt to improve the
10447 performance and/or code size at the expense of compilation time and
10448 possibly the ability to debug the program.
10449
10450 If you use multiple
10451 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10452 the last such option is the one that is effective.
10453
10454 @noindent
10455 The default is optimization off. This results in the fastest compile
10456 times, but GNAT makes absolutely no attempt to optimize, and the
10457 generated programs are considerably larger and slower than when
10458 optimization is enabled. You can use the
10459 @ifclear vms
10460 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10461 @option{-O2}, @option{-O3}, and @option{-Os})
10462 @end ifclear
10463 @ifset vms
10464 @code{OPTIMIZE} qualifier
10465 @end ifset
10466 to @command{gcc} to control the optimization level:
10467
10468 @table @option
10469 @item ^-O0^/OPTIMIZE=NONE^
10470 No optimization (the default);
10471 generates unoptimized code but has
10472 the fastest compilation time.
10473
10474 Note that many other compilers do fairly extensive optimization
10475 even if ``no optimization'' is specified. With gcc, it is
10476 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10477 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10478 really does mean no optimization at all. This difference between
10479 gcc and other compilers should be kept in mind when doing
10480 performance comparisons.
10481
10482 @item ^-O1^/OPTIMIZE=SOME^
10483 Moderate optimization;
10484 optimizes reasonably well but does not
10485 degrade compilation time significantly.
10486
10487 @item ^-O2^/OPTIMIZE=ALL^
10488 @ifset vms
10489 @itemx /OPTIMIZE=DEVELOPMENT
10490 @end ifset
10491 Full optimization;
10492 generates highly optimized code and has
10493 the slowest compilation time.
10494
10495 @item ^-O3^/OPTIMIZE=INLINING^
10496 Full optimization as in @option{-O2};
10497 also uses more aggressive automatic inlining of subprograms within a unit
10498 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10499
10500 @item ^-Os^/OPTIMIZE=SPACE^
10501 Optimize space usage (code and data) of resulting program.
10502 @end table
10503
10504 @noindent
10505 Higher optimization levels perform more global transformations on the
10506 program and apply more expensive analysis algorithms in order to generate
10507 faster and more compact code. The price in compilation time, and the
10508 resulting improvement in execution time,
10509 both depend on the particular application and the hardware environment.
10510 You should experiment to find the best level for your application.
10511
10512 Since the precise set of optimizations done at each level will vary from
10513 release to release (and sometime from target to target), it is best to think
10514 of the optimization settings in general terms.
10515 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10516 the GNU Compiler Collection (GCC)}, for details about
10517 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10518 individually enable or disable specific optimizations.
10519
10520 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10521 been tested extensively at all optimization levels. There are some bugs
10522 which appear only with optimization turned on, but there have also been
10523 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10524 level of optimization does not improve the reliability of the code
10525 generator, which in practice is highly reliable at all optimization
10526 levels.
10527
10528 Note regarding the use of @option{-O3}: The use of this optimization level
10529 is generally discouraged with GNAT, since it often results in larger
10530 executables which may run more slowly. See further discussion of this point
10531 in @ref{Inlining of Subprograms}.
10532
10533 @node Debugging Optimized Code
10534 @subsection Debugging Optimized Code
10535 @cindex Debugging optimized code
10536 @cindex Optimization and debugging
10537
10538 @noindent
10539 Although it is possible to do a reasonable amount of debugging at
10540 @ifclear vms
10541 nonzero optimization levels,
10542 the higher the level the more likely that
10543 @end ifclear
10544 @ifset vms
10545 @option{/OPTIMIZE} settings other than @code{NONE},
10546 such settings will make it more likely that
10547 @end ifset
10548 source-level constructs will have been eliminated by optimization.
10549 For example, if a loop is strength-reduced, the loop
10550 control variable may be completely eliminated and thus cannot be
10551 displayed in the debugger.
10552 This can only happen at @option{-O2} or @option{-O3}.
10553 Explicit temporary variables that you code might be eliminated at
10554 ^level^setting^ @option{-O1} or higher.
10555
10556 The use of the @option{^-g^/DEBUG^} switch,
10557 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10558 which is needed for source-level debugging,
10559 affects the size of the program executable on disk,
10560 and indeed the debugging information can be quite large.
10561 However, it has no effect on the generated code (and thus does not
10562 degrade performance)
10563
10564 Since the compiler generates debugging tables for a compilation unit before
10565 it performs optimizations, the optimizing transformations may invalidate some
10566 of the debugging data. You therefore need to anticipate certain
10567 anomalous situations that may arise while debugging optimized code.
10568 These are the most common cases:
10569
10570 @enumerate
10571 @item
10572 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
10573 commands show
10574 the PC bouncing back and forth in the code. This may result from any of
10575 the following optimizations:
10576
10577 @itemize @bullet
10578 @item
10579 @i{Common subexpression elimination:} using a single instance of code for a
10580 quantity that the source computes several times. As a result you
10581 may not be able to stop on what looks like a statement.
10582
10583 @item
10584 @i{Invariant code motion:} moving an expression that does not change within a
10585 loop, to the beginning of the loop.
10586
10587 @item
10588 @i{Instruction scheduling:} moving instructions so as to
10589 overlap loads and stores (typically) with other code, or in
10590 general to move computations of values closer to their uses. Often
10591 this causes you to pass an assignment statement without the assignment
10592 happening and then later bounce back to the statement when the
10593 value is actually needed. Placing a breakpoint on a line of code
10594 and then stepping over it may, therefore, not always cause all the
10595 expected side-effects.
10596 @end itemize
10597
10598 @item
10599 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10600 two identical pieces of code are merged and the program counter suddenly
10601 jumps to a statement that is not supposed to be executed, simply because
10602 it (and the code following) translates to the same thing as the code
10603 that @emph{was} supposed to be executed. This effect is typically seen in
10604 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10605 a @code{break} in a C @code{^switch^switch^} statement.
10606
10607 @item
10608 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10609 There are various reasons for this effect:
10610
10611 @itemize @bullet
10612 @item
10613 In a subprogram prologue, a parameter may not yet have been moved to its
10614 ``home''.
10615
10616 @item
10617 A variable may be dead, and its register re-used. This is
10618 probably the most common cause.
10619
10620 @item
10621 As mentioned above, the assignment of a value to a variable may
10622 have been moved.
10623
10624 @item
10625 A variable may be eliminated entirely by value propagation or
10626 other means. In this case, GCC may incorrectly generate debugging
10627 information for the variable
10628 @end itemize
10629
10630 @noindent
10631 In general, when an unexpected value appears for a local variable or parameter
10632 you should first ascertain if that value was actually computed by
10633 your program, as opposed to being incorrectly reported by the debugger.
10634 Record fields or
10635 array elements in an object designated by an access value
10636 are generally less of a problem, once you have ascertained that the access
10637 value is sensible.
10638 Typically, this means checking variables in the preceding code and in the
10639 calling subprogram to verify that the value observed is explainable from other
10640 values (one must apply the procedure recursively to those
10641 other values); or re-running the code and stopping a little earlier
10642 (perhaps before the call) and stepping to better see how the variable obtained
10643 the value in question; or continuing to step @emph{from} the point of the
10644 strange value to see if code motion had simply moved the variable's
10645 assignments later.
10646 @end enumerate
10647
10648 @noindent
10649 In light of such anomalies, a recommended technique is to use @option{-O0}
10650 early in the software development cycle, when extensive debugging capabilities
10651 are most needed, and then move to @option{-O1} and later @option{-O2} as
10652 the debugger becomes less critical.
10653 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10654 a release management issue.
10655 @ifclear vms
10656 Note that if you use @option{-g} you can then use the @command{strip} program
10657 on the resulting executable,
10658 which removes both debugging information and global symbols.
10659 @end ifclear
10660
10661 @node Inlining of Subprograms
10662 @subsection Inlining of Subprograms
10663
10664 @noindent
10665 A call to a subprogram in the current unit is inlined if all the
10666 following conditions are met:
10667
10668 @itemize @bullet
10669 @item
10670 The optimization level is at least @option{-O1}.
10671
10672 @item
10673 The called subprogram is suitable for inlining: It must be small enough
10674 and not contain something that @command{gcc} cannot support in inlined
10675 subprograms.
10676
10677 @item
10678 @cindex pragma Inline
10679 @findex Inline
10680 Any one of the following applies: @code{pragma Inline} is applied to the
10681 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10682 subprogram is local to the unit and called once from within it; the
10683 subprogram is small and optimization level @option{-O2} is specified;
10684 optimization level @option{-O3} is specified.
10685 @end itemize
10686
10687 @noindent
10688 Calls to subprograms in @code{with}'ed units are normally not inlined.
10689 To achieve actual inlining (that is, replacement of the call by the code
10690 in the body of the subprogram), the following conditions must all be true:
10691
10692 @itemize @bullet
10693 @item
10694 The optimization level is at least @option{-O1}.
10695
10696 @item
10697 The called subprogram is suitable for inlining: It must be small enough
10698 and not contain something that @command{gcc} cannot support in inlined
10699 subprograms.
10700
10701 @item
10702 The call appears in a body (not in a package spec).
10703
10704 @item
10705 There is a @code{pragma Inline} for the subprogram.
10706
10707 @item
10708 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10709 @end itemize
10710
10711 Even if all these conditions are met, it may not be possible for
10712 the compiler to inline the call, due to the length of the body,
10713 or features in the body that make it impossible for the compiler
10714 to do the inlining.
10715
10716 Note that specifying the @option{-gnatn} switch causes additional
10717 compilation dependencies. Consider the following:
10718
10719 @smallexample @c ada
10720 @cartouche
10721 package R is
10722 procedure Q;
10723 pragma Inline (Q);
10724 end R;
10725 package body R is
10726 @dots{}
10727 end R;
10728
10729 with R;
10730 procedure Main is
10731 begin
10732 @dots{}
10733 R.Q;
10734 end Main;
10735 @end cartouche
10736 @end smallexample
10737
10738 @noindent
10739 With the default behavior (no @option{-gnatn} switch specified), the
10740 compilation of the @code{Main} procedure depends only on its own source,
10741 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10742 means that editing the body of @code{R} does not require recompiling
10743 @code{Main}.
10744
10745 On the other hand, the call @code{R.Q} is not inlined under these
10746 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10747 is compiled, the call will be inlined if the body of @code{Q} is small
10748 enough, but now @code{Main} depends on the body of @code{R} in
10749 @file{r.adb} as well as on the spec. This means that if this body is edited,
10750 the main program must be recompiled. Note that this extra dependency
10751 occurs whether or not the call is in fact inlined by @command{gcc}.
10752
10753 The use of front end inlining with @option{-gnatN} generates similar
10754 additional dependencies.
10755
10756 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10757 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10758 can be used to prevent
10759 all inlining. This switch overrides all other conditions and ensures
10760 that no inlining occurs. The extra dependences resulting from
10761 @option{-gnatn} will still be active, even if
10762 this switch is used to suppress the resulting inlining actions.
10763
10764 @cindex @option{-fno-inline-functions} (@command{gcc})
10765 Note: The @option{-fno-inline-functions} switch can be used to prevent
10766 automatic inlining of subprograms if @option{-O3} is used.
10767
10768 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10769 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10770 automatic inlining of small subprograms if @option{-O2} is used.
10771
10772 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10773 Note: The @option{-fno-inline-functions-called-once} switch
10774 can be used to prevent inlining of subprograms local to the unit
10775 and called once from within it if @option{-O1} is used.
10776
10777 Note regarding the use of @option{-O3}: @option{-gnatn} is made up of two
10778 sub-switches @option{-gnatn1} and @option{-gnatn2} that can be directly
10779 specified in lieu of it, @option{-gnatn} being translated into one of them
10780 based on the optimization level. With @option{-O2} or below, @option{-gnatn}
10781 is equivalent to @option{-gnatn1} which activates pragma @code{Inline} with
10782 moderate inlining across modules. With @option{-O3}, @option{-gnatn} is
10783 equivalent to @option{-gnatn2} which activates pragma @code{Inline} with
10784 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
10785 effect of inlining subprograms you did not think should be inlined. We have
10786 found that the use of @option{-O3} may slow down the compilation and increase
10787 the code size by performing excessive inlining, leading to increased
10788 instruction cache pressure from the increased code size and thus minor
10789 performance improvements. So the bottom line here is that you should not
10790 automatically assume that @option{-O3} is better than @option{-O2}, and
10791 indeed you should use @option{-O3} only if tests show that it actually
10792 improves performance for your program.
10793
10794 @node Vectorization of loops
10795 @subsection Vectorization of loops
10796 @cindex Optimization Switches
10797
10798 You can take advantage of the auto-vectorizer present in the @command{gcc}
10799 back end to vectorize loops with GNAT. The corresponding command line switch
10800 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10801 and other aggressive optimizations helpful for vectorization also are enabled
10802 by default at this level, using @option{-O3} directly is recommended.
10803
10804 You also need to make sure that the target architecture features a supported
10805 SIMD instruction set. For example, for the x86 architecture, you should at
10806 least specify @option{-msse2} to get significant vectorization (but you don't
10807 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10808 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10809
10810 The preferred loop form for vectorization is the @code{for} iteration scheme.
10811 Loops with a @code{while} iteration scheme can also be vectorized if they are
10812 very simple, but the vectorizer will quickly give up otherwise. With either
10813 iteration scheme, the flow of control must be straight, in particular no
10814 @code{exit} statement may appear in the loop body. The loop may however
10815 contain a single nested loop, if it can be vectorized when considered alone:
10816
10817 @smallexample @c ada
10818 @cartouche
10819 A : array (1..4, 1..4) of Long_Float;
10820 S : array (1..4) of Long_Float;
10821
10822 procedure Sum is
10823 begin
10824 for I in A'Range(1) loop
10825 for J in A'Range(2) loop
10826 S (I) := S (I) + A (I, J);
10827 end loop;
10828 end loop;
10829 end Sum;
10830 @end cartouche
10831 @end smallexample
10832
10833 The vectorizable operations depend on the targeted SIMD instruction set, but
10834 the adding and some of the multiplying operators are generally supported, as
10835 well as the logical operators for modular types. Note that, in the former
10836 case, enabling overflow checks, for example with @option{-gnato}, totally
10837 disables vectorization. The other checks are not supposed to have the same
10838 definitive effect, although compiling with @option{-gnatp} might well reveal
10839 cases where some checks do thwart vectorization.
10840
10841 Type conversions may also prevent vectorization if they involve semantics that
10842 are not directly supported by the code generator or the SIMD instruction set.
10843 A typical example is direct conversion from floating-point to integer types.
10844 The solution in this case is to use the following idiom:
10845
10846 @smallexample @c ada
10847 Integer (S'Truncation (F))
10848 @end smallexample
10849
10850 @noindent
10851 if @code{S} is the subtype of floating-point object @code{F}.
10852
10853 In most cases, the vectorizable loops are loops that iterate over arrays.
10854 All kinds of array types are supported, i.e. constrained array types with
10855 static bounds:
10856
10857 @smallexample @c ada
10858 type Array_Type is array (1 .. 4) of Long_Float;
10859 @end smallexample
10860
10861 @noindent
10862 constrained array types with dynamic bounds:
10863
10864 @smallexample @c ada
10865 type Array_Type is array (1 .. Q.N) of Long_Float;
10866
10867 type Array_Type is array (Q.K .. 4) of Long_Float;
10868
10869 type Array_Type is array (Q.K .. Q.N) of Long_Float;
10870 @end smallexample
10871
10872 @noindent
10873 or unconstrained array types:
10874
10875 @smallexample @c ada
10876 type Array_Type is array (Positive range <>) of Long_Float;
10877 @end smallexample
10878
10879 @noindent
10880 The quality of the generated code decreases when the dynamic aspect of the
10881 array type increases, the worst code being generated for unconstrained array
10882 types. This is so because, the less information the compiler has about the
10883 bounds of the array, the more fallback code it needs to generate in order to
10884 fix things up at run time.
10885
10886 It is possible to specify that a given loop should be subject to vectorization
10887 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
10888
10889 @smallexample @c ada
10890 pragma Loop_Optimize (Vector);
10891 @end smallexample
10892
10893 @noindent
10894 placed immediately within the loop will convey the appropriate hint to the
10895 compiler for this loop.
10896
10897 It is also possible to help the compiler generate better vectorized code
10898 for a given loop by asserting that there are no loop-carried dependencies
10899 in the loop. Consider for example the procedure:
10900
10901 @smallexample @c ada
10902 type Arr is array (1 .. 4) of Long_Float;
10903
10904 procedure Add (X, Y : not null access Arr; R : not null access Arr) is
10905 begin
10906 for I in Arr'Range loop
10907 R(I) := X(I) + Y(I);
10908 end loop;
10909 end;
10910 @end smallexample
10911
10912 @noindent
10913 By default, the compiler cannot unconditionally vectorize the loop because
10914 assigning to a component of the array designated by R in one iteration could
10915 change the value read from the components of the arrays designated by X or Y
10916 in a later iteration. As a result, the compiler will generate two versions
10917 of the loop in the object code, one vectorized and the other not vectorized,
10918 as well as a test to select the appropriate version at run time. This can
10919 be overcome by another hint:
10920
10921 @smallexample @c ada
10922 pragma Loop_Optimize (Ivdep);
10923 @end smallexample
10924
10925 @noindent
10926 placed immediately within the loop will tell the compiler that it can safely
10927 omit the non-vectorized version of the loop as well as the run-time test.
10928
10929 @node Other Optimization Switches
10930 @subsection Other Optimization Switches
10931 @cindex Optimization Switches
10932
10933 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10934 @command{gcc} optimization switches are potentially usable. These switches
10935 have not been extensively tested with GNAT but can generally be expected
10936 to work. Examples of switches in this category are @option{-funroll-loops}
10937 and the various target-specific @option{-m} options (in particular, it has
10938 been observed that @option{-march=xxx} can significantly improve performance
10939 on appropriate machines). For full details of these switches, see
10940 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10941 the GNU Compiler Collection (GCC)}.
10942
10943 @node Optimization and Strict Aliasing
10944 @subsection Optimization and Strict Aliasing
10945 @cindex Aliasing
10946 @cindex Strict Aliasing
10947 @cindex No_Strict_Aliasing
10948
10949 @noindent
10950 The strong typing capabilities of Ada allow an optimizer to generate
10951 efficient code in situations where other languages would be forced to
10952 make worst case assumptions preventing such optimizations. Consider
10953 the following example:
10954
10955 @smallexample @c ada
10956 @cartouche
10957 procedure R is
10958 type Int1 is new Integer;
10959 type Int2 is new Integer;
10960 type Int1A is access Int1;
10961 type Int2A is access Int2;
10962 Int1V : Int1A;
10963 Int2V : Int2A;
10964 @dots{}
10965
10966 begin
10967 @dots{}
10968 for J in Data'Range loop
10969 if Data (J) = Int1V.all then
10970 Int2V.all := Int2V.all + 1;
10971 end if;
10972 end loop;
10973 @dots{}
10974 end R;
10975 @end cartouche
10976 @end smallexample
10977
10978 @noindent
10979 In this example, since the variable @code{Int1V} can only access objects
10980 of type @code{Int1}, and @code{Int2V} can only access objects of type
10981 @code{Int2}, there is no possibility that the assignment to
10982 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10983 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10984 for all iterations of the loop and avoid the extra memory reference
10985 required to dereference it each time through the loop.
10986
10987 This kind of optimization, called strict aliasing analysis, is
10988 triggered by specifying an optimization level of @option{-O2} or
10989 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10990 when access values are involved.
10991
10992 However, although this optimization is always correct in terms of
10993 the formal semantics of the Ada Reference Manual, difficulties can
10994 arise if features like @code{Unchecked_Conversion} are used to break
10995 the typing system. Consider the following complete program example:
10996
10997 @smallexample @c ada
10998 @cartouche
10999 package p1 is
11000 type int1 is new integer;
11001 type int2 is new integer;
11002 type a1 is access int1;
11003 type a2 is access int2;
11004 end p1;
11005
11006 with p1; use p1;
11007 package p2 is
11008 function to_a2 (Input : a1) return a2;
11009 end p2;
11010
11011 with Unchecked_Conversion;
11012 package body p2 is
11013 function to_a2 (Input : a1) return a2 is
11014 function to_a2u is
11015 new Unchecked_Conversion (a1, a2);
11016 begin
11017 return to_a2u (Input);
11018 end to_a2;
11019 end p2;
11020
11021 with p2; use p2;
11022 with p1; use p1;
11023 with Text_IO; use Text_IO;
11024 procedure m is
11025 v1 : a1 := new int1;
11026 v2 : a2 := to_a2 (v1);
11027 begin
11028 v1.all := 1;
11029 v2.all := 0;
11030 put_line (int1'image (v1.all));
11031 end;
11032 @end cartouche
11033 @end smallexample
11034
11035 @noindent
11036 This program prints out 0 in @option{-O0} or @option{-O1}
11037 mode, but it prints out 1 in @option{-O2} mode. That's
11038 because in strict aliasing mode, the compiler can and
11039 does assume that the assignment to @code{v2.all} could not
11040 affect the value of @code{v1.all}, since different types
11041 are involved.
11042
11043 This behavior is not a case of non-conformance with the standard, since
11044 the Ada RM specifies that an unchecked conversion where the resulting
11045 bit pattern is not a correct value of the target type can result in an
11046 abnormal value and attempting to reference an abnormal value makes the
11047 execution of a program erroneous. That's the case here since the result
11048 does not point to an object of type @code{int2}. This means that the
11049 effect is entirely unpredictable.
11050
11051 However, although that explanation may satisfy a language
11052 lawyer, in practice an applications programmer expects an
11053 unchecked conversion involving pointers to create true
11054 aliases and the behavior of printing 1 seems plain wrong.
11055 In this case, the strict aliasing optimization is unwelcome.
11056
11057 Indeed the compiler recognizes this possibility, and the
11058 unchecked conversion generates a warning:
11059
11060 @smallexample
11061 p2.adb:5:07: warning: possible aliasing problem with type "a2"
11062 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
11063 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
11064 @end smallexample
11065
11066 @noindent
11067 Unfortunately the problem is recognized when compiling the body of
11068 package @code{p2}, but the actual "bad" code is generated while
11069 compiling the body of @code{m} and this latter compilation does not see
11070 the suspicious @code{Unchecked_Conversion}.
11071
11072 As implied by the warning message, there are approaches you can use to
11073 avoid the unwanted strict aliasing optimization in a case like this.
11074
11075 One possibility is to simply avoid the use of @option{-O2}, but
11076 that is a bit drastic, since it throws away a number of useful
11077 optimizations that do not involve strict aliasing assumptions.
11078
11079 A less drastic approach is to compile the program using the
11080 option @option{-fno-strict-aliasing}. Actually it is only the
11081 unit containing the dereferencing of the suspicious pointer
11082 that needs to be compiled. So in this case, if we compile
11083 unit @code{m} with this switch, then we get the expected
11084 value of zero printed. Analyzing which units might need
11085 the switch can be painful, so a more reasonable approach
11086 is to compile the entire program with options @option{-O2}
11087 and @option{-fno-strict-aliasing}. If the performance is
11088 satisfactory with this combination of options, then the
11089 advantage is that the entire issue of possible "wrong"
11090 optimization due to strict aliasing is avoided.
11091
11092 To avoid the use of compiler switches, the configuration
11093 pragma @code{No_Strict_Aliasing} with no parameters may be
11094 used to specify that for all access types, the strict
11095 aliasing optimization should be suppressed.
11096
11097 However, these approaches are still overkill, in that they causes
11098 all manipulations of all access values to be deoptimized. A more
11099 refined approach is to concentrate attention on the specific
11100 access type identified as problematic.
11101
11102 First, if a careful analysis of uses of the pointer shows
11103 that there are no possible problematic references, then
11104 the warning can be suppressed by bracketing the
11105 instantiation of @code{Unchecked_Conversion} to turn
11106 the warning off:
11107
11108 @smallexample @c ada
11109 pragma Warnings (Off);
11110 function to_a2u is
11111 new Unchecked_Conversion (a1, a2);
11112 pragma Warnings (On);
11113 @end smallexample
11114
11115 @noindent
11116 Of course that approach is not appropriate for this particular
11117 example, since indeed there is a problematic reference. In this
11118 case we can take one of two other approaches.
11119
11120 The first possibility is to move the instantiation of unchecked
11121 conversion to the unit in which the type is declared. In
11122 this example, we would move the instantiation of
11123 @code{Unchecked_Conversion} from the body of package
11124 @code{p2} to the spec of package @code{p1}. Now the
11125 warning disappears. That's because any use of the
11126 access type knows there is a suspicious unchecked
11127 conversion, and the strict aliasing optimization
11128 is automatically suppressed for the type.
11129
11130 If it is not practical to move the unchecked conversion to the same unit
11131 in which the destination access type is declared (perhaps because the
11132 source type is not visible in that unit), you may use pragma
11133 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
11134 same declarative sequence as the declaration of the access type:
11135
11136 @smallexample @c ada
11137 type a2 is access int2;
11138 pragma No_Strict_Aliasing (a2);
11139 @end smallexample
11140
11141 @noindent
11142 Here again, the compiler now knows that the strict aliasing optimization
11143 should be suppressed for any reference to type @code{a2} and the
11144 expected behavior is obtained.
11145
11146 Finally, note that although the compiler can generate warnings for
11147 simple cases of unchecked conversions, there are tricker and more
11148 indirect ways of creating type incorrect aliases which the compiler
11149 cannot detect. Examples are the use of address overlays and unchecked
11150 conversions involving composite types containing access types as
11151 components. In such cases, no warnings are generated, but there can
11152 still be aliasing problems. One safe coding practice is to forbid the
11153 use of address clauses for type overlaying, and to allow unchecked
11154 conversion only for primitive types. This is not really a significant
11155 restriction since any possible desired effect can be achieved by
11156 unchecked conversion of access values.
11157
11158 The aliasing analysis done in strict aliasing mode can certainly
11159 have significant benefits. We have seen cases of large scale
11160 application code where the time is increased by up to 5% by turning
11161 this optimization off. If you have code that includes significant
11162 usage of unchecked conversion, you might want to just stick with
11163 @option{-O1} and avoid the entire issue. If you get adequate
11164 performance at this level of optimization level, that's probably
11165 the safest approach. If tests show that you really need higher
11166 levels of optimization, then you can experiment with @option{-O2}
11167 and @option{-O2 -fno-strict-aliasing} to see how much effect this
11168 has on size and speed of the code. If you really need to use
11169 @option{-O2} with strict aliasing in effect, then you should
11170 review any uses of unchecked conversion of access types,
11171 particularly if you are getting the warnings described above.
11172
11173 @node Aliased Variables and Optimization
11174 @subsection Aliased Variables and Optimization
11175 @cindex Aliasing
11176 There are scenarios in which programs may
11177 use low level techniques to modify variables
11178 that otherwise might be considered to be unassigned. For example,
11179 a variable can be passed to a procedure by reference, which takes
11180 the address of the parameter and uses the address to modify the
11181 variable's value, even though it is passed as an IN parameter.
11182 Consider the following example:
11183
11184 @smallexample @c ada
11185 procedure P is
11186 Max_Length : constant Natural := 16;
11187 type Char_Ptr is access all Character;
11188
11189 procedure Get_String(Buffer: Char_Ptr; Size : Integer);
11190 pragma Import (C, Get_String, "get_string");
11191
11192 Name : aliased String (1 .. Max_Length) := (others => ' ');
11193 Temp : Char_Ptr;
11194
11195 function Addr (S : String) return Char_Ptr is
11196 function To_Char_Ptr is
11197 new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
11198 begin
11199 return To_Char_Ptr (S (S'First)'Address);
11200 end;
11201
11202 begin
11203 Temp := Addr (Name);
11204 Get_String (Temp, Max_Length);
11205 end;
11206 @end smallexample
11207
11208 @noindent
11209 where Get_String is a C function that uses the address in Temp to
11210 modify the variable @code{Name}. This code is dubious, and arguably
11211 erroneous, and the compiler would be entitled to assume that
11212 @code{Name} is never modified, and generate code accordingly.
11213
11214 However, in practice, this would cause some existing code that
11215 seems to work with no optimization to start failing at high
11216 levels of optimzization.
11217
11218 What the compiler does for such cases is to assume that marking
11219 a variable as aliased indicates that some "funny business" may
11220 be going on. The optimizer recognizes the aliased keyword and
11221 inhibits optimizations that assume the value cannot be assigned.
11222 This means that the above example will in fact "work" reliably,
11223 that is, it will produce the expected results.
11224
11225 @node Atomic Variables and Optimization
11226 @subsection Atomic Variables and Optimization
11227 @cindex Atomic
11228 There are two considerations with regard to performance when
11229 atomic variables are used.
11230
11231 First, the RM only guarantees that access to atomic variables
11232 be atomic, it has nothing to say about how this is achieved,
11233 though there is a strong implication that this should not be
11234 achieved by explicit locking code. Indeed GNAT will never
11235 generate any locking code for atomic variable access (it will
11236 simply reject any attempt to make a variable or type atomic
11237 if the atomic access cannot be achieved without such locking code).
11238
11239 That being said, it is important to understand that you cannot
11240 assume that the entire variable will always be accessed. Consider
11241 this example:
11242
11243 @smallexample @c ada
11244 type R is record
11245 A,B,C,D : Character;
11246 end record;
11247 for R'Size use 32;
11248 for R'Alignment use 4;
11249
11250 RV : R;
11251 pragma Atomic (RV);
11252 X : Character;
11253 ...
11254 X := RV.B;
11255 @end smallexample
11256
11257 @noindent
11258 You cannot assume that the reference to @code{RV.B}
11259 will read the entire 32-bit
11260 variable with a single load instruction. It is perfectly legitimate if
11261 the hardware allows it to do a byte read of just the B field. This read
11262 is still atomic, which is all the RM requires. GNAT can and does take
11263 advantage of this, depending on the architecture and optimization level.
11264 Any assumption to the contrary is non-portable and risky. Even if you
11265 examine the assembly language and see a full 32-bit load, this might
11266 change in a future version of the compiler.
11267
11268 If your application requires that all accesses to @code{RV} in this
11269 example be full 32-bit loads, you need to make a copy for the access
11270 as in:
11271
11272 @smallexample @c ada
11273 declare
11274 RV_Copy : constant R := RV;
11275 begin
11276 X := RV_Copy.B;
11277 end;
11278 @end smallexample
11279
11280
11281 @noindent
11282 Now the reference to RV must read the whole variable.
11283 Actually one can imagine some compiler which figures
11284 out that the whole copy is not required (because only
11285 the B field is actually accessed), but GNAT
11286 certainly won't do that, and we don't know of any
11287 compiler that would not handle this right, and the
11288 above code will in practice work portably across
11289 all architectures (that permit the Atomic declaration).
11290
11291 The second issue with atomic variables has to do with
11292 the possible requirement of generating synchronization
11293 code. For more details on this, consult the sections on
11294 the pragmas Enable/Disable_Atomic_Synchronization in the
11295 GNAT Reference Manual. If performance is critical, and
11296 such synchronization code is not required, it may be
11297 useful to disable it.
11298
11299 @node Passive Task Optimization
11300 @subsection Passive Task Optimization
11301 @cindex Passive Task
11302
11303 A passive task is one which is sufficiently simple that
11304 in theory a compiler could recognize it an implement it
11305 efficiently without creating a new thread. The original design
11306 of Ada 83 had in mind this kind of passive task optimization, but
11307 only a few Ada 83 compilers attempted it. The problem was that
11308 it was difficult to determine the exact conditions under which
11309 the optimization was possible. The result is a very fragile
11310 optimization where a very minor change in the program can
11311 suddenly silently make a task non-optimizable.
11312
11313 With the revisiting of this issue in Ada 95, there was general
11314 agreement that this approach was fundamentally flawed, and the
11315 notion of protected types was introduced. When using protected
11316 types, the restrictions are well defined, and you KNOW that the
11317 operations will be optimized, and furthermore this optimized
11318 performance is fully portable.
11319
11320 Although it would theoretically be possible for GNAT to attempt to
11321 do this optimization, but it really doesn't make sense in the
11322 context of Ada 95, and none of the Ada 95 compilers implement
11323 this optimization as far as we know. In particular GNAT never
11324 attempts to perform this optimization.
11325
11326 In any new Ada 95 code that is written, you should always
11327 use protected types in place of tasks that might be able to
11328 be optimized in this manner.
11329 Of course this does not help if you have legacy Ada 83 code
11330 that depends on this optimization, but it is unusual to encounter
11331 a case where the performance gains from this optimization
11332 are significant.
11333
11334 Your program should work correctly without this optimization. If
11335 you have performance problems, then the most practical
11336 approach is to figure out exactly where these performance problems
11337 arise, and update those particular tasks to be protected types. Note
11338 that typically clients of the tasks who call entries, will not have
11339 to be modified, only the task definition itself.
11340
11341 @ifset vms
11342 @node Coverage Analysis
11343 @subsection Coverage Analysis
11344
11345 @noindent
11346 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
11347 the user to determine the distribution of execution time across a program,
11348 @pxref{Profiling} for details of usage.
11349 @end ifset
11350
11351
11352 @node Text_IO Suggestions
11353 @section @code{Text_IO} Suggestions
11354 @cindex @code{Text_IO} and performance
11355
11356 @noindent
11357 The @code{Ada.Text_IO} package has fairly high overheads due in part to
11358 the requirement of maintaining page and line counts. If performance
11359 is critical, a recommendation is to use @code{Stream_IO} instead of
11360 @code{Text_IO} for volume output, since this package has less overhead.
11361
11362 If @code{Text_IO} must be used, note that by default output to the standard
11363 output and standard error files is unbuffered (this provides better
11364 behavior when output statements are used for debugging, or if the
11365 progress of a program is observed by tracking the output, e.g. by
11366 using the Unix @command{tail -f} command to watch redirected output.
11367
11368 If you are generating large volumes of output with @code{Text_IO} and
11369 performance is an important factor, use a designated file instead
11370 of the standard output file, or change the standard output file to
11371 be buffered using @code{Interfaces.C_Streams.setvbuf}.
11372
11373
11374 @ifclear FSFEDITION
11375 @node Reducing Size of Ada Executables with gnatelim
11376 @section Reducing Size of Ada Executables with @code{gnatelim}
11377 @findex gnatelim
11378
11379 @noindent
11380 This section describes @command{gnatelim}, a tool which detects unused
11381 subprograms and helps the compiler to create a smaller executable for your
11382 program.
11383
11384 @menu
11385 * About gnatelim::
11386 * Running gnatelim::
11387 * Processing Precompiled Libraries::
11388 * Correcting the List of Eliminate Pragmas::
11389 * Making Your Executables Smaller::
11390 * Summary of the gnatelim Usage Cycle::
11391 @end menu
11392
11393 @node About gnatelim
11394 @subsection About @code{gnatelim}
11395
11396 @noindent
11397 When a program shares a set of Ada
11398 packages with other programs, it may happen that this program uses
11399 only a fraction of the subprograms defined in these packages. The code
11400 created for these unused subprograms increases the size of the executable.
11401
11402 @code{gnatelim} tracks unused subprograms in an Ada program and
11403 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
11404 subprograms that are declared but never called. By placing the list of
11405 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
11406 recompiling your program, you may decrease the size of its executable,
11407 because the compiler will not generate the code for 'eliminated' subprograms.
11408 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
11409 information about this pragma.
11410
11411 @code{gnatelim} needs as its input data the name of the main subprogram.
11412
11413 If a set of source files is specified as @code{gnatelim} arguments, it
11414 treats these files as a complete set of sources making up a program to
11415 analyse, and analyses only these sources.
11416
11417 After a full successful build of the main subprogram @code{gnatelim} can be
11418 called without specifying sources to analyse, in this case it computes
11419 the source closure of the main unit from the @file{ALI} files.
11420
11421 The following command will create the set of @file{ALI} files needed for
11422 @code{gnatelim}:
11423
11424 @smallexample
11425 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
11426 @end smallexample
11427
11428 Note that @code{gnatelim} does not need object files.
11429
11430 @node Running gnatelim
11431 @subsection Running @code{gnatelim}
11432
11433 @noindent
11434 @code{gnatelim} has the following command-line interface:
11435
11436 @smallexample
11437 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
11438 @end smallexample
11439
11440 @noindent
11441 @var{main_unit_name} should be a name of a source file that contains the main
11442 subprogram of a program (partition).
11443
11444 Each @var{filename} is the name (including the extension) of a source
11445 file to process. ``Wildcards'' are allowed, and
11446 the file name may contain path information.
11447
11448 @samp{@var{gcc_switches}} is a list of switches for
11449 @command{gcc}. They will be passed on to all compiler invocations made by
11450 @command{gnatelim} to generate the ASIS trees. Here you can provide
11451 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
11452 use the @option{-gnatec} switch to set the configuration file,
11453 use the @option{-gnat05} switch if sources should be compiled in
11454 Ada 2005 mode etc.
11455
11456 @code{gnatelim} has the following switches:
11457
11458 @table @option
11459 @c !sort!
11460 @item --version
11461 @cindex @option{--version} @command{gnatelim}
11462 Display Copyright and version, then exit disregarding all other options.
11463
11464 @item --help
11465 @cindex @option{--help} @command{gnatelim}
11466 Display usage, then exit disregarding all other options.
11467
11468 @item -P @var{file}
11469 @cindex @option{-P} @command{gnatelim}
11470 Indicates the name of the project file that describes the set of sources
11471 to be processed.
11472
11473 @item -X@var{name}=@var{value}
11474 @cindex @option{-X} @command{gnatelim}
11475 Indicates that external variable @var{name} in the argument project
11476 has the value @var{value}. Has no effect if no project is specified as
11477 tool argument.
11478
11479 @item ^-files^/FILES^=@var{filename}
11480 @cindex @option{^-files^/FILES^} (@code{gnatelim})
11481 Take the argument source files from the specified file. This file should be an
11482 ordinary text file containing file names separated by spaces or
11483 line breaks. You can use this switch more than once in the same call to
11484 @command{gnatelim}. You also can combine this switch with
11485 an explicit list of files.
11486
11487 @item ^-log^/LOG^
11488 @cindex @option{^-log^/LOG^} (@command{gnatelim})
11489 Duplicate all the output sent to @file{stderr} into a log file. The log file
11490 is named @file{gnatelim.log} and is located in the current directory.
11491
11492 @ignore
11493 @item ^-log^/LOGFILE^=@var{filename}
11494 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
11495 Duplicate all the output sent to @file{stderr} into a specified log file.
11496 @end ignore
11497
11498 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
11499 @item ^--no-elim-dispatch^/NO_DISPATCH^
11500 Do not generate pragmas for dispatching operations.
11501
11502 @item ^--ignore^/IGNORE^=@var{filename}
11503 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
11504 Do not generate pragmas for subprograms declared in the sources
11505 listed in a specified file
11506
11507 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
11508 @item ^-o^/OUTPUT^=@var{report_file}
11509 Put @command{gnatelim} output into a specified file. If this file already exists,
11510 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
11511 into @file{stderr}
11512
11513 @item ^-j^/PROCESSES=^@var{n}
11514 @cindex @option{^-j^/PROCESSES^} (@command{gnatelim})
11515 Use @var{n} processes to carry out the tree creations (internal representations
11516 of the argument sources). On a multiprocessor machine this speeds up processing
11517 of big sets of argument sources. If @var{n} is 0, then the maximum number of
11518 parallel tree creations is the number of core processors on the platform.
11519
11520 @item ^-q^/QUIET^
11521 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
11522 Quiet mode: by default @code{gnatelim} outputs to the standard error
11523 stream the number of program units left to be processed. This option turns
11524 this trace off.
11525
11526 @cindex @option{^-t^/TIME^} (@command{gnatelim})
11527 @item ^-t^/TIME^
11528 Print out execution time.
11529
11530 @item ^-v^/VERBOSE^
11531 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
11532 Verbose mode: @code{gnatelim} version information is printed as Ada
11533 comments to the standard output stream. Also, in addition to the number of
11534 program units left @code{gnatelim} will output the name of the current unit
11535 being processed.
11536
11537 @item ^-wq^/WARNINGS=QUIET^
11538 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
11539 Quiet warning mode - some warnings are suppressed. In particular warnings that
11540 indicate that the analysed set of sources is incomplete to make up a
11541 partition and that some subprogram bodies are missing are not generated.
11542 @end table
11543
11544 @noindent
11545 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11546 driver (see @ref{The GNAT Driver and Project Files}).
11547
11548 @node Processing Precompiled Libraries
11549 @subsection Processing Precompiled Libraries
11550
11551 @noindent
11552 If some program uses a precompiled Ada library, it can be processed by
11553 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11554 Eliminate pragma for a subprogram if the body of this subprogram has not
11555 been analysed, this is a typical case for subprograms from precompiled
11556 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11557 warnings about missing source files and non-analyzed subprogram bodies
11558 that can be generated when processing precompiled Ada libraries.
11559
11560 @node Correcting the List of Eliminate Pragmas
11561 @subsection Correcting the List of Eliminate Pragmas
11562
11563 @noindent
11564 In some rare cases @code{gnatelim} may try to eliminate
11565 subprograms that are actually called in the program. In this case, the
11566 compiler will generate an error message of the form:
11567
11568 @smallexample
11569 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11570 @end smallexample
11571
11572 @noindent
11573 You will need to manually remove the wrong @code{Eliminate} pragmas from
11574 the configuration file indicated in the error message. You should recompile
11575 your program from scratch after that, because you need a consistent
11576 configuration file(s) during the entire compilation.
11577
11578 @node Making Your Executables Smaller
11579 @subsection Making Your Executables Smaller
11580
11581 @noindent
11582 In order to get a smaller executable for your program you now have to
11583 recompile the program completely with the configuration file containing
11584 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11585 @file{gnat.adc} file located in your current directory, just do:
11586
11587 @smallexample
11588 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11589 @end smallexample
11590
11591 @noindent
11592 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11593 recompile everything
11594 with the set of pragmas @code{Eliminate} that you have obtained with
11595 @command{gnatelim}).
11596
11597 Be aware that the set of @code{Eliminate} pragmas is specific to each
11598 program. It is not recommended to merge sets of @code{Eliminate}
11599 pragmas created for different programs in one configuration file.
11600
11601 @node Summary of the gnatelim Usage Cycle
11602 @subsection Summary of the @code{gnatelim} Usage Cycle
11603
11604 @noindent
11605 Here is a quick summary of the steps to be taken in order to reduce
11606 the size of your executables with @code{gnatelim}. You may use
11607 other GNAT options to control the optimization level,
11608 to produce the debugging information, to set search path, etc.
11609
11610 @enumerate
11611 @item
11612 Create a complete set of @file{ALI} files (if the program has not been
11613 built already)
11614
11615 @smallexample
11616 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11617 @end smallexample
11618
11619 @item
11620 Generate a list of @code{Eliminate} pragmas in default configuration file
11621 @file{gnat.adc} in the current directory
11622 @smallexample
11623 @ifset vms
11624 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11625 @end ifset
11626 @ifclear vms
11627 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11628 @end ifclear
11629 @end smallexample
11630
11631 @item
11632 Recompile the application
11633
11634 @smallexample
11635 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11636 @end smallexample
11637
11638 @end enumerate
11639 @end ifclear
11640
11641 @node Reducing Size of Executables with unused subprogram/data elimination
11642 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11643 @findex unused subprogram/data elimination
11644
11645 @noindent
11646 This section describes how you can eliminate unused subprograms and data from
11647 your executable just by setting options at compilation time.
11648
11649 @menu
11650 * About unused subprogram/data elimination::
11651 * Compilation options::
11652 * Example of unused subprogram/data elimination::
11653 @end menu
11654
11655 @node About unused subprogram/data elimination
11656 @subsection About unused subprogram/data elimination
11657
11658 @noindent
11659 By default, an executable contains all code and data of its composing objects
11660 (directly linked or coming from statically linked libraries), even data or code
11661 never used by this executable.
11662
11663 This feature will allow you to eliminate such unused code from your
11664 executable, making it smaller (in disk and in memory).
11665
11666 This functionality is available on all Linux platforms except for the IA-64
11667 architecture and on all cross platforms using the ELF binary file format.
11668 In both cases GNU binutils version 2.16 or later are required to enable it.
11669
11670 @node Compilation options
11671 @subsection Compilation options
11672
11673 @noindent
11674 The operation of eliminating the unused code and data from the final executable
11675 is directly performed by the linker.
11676
11677 In order to do this, it has to work with objects compiled with the
11678 following options:
11679 @option{-ffunction-sections} @option{-fdata-sections}.
11680 @cindex @option{-ffunction-sections} (@command{gcc})
11681 @cindex @option{-fdata-sections} (@command{gcc})
11682 These options are usable with C and Ada files.
11683 They will place respectively each
11684 function or data in a separate section in the resulting object file.
11685
11686 Once the objects and static libraries are created with these options, the
11687 linker can perform the dead code elimination. You can do this by setting
11688 the @option{-Wl,--gc-sections} option to gcc command or in the
11689 @option{-largs} section of @command{gnatmake}. This will perform a
11690 garbage collection of code and data never referenced.
11691
11692 If the linker performs a partial link (@option{-r} linker option), then you
11693 will need to provide the entry point using the @option{-e} / @option{--entry}
11694 linker option.
11695
11696 Note that objects compiled without the @option{-ffunction-sections} and
11697 @option{-fdata-sections} options can still be linked with the executable.
11698 However, no dead code elimination will be performed on those objects (they will
11699 be linked as is).
11700
11701 The GNAT static library is now compiled with -ffunction-sections and
11702 -fdata-sections on some platforms. This allows you to eliminate the unused code
11703 and data of the GNAT library from your executable.
11704
11705 @node Example of unused subprogram/data elimination
11706 @subsection Example of unused subprogram/data elimination
11707
11708 @noindent
11709 Here is a simple example:
11710
11711 @smallexample @c ada
11712 with Aux;
11713
11714 procedure Test is
11715 begin
11716 Aux.Used (10);
11717 end Test;
11718
11719 package Aux is
11720 Used_Data : Integer;
11721 Unused_Data : Integer;
11722
11723 procedure Used (Data : Integer);
11724 procedure Unused (Data : Integer);
11725 end Aux;
11726
11727 package body Aux is
11728 procedure Used (Data : Integer) is
11729 begin
11730 Used_Data := Data;
11731 end Used;
11732
11733 procedure Unused (Data : Integer) is
11734 begin
11735 Unused_Data := Data;
11736 end Unused;
11737 end Aux;
11738 @end smallexample
11739
11740 @noindent
11741 @code{Unused} and @code{Unused_Data} are never referenced in this code
11742 excerpt, and hence they may be safely removed from the final executable.
11743
11744 @smallexample
11745 $ gnatmake test
11746
11747 $ nm test | grep used
11748 020015f0 T aux__unused
11749 02005d88 B aux__unused_data
11750 020015cc T aux__used
11751 02005d84 B aux__used_data
11752
11753 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11754 -largs -Wl,--gc-sections
11755
11756 $ nm test | grep used
11757 02005350 T aux__used
11758 0201ffe0 B aux__used_data
11759 @end smallexample
11760
11761 @noindent
11762 It can be observed that the procedure @code{Unused} and the object
11763 @code{Unused_Data} are removed by the linker when using the
11764 appropriate options.
11765
11766 @c ********************************
11767 @node Renaming Files with gnatchop
11768 @chapter Renaming Files with @code{gnatchop}
11769 @findex gnatchop
11770
11771 @noindent
11772 This chapter discusses how to handle files with multiple units by using
11773 the @code{gnatchop} utility. This utility is also useful in renaming
11774 files to meet the standard GNAT default file naming conventions.
11775
11776 @menu
11777 * Handling Files with Multiple Units::
11778 * Operating gnatchop in Compilation Mode::
11779 * Command Line for gnatchop::
11780 * Switches for gnatchop::
11781 * Examples of gnatchop Usage::
11782 @end menu
11783
11784 @node Handling Files with Multiple Units
11785 @section Handling Files with Multiple Units
11786
11787 @noindent
11788 The basic compilation model of GNAT requires that a file submitted to the
11789 compiler have only one unit and there be a strict correspondence
11790 between the file name and the unit name.
11791
11792 The @code{gnatchop} utility allows both of these rules to be relaxed,
11793 allowing GNAT to process files which contain multiple compilation units
11794 and files with arbitrary file names. @code{gnatchop}
11795 reads the specified file and generates one or more output files,
11796 containing one unit per file. The unit and the file name correspond,
11797 as required by GNAT.
11798
11799 If you want to permanently restructure a set of ``foreign'' files so that
11800 they match the GNAT rules, and do the remaining development using the
11801 GNAT structure, you can simply use @command{gnatchop} once, generate the
11802 new set of files and work with them from that point on.
11803
11804 Alternatively, if you want to keep your files in the ``foreign'' format,
11805 perhaps to maintain compatibility with some other Ada compilation
11806 system, you can set up a procedure where you use @command{gnatchop} each
11807 time you compile, regarding the source files that it writes as temporary
11808 files that you throw away.
11809
11810 Note that if your file containing multiple units starts with a byte order
11811 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11812 will each start with a copy of this BOM, meaning that they can be compiled
11813 automatically in UTF-8 mode without needing to specify an explicit encoding.
11814
11815 @node Operating gnatchop in Compilation Mode
11816 @section Operating gnatchop in Compilation Mode
11817
11818 @noindent
11819 The basic function of @code{gnatchop} is to take a file with multiple units
11820 and split it into separate files. The boundary between files is reasonably
11821 clear, except for the issue of comments and pragmas. In default mode, the
11822 rule is that any pragmas between units belong to the previous unit, except
11823 that configuration pragmas always belong to the following unit. Any comments
11824 belong to the following unit. These rules
11825 almost always result in the right choice of
11826 the split point without needing to mark it explicitly and most users will
11827 find this default to be what they want. In this default mode it is incorrect to
11828 submit a file containing only configuration pragmas, or one that ends in
11829 configuration pragmas, to @code{gnatchop}.
11830
11831 However, using a special option to activate ``compilation mode'',
11832 @code{gnatchop}
11833 can perform another function, which is to provide exactly the semantics
11834 required by the RM for handling of configuration pragmas in a compilation.
11835 In the absence of configuration pragmas (at the main file level), this
11836 option has no effect, but it causes such configuration pragmas to be handled
11837 in a quite different manner.
11838
11839 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11840 only configuration pragmas, then this file is appended to the
11841 @file{gnat.adc} file in the current directory. This behavior provides
11842 the required behavior described in the RM for the actions to be taken
11843 on submitting such a file to the compiler, namely that these pragmas
11844 should apply to all subsequent compilations in the same compilation
11845 environment. Using GNAT, the current directory, possibly containing a
11846 @file{gnat.adc} file is the representation
11847 of a compilation environment. For more information on the
11848 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11849
11850 Second, in compilation mode, if @code{gnatchop}
11851 is given a file that starts with
11852 configuration pragmas, and contains one or more units, then these
11853 configuration pragmas are prepended to each of the chopped files. This
11854 behavior provides the required behavior described in the RM for the
11855 actions to be taken on compiling such a file, namely that the pragmas
11856 apply to all units in the compilation, but not to subsequently compiled
11857 units.
11858
11859 Finally, if configuration pragmas appear between units, they are appended
11860 to the previous unit. This results in the previous unit being illegal,
11861 since the compiler does not accept configuration pragmas that follow
11862 a unit. This provides the required RM behavior that forbids configuration
11863 pragmas other than those preceding the first compilation unit of a
11864 compilation.
11865
11866 For most purposes, @code{gnatchop} will be used in default mode. The
11867 compilation mode described above is used only if you need exactly
11868 accurate behavior with respect to compilations, and you have files
11869 that contain multiple units and configuration pragmas. In this
11870 circumstance the use of @code{gnatchop} with the compilation mode
11871 switch provides the required behavior, and is for example the mode
11872 in which GNAT processes the ACVC tests.
11873
11874 @node Command Line for gnatchop
11875 @section Command Line for @code{gnatchop}
11876
11877 @noindent
11878 The @code{gnatchop} command has the form:
11879
11880 @smallexample
11881 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11882 @c @ovar{directory}
11883 @c Expanding @ovar macro inline (explanation in macro def comments)
11884 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11885 @r{[}@var{directory}@r{]}
11886 @end smallexample
11887
11888 @noindent
11889 The only required argument is the file name of the file to be chopped.
11890 There are no restrictions on the form of this file name. The file itself
11891 contains one or more Ada units, in normal GNAT format, concatenated
11892 together. As shown, more than one file may be presented to be chopped.
11893
11894 When run in default mode, @code{gnatchop} generates one output file in
11895 the current directory for each unit in each of the files.
11896
11897 @var{directory}, if specified, gives the name of the directory to which
11898 the output files will be written. If it is not specified, all files are
11899 written to the current directory.
11900
11901 For example, given a
11902 file called @file{hellofiles} containing
11903
11904 @smallexample @c ada
11905 @group
11906 @cartouche
11907 procedure hello;
11908
11909 with Text_IO; use Text_IO;
11910 procedure hello is
11911 begin
11912 Put_Line ("Hello");
11913 end hello;
11914 @end cartouche
11915 @end group
11916 @end smallexample
11917
11918 @noindent
11919 the command
11920
11921 @smallexample
11922 $ gnatchop ^hellofiles^HELLOFILES.^
11923 @end smallexample
11924
11925 @noindent
11926 generates two files in the current directory, one called
11927 @file{hello.ads} containing the single line that is the procedure spec,
11928 and the other called @file{hello.adb} containing the remaining text. The
11929 original file is not affected. The generated files can be compiled in
11930 the normal manner.
11931
11932 @noindent
11933 When gnatchop is invoked on a file that is empty or that contains only empty
11934 lines and/or comments, gnatchop will not fail, but will not produce any
11935 new sources.
11936
11937 For example, given a
11938 file called @file{toto.txt} containing
11939
11940 @smallexample @c ada
11941 @group
11942 @cartouche
11943 -- Just a comment
11944 @end cartouche
11945 @end group
11946 @end smallexample
11947
11948 @noindent
11949 the command
11950
11951 @smallexample
11952 $ gnatchop ^toto.txt^TOT.TXT^
11953 @end smallexample
11954
11955 @noindent
11956 will not produce any new file and will result in the following warnings:
11957
11958 @smallexample
11959 toto.txt:1:01: warning: empty file, contains no compilation units
11960 no compilation units found
11961 no source files written
11962 @end smallexample
11963
11964 @node Switches for gnatchop
11965 @section Switches for @code{gnatchop}
11966
11967 @noindent
11968 @command{gnatchop} recognizes the following switches:
11969
11970 @table @option
11971 @c !sort!
11972
11973 @item --version
11974 @cindex @option{--version} @command{gnatchop}
11975 Display Copyright and version, then exit disregarding all other options.
11976
11977 @item --help
11978 @cindex @option{--help} @command{gnatchop}
11979 If @option{--version} was not used, display usage, then exit disregarding
11980 all other options.
11981
11982 @item ^-c^/COMPILATION^
11983 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11984 Causes @code{gnatchop} to operate in compilation mode, in which
11985 configuration pragmas are handled according to strict RM rules. See
11986 previous section for a full description of this mode.
11987
11988 @ifclear vms
11989 @item -gnat@var{xxx}
11990 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11991 used to parse the given file. Not all @var{xxx} options make sense,
11992 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11993 process a source file that uses Latin-2 coding for identifiers.
11994 @end ifclear
11995
11996 @item ^-h^/HELP^
11997 Causes @code{gnatchop} to generate a brief help summary to the standard
11998 output file showing usage information.
11999
12000 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
12001 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
12002 Limit generated file names to the specified number @code{mm}
12003 of characters.
12004 This is useful if the
12005 resulting set of files is required to be interoperable with systems
12006 which limit the length of file names.
12007 @ifset vms
12008 If no value is given, or
12009 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
12010 a default of 39, suitable for OpenVMS Alpha
12011 Systems, is assumed
12012 @end ifset
12013 @ifclear vms
12014 No space is allowed between the @option{-k} and the numeric value. The numeric
12015 value may be omitted in which case a default of @option{-k8},
12016 suitable for use
12017 with DOS-like file systems, is used. If no @option{-k} switch
12018 is present then
12019 there is no limit on the length of file names.
12020 @end ifclear
12021
12022 @item ^-p^/PRESERVE^
12023 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
12024 Causes the file ^modification^creation^ time stamp of the input file to be
12025 preserved and used for the time stamp of the output file(s). This may be
12026 useful for preserving coherency of time stamps in an environment where
12027 @code{gnatchop} is used as part of a standard build process.
12028
12029 @item ^-q^/QUIET^
12030 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
12031 Causes output of informational messages indicating the set of generated
12032 files to be suppressed. Warnings and error messages are unaffected.
12033
12034 @item ^-r^/REFERENCE^
12035 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
12036 @findex Source_Reference
12037 Generate @code{Source_Reference} pragmas. Use this switch if the output
12038 files are regarded as temporary and development is to be done in terms
12039 of the original unchopped file. This switch causes
12040 @code{Source_Reference} pragmas to be inserted into each of the
12041 generated files to refers back to the original file name and line number.
12042 The result is that all error messages refer back to the original
12043 unchopped file.
12044 In addition, the debugging information placed into the object file (when
12045 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
12046 specified)
12047 also refers back to this original file so that tools like profilers and
12048 debuggers will give information in terms of the original unchopped file.
12049
12050 If the original file to be chopped itself contains
12051 a @code{Source_Reference}
12052 pragma referencing a third file, then gnatchop respects
12053 this pragma, and the generated @code{Source_Reference} pragmas
12054 in the chopped file refer to the original file, with appropriate
12055 line numbers. This is particularly useful when @code{gnatchop}
12056 is used in conjunction with @code{gnatprep} to compile files that
12057 contain preprocessing statements and multiple units.
12058
12059 @item ^-v^/VERBOSE^
12060 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
12061 Causes @code{gnatchop} to operate in verbose mode. The version
12062 number and copyright notice are output, as well as exact copies of
12063 the gnat1 commands spawned to obtain the chop control information.
12064
12065 @item ^-w^/OVERWRITE^
12066 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
12067 Overwrite existing file names. Normally @code{gnatchop} regards it as a
12068 fatal error if there is already a file with the same name as a
12069 file it would otherwise output, in other words if the files to be
12070 chopped contain duplicated units. This switch bypasses this
12071 check, and causes all but the last instance of such duplicated
12072 units to be skipped.
12073
12074 @ifclear vms
12075 @item --GCC=@var{xxxx}
12076 @cindex @option{--GCC=} (@code{gnatchop})
12077 Specify the path of the GNAT parser to be used. When this switch is used,
12078 no attempt is made to add the prefix to the GNAT parser executable.
12079 @end ifclear
12080 @end table
12081
12082 @node Examples of gnatchop Usage
12083 @section Examples of @code{gnatchop} Usage
12084
12085 @table @code
12086 @ifset vms
12087 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
12088 @end ifset
12089 @ifclear vms
12090 @item gnatchop -w hello_s.ada prerelease/files
12091 @end ifclear
12092
12093 Chops the source file @file{hello_s.ada}. The output files will be
12094 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
12095 overwriting any
12096 files with matching names in that directory (no files in the current
12097 directory are modified).
12098
12099 @item gnatchop ^archive^ARCHIVE.^
12100 Chops the source file @file{^archive^ARCHIVE.^}
12101 into the current directory. One
12102 useful application of @code{gnatchop} is in sending sets of sources
12103 around, for example in email messages. The required sources are simply
12104 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
12105 command), and then
12106 @command{gnatchop} is used at the other end to reconstitute the original
12107 file names.
12108
12109 @item gnatchop file1 file2 file3 direc
12110 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
12111 the resulting files in the directory @file{direc}. Note that if any units
12112 occur more than once anywhere within this set of files, an error message
12113 is generated, and no files are written. To override this check, use the
12114 @option{^-w^/OVERWRITE^} switch,
12115 in which case the last occurrence in the last file will
12116 be the one that is output, and earlier duplicate occurrences for a given
12117 unit will be skipped.
12118 @end table
12119
12120 @node Configuration Pragmas
12121 @chapter Configuration Pragmas
12122 @cindex Configuration pragmas
12123 @cindex Pragmas, configuration
12124
12125 @menu
12126 * Handling of Configuration Pragmas::
12127 * The Configuration Pragmas Files::
12128 @end menu
12129
12130 @noindent
12131 Configuration pragmas include those pragmas described as
12132 such in the Ada Reference Manual, as well as
12133 implementation-dependent pragmas that are configuration pragmas.
12134 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
12135 for details on these additional GNAT-specific configuration pragmas.
12136 Most notably, the pragma @code{Source_File_Name}, which allows
12137 specifying non-default names for source files, is a configuration
12138 pragma. The following is a complete list of configuration pragmas
12139 recognized by GNAT:
12140
12141 @smallexample
12142 Ada_83
12143 Ada_95
12144 Ada_05
12145 Ada_2005
12146 Ada_12
12147 Ada_2012
12148 Allow_Integer_Address
12149 Annotate
12150 Assertion_Policy
12151 Assume_No_Invalid_Values
12152 C_Pass_By_Copy
12153 Check_Name
12154 Check_Policy
12155 Compile_Time_Error
12156 Compile_Time_Warning
12157 Compiler_Unit
12158 Component_Alignment
12159 Convention_Identifier
12160 Debug_Policy
12161 Detect_Blocking
12162 Default_Storage_Pool
12163 Discard_Names
12164 Elaboration_Checks
12165 Eliminate
12166 Extend_System
12167 Extensions_Allowed
12168 External_Name_Casing
12169 Fast_Math
12170 Favor_Top_Level
12171 Float_Representation
12172 Implicit_Packing
12173 Initialize_Scalars
12174 Interrupt_State
12175 License
12176 Locking_Policy
12177 Long_Float
12178 No_Run_Time
12179 No_Strict_Aliasing
12180 Normalize_Scalars
12181 Optimize_Alignment
12182 Persistent_BSS
12183 Polling
12184 Priority_Specific_Dispatching
12185 Profile
12186 Profile_Warnings
12187 Propagate_Exceptions
12188 Queuing_Policy
12189 Ravenscar
12190 Restricted_Run_Time
12191 Restrictions
12192 Restrictions_Warnings
12193 Reviewable
12194 Short_Circuit_And_Or
12195 Source_File_Name
12196 Source_File_Name_Project
12197 SPARK_Mode
12198 Style_Checks
12199 Suppress
12200 Suppress_Exception_Locations
12201 Task_Dispatching_Policy
12202 Universal_Data
12203 Unsuppress
12204 Use_VADS_Size
12205 Validity_Checks
12206 Warnings
12207 Wide_Character_Encoding
12208 @end smallexample
12209
12210 @node Handling of Configuration Pragmas
12211 @section Handling of Configuration Pragmas
12212
12213 Configuration pragmas may either appear at the start of a compilation
12214 unit, or they can appear in a configuration pragma file to apply to
12215 all compilations performed in a given compilation environment.
12216
12217 GNAT also provides the @code{gnatchop} utility to provide an automatic
12218 way to handle configuration pragmas following the semantics for
12219 compilations (that is, files with multiple units), described in the RM.
12220 See @ref{Operating gnatchop in Compilation Mode} for details.
12221 However, for most purposes, it will be more convenient to edit the
12222 @file{gnat.adc} file that contains configuration pragmas directly,
12223 as described in the following section.
12224
12225 In the case of @code{Restrictions} pragmas appearing as configuration
12226 pragmas in individual compilation units, the exact handling depends on
12227 the type of restriction.
12228
12229 Restrictions that require partition-wide consistency (like
12230 @code{No_Tasking}) are
12231 recognized wherever they appear
12232 and can be freely inherited, e.g. from a with'ed unit to the with'ing
12233 unit. This makes sense since the binder will in any case insist on seeing
12234 consistent use, so any unit not conforming to any restrictions that are
12235 anywhere in the partition will be rejected, and you might as well find
12236 that out at compile time rather than at bind time.
12237
12238 For restrictions that do not require partition-wide consistency, e.g.
12239 SPARK or No_Implementation_Attributes, in general the restriction applies
12240 only to the unit in which the pragma appears, and not to any other units.
12241
12242 The exception is No_Elaboration_Code which always applies to the entire
12243 object file from a compilation, i.e. to the body, spec, and all subunits.
12244 This restriction can be specified in a configuration pragma file, or it
12245 can be on the body and/or the spec (in eithe case it applies to all the
12246 relevant units). It can appear on a subunit only if it has previously
12247 appeared in the body of spec.
12248
12249 @node The Configuration Pragmas Files
12250 @section The Configuration Pragmas Files
12251 @cindex @file{gnat.adc}
12252
12253 @noindent
12254 In GNAT a compilation environment is defined by the current
12255 directory at the time that a compile command is given. This current
12256 directory is searched for a file whose name is @file{gnat.adc}. If
12257 this file is present, it is expected to contain one or more
12258 configuration pragmas that will be applied to the current compilation.
12259 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
12260 considered.
12261
12262 Configuration pragmas may be entered into the @file{gnat.adc} file
12263 either by running @code{gnatchop} on a source file that consists only of
12264 configuration pragmas, or more conveniently by
12265 direct editing of the @file{gnat.adc} file, which is a standard format
12266 source file.
12267
12268 In addition to @file{gnat.adc}, additional files containing configuration
12269 pragmas may be applied to the current compilation using the switch
12270 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
12271 contains only configuration pragmas. These configuration pragmas are
12272 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
12273 is present and switch @option{-gnatA} is not used).
12274
12275 It is allowed to specify several switches @option{-gnatec}, all of which
12276 will be taken into account.
12277
12278 If you are using project file, a separate mechanism is provided using
12279 project attributes, see @ref{Specifying Configuration Pragmas} for more
12280 details.
12281
12282 @ifset vms
12283 Of special interest to GNAT OpenVMS Alpha is the following
12284 configuration pragma:
12285
12286 @smallexample @c ada
12287 @cartouche
12288 pragma Extend_System (Aux_DEC);
12289 @end cartouche
12290 @end smallexample
12291
12292 @noindent
12293 In the presence of this pragma, GNAT adds to the definition of the
12294 predefined package SYSTEM all the additional types and subprograms that are
12295 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
12296 @end ifset
12297
12298 @node Handling Arbitrary File Naming Conventions with gnatname
12299 @chapter Handling Arbitrary File Naming Conventions with @code{gnatname}
12300 @cindex Arbitrary File Naming Conventions
12301
12302 @menu
12303 * Arbitrary File Naming Conventions::
12304 * Running gnatname::
12305 * Switches for gnatname::
12306 * Examples of gnatname Usage::
12307 @end menu
12308
12309 @node Arbitrary File Naming Conventions
12310 @section Arbitrary File Naming Conventions
12311
12312 @noindent
12313 The GNAT compiler must be able to know the source file name of a compilation
12314 unit. When using the standard GNAT default file naming conventions
12315 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
12316 does not need additional information.
12317
12318 @noindent
12319 When the source file names do not follow the standard GNAT default file naming
12320 conventions, the GNAT compiler must be given additional information through
12321 a configuration pragmas file (@pxref{Configuration Pragmas})
12322 or a project file.
12323 When the non-standard file naming conventions are well-defined,
12324 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
12325 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
12326 if the file naming conventions are irregular or arbitrary, a number
12327 of pragma @code{Source_File_Name} for individual compilation units
12328 must be defined.
12329 To help maintain the correspondence between compilation unit names and
12330 source file names within the compiler,
12331 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
12332 set of files.
12333
12334 @node Running gnatname
12335 @section Running @code{gnatname}
12336
12337 @noindent
12338 The usual form of the @code{gnatname} command is
12339
12340 @smallexample
12341 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
12342 @c @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
12343 @c Expanding @ovar macro inline (explanation in macro def comments)
12344 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
12345 @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
12346 @end smallexample
12347
12348 @noindent
12349 All of the arguments are optional. If invoked without any argument,
12350 @code{gnatname} will display its usage.
12351
12352 @noindent
12353 When used with at least one naming pattern, @code{gnatname} will attempt to
12354 find all the compilation units in files that follow at least one of the
12355 naming patterns. To find these compilation units,
12356 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
12357 regular files.
12358
12359 @noindent
12360 One or several Naming Patterns may be given as arguments to @code{gnatname}.
12361 Each Naming Pattern is enclosed between double quotes (or single
12362 quotes on Windows).
12363 A Naming Pattern is a regular expression similar to the wildcard patterns
12364 used in file names by the Unix shells or the DOS prompt.
12365
12366 @noindent
12367 @code{gnatname} may be called with several sections of directories/patterns.
12368 Sections are separated by switch @code{--and}. In each section, there must be
12369 at least one pattern. If no directory is specified in a section, the current
12370 directory (or the project directory is @code{-P} is used) is implied.
12371 The options other that the directory switches and the patterns apply globally
12372 even if they are in different sections.
12373
12374 @noindent
12375 Examples of Naming Patterns are
12376
12377 @smallexample
12378 "*.[12].ada"
12379 "*.ad[sb]*"
12380 "body_*" "spec_*"
12381 @end smallexample
12382
12383 @noindent
12384 For a more complete description of the syntax of Naming Patterns,
12385 see the second kind of regular expressions described in @file{g-regexp.ads}
12386 (the ``Glob'' regular expressions).
12387
12388 @noindent
12389 When invoked with no switch @code{-P}, @code{gnatname} will create a
12390 configuration pragmas file @file{gnat.adc} in the current working directory,
12391 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
12392 unit.
12393
12394 @node Switches for gnatname
12395 @section Switches for @code{gnatname}
12396
12397 @noindent
12398 Switches for @code{gnatname} must precede any specified Naming Pattern.
12399
12400 @noindent
12401 You may specify any of the following switches to @code{gnatname}:
12402
12403 @table @option
12404 @c !sort!
12405
12406 @item --version
12407 @cindex @option{--version} @command{gnatname}
12408 Display Copyright and version, then exit disregarding all other options.
12409
12410 @item --help
12411 @cindex @option{--help} @command{gnatname}
12412 If @option{--version} was not used, display usage, then exit disregarding
12413 all other options.
12414
12415 @item --subdirs=<dir>
12416 Real object, library or exec directories are subdirectories <dir> of the
12417 specified ones.
12418
12419 @item --no-backup
12420 Do not create a backup copy of an existing project file.
12421
12422 @item --and
12423 Start another section of directories/patterns.
12424
12425 @item ^-c^/CONFIG_FILE=^@file{file}
12426 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
12427 Create a configuration pragmas file @file{file} (instead of the default
12428 @file{gnat.adc}).
12429 @ifclear vms
12430 There may be zero, one or more space between @option{-c} and
12431 @file{file}.
12432 @end ifclear
12433 @file{file} may include directory information. @file{file} must be
12434 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
12435 When a switch @option{^-c^/CONFIG_FILE^} is
12436 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
12437
12438 @item ^-d^/SOURCE_DIRS=^@file{dir}
12439 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
12440 Look for source files in directory @file{dir}. There may be zero, one or more
12441 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
12442 @file{dir} may end with @code{/**}, that is it may be of the form
12443 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
12444 subdirectories, recursively, have to be searched for sources.
12445 When a switch @option{^-d^/SOURCE_DIRS^}
12446 is specified, the current working directory will not be searched for source
12447 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
12448 or @option{^-D^/DIR_FILES^} switch.
12449 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
12450 If @file{dir} is a relative path, it is relative to the directory of
12451 the configuration pragmas file specified with switch
12452 @option{^-c^/CONFIG_FILE^},
12453 or to the directory of the project file specified with switch
12454 @option{^-P^/PROJECT_FILE^} or,
12455 if neither switch @option{^-c^/CONFIG_FILE^}
12456 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
12457 current working directory. The directory
12458 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
12459
12460 @item ^-D^/DIRS_FILE=^@file{file}
12461 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
12462 Look for source files in all directories listed in text file @file{file}.
12463 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
12464 and @file{file}.
12465 @file{file} must be an existing, readable text file.
12466 Each nonempty line in @file{file} must be a directory.
12467 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
12468 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
12469 @file{file}.
12470
12471 @item -eL
12472 Follow symbolic links when processing project files.
12473
12474 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
12475 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
12476 Foreign patterns. Using this switch, it is possible to add sources of languages
12477 other than Ada to the list of sources of a project file.
12478 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
12479 For example,
12480 @smallexample
12481 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
12482 @end smallexample
12483 @noindent
12484 will look for Ada units in all files with the @file{.ada} extension,
12485 and will add to the list of file for project @file{prj.gpr} the C files
12486 with extension @file{.^c^C^}.
12487
12488 @item ^-h^/HELP^
12489 @cindex @option{^-h^/HELP^} (@code{gnatname})
12490 Output usage (help) information. The output is written to @file{stdout}.
12491
12492 @item ^-P^/PROJECT_FILE=^@file{proj}
12493 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
12494 Create or update project file @file{proj}. There may be zero, one or more space
12495 between @option{-P} and @file{proj}. @file{proj} may include directory
12496 information. @file{proj} must be writable.
12497 There may be only one switch @option{^-P^/PROJECT_FILE^}.
12498 When a switch @option{^-P^/PROJECT_FILE^} is specified,
12499 no switch @option{^-c^/CONFIG_FILE^} may be specified.
12500 On all platforms, except on VMS, when @code{gnatname} is invoked for an
12501 existing project file <proj>.gpr, a backup copy of the project file is created
12502 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
12503 non negative number that makes this backup copy a new file.
12504
12505 @item ^-v^/VERBOSE^
12506 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
12507 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
12508 This includes name of the file written, the name of the directories to search
12509 and, for each file in those directories whose name matches at least one of
12510 the Naming Patterns, an indication of whether the file contains a unit,
12511 and if so the name of the unit.
12512
12513 @item ^-v -v^/VERBOSE /VERBOSE^
12514 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
12515 Very Verbose mode. In addition to the output produced in verbose mode,
12516 for each file in the searched directories whose name matches none of
12517 the Naming Patterns, an indication is given that there is no match.
12518
12519 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
12520 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
12521 Excluded patterns. Using this switch, it is possible to exclude some files
12522 that would match the name patterns. For example,
12523 @smallexample
12524 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
12525 @end smallexample
12526 @noindent
12527 will look for Ada units in all files with the @file{.ada} extension,
12528 except those whose names end with @file{_nt.ada}.
12529
12530 @end table
12531
12532 @node Examples of gnatname Usage
12533 @section Examples of @code{gnatname} Usage
12534
12535 @ifset vms
12536 @smallexample
12537 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
12538 @end smallexample
12539 @end ifset
12540
12541 @ifclear vms
12542 @smallexample
12543 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
12544 @end smallexample
12545 @end ifclear
12546
12547 @noindent
12548 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
12549 and be writable. In addition, the directory
12550 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
12551 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
12552
12553 @ifclear vms
12554 Note the optional spaces after @option{-c} and @option{-d}.
12555 @end ifclear
12556
12557 @smallexample
12558 @ifclear vms
12559 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
12560 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12561 @end ifclear
12562 @ifset vms
12563 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
12564 /EXCLUDED_PATTERN=*_nt_body.ada
12565 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
12566 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
12567 @end ifset
12568 @end smallexample
12569
12570 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
12571 even in conjunction with one or several switches
12572 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
12573 are used in this example.
12574
12575 @c *****************************************
12576 @c * G N A T P r o j e c t M a n a g e r *
12577 @c *****************************************
12578
12579 @c ------ macros for projects.texi
12580 @c These macros are needed when building the gprbuild documentation, but
12581 @c should have no effect in the gnat user's guide
12582
12583 @macro CODESAMPLE{TXT}
12584 @smallexample
12585 @group
12586 \TXT\
12587 @end group
12588 @end smallexample
12589 @end macro
12590
12591 @macro PROJECTFILE{TXT}
12592 @CODESAMPLE{\TXT\}
12593 @end macro
12594
12595 @c simulates a newline when in a @CODESAMPLE
12596 @macro NL{}
12597 @end macro
12598
12599 @macro TIP{TXT}
12600 @quotation
12601 @noindent
12602 \TXT\
12603 @end quotation
12604 @end macro
12605
12606 @macro TIPHTML{TXT}
12607 \TXT\
12608 @end macro
12609
12610 @macro IMPORTANT{TXT}
12611 @quotation
12612 @noindent
12613 \TXT\
12614 @end quotation
12615
12616 @end macro
12617
12618 @macro NOTE{TXT}
12619 @quotation
12620 @noindent
12621 \TXT\
12622 @end quotation
12623 @end macro
12624
12625 @include projects.texi
12626
12627 @c ---------------------------------------------
12628 @c Tools Supporting Project Files
12629 @c ---------------------------------------------
12630
12631 @node Tools Supporting Project Files
12632 @chapter Tools Supporting Project Files
12633
12634 @noindent
12635
12636 @menu
12637 * gnatmake and Project Files::
12638 * The GNAT Driver and Project Files::
12639 @end menu
12640
12641 @c ---------------------------------------------
12642 @node gnatmake and Project Files
12643 @section gnatmake and Project Files
12644 @c ---------------------------------------------
12645
12646 @noindent
12647 This section covers several topics related to @command{gnatmake} and
12648 project files: defining ^switches^switches^ for @command{gnatmake}
12649 and for the tools that it invokes; specifying configuration pragmas;
12650 the use of the @code{Main} attribute; building and rebuilding library project
12651 files.
12652
12653 @menu
12654 * Switches Related to Project Files::
12655 * Switches and Project Files::
12656 * Specifying Configuration Pragmas::
12657 * Project Files and Main Subprograms::
12658 * Library Project Files::
12659 @end menu
12660
12661 @c ---------------------------------------------
12662 @node Switches Related to Project Files
12663 @subsection Switches Related to Project Files
12664 @c ---------------------------------------------
12665
12666 @noindent
12667 The following switches are used by GNAT tools that support project files:
12668
12669 @table @option
12670
12671 @item ^-P^/PROJECT_FILE=^@var{project}
12672 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
12673 Indicates the name of a project file. This project file will be parsed with
12674 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12675 if any, and using the external references indicated
12676 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12677 @ifclear vms
12678 There may zero, one or more spaces between @option{-P} and @var{project}.
12679 @end ifclear
12680
12681 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12682
12683 Since the Project Manager parses the project file only after all the switches
12684 on the command line are checked, the order of the switches
12685 @option{^-P^/PROJECT_FILE^},
12686 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12687 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12688
12689 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12690 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
12691 Indicates that external variable @var{name} has the value @var{value}.
12692 The Project Manager will use this value for occurrences of
12693 @code{external(name)} when parsing the project file.
12694
12695 @ifclear vms
12696 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12697 put between quotes.
12698 @smallexample
12699 -XOS=NT
12700 -X"user=John Doe"
12701 @end smallexample
12702 @end ifclear
12703
12704 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12705 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12706 @var{name}, only the last one is used.
12707
12708 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12709 takes precedence over the value of the same name in the environment.
12710
12711 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12712 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
12713 Indicates the verbosity of the parsing of GNAT project files.
12714
12715 @ifclear vms
12716 @option{-vP0} means Default;
12717 @option{-vP1} means Medium;
12718 @option{-vP2} means High.
12719 @end ifclear
12720
12721 @ifset vms
12722 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12723 HIGH.
12724 @end ifset
12725
12726 The default is ^Default^DEFAULT^: no output for syntactically correct
12727 project files.
12728 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12729 only the last one is used.
12730
12731 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
12732 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
12733 Add directory <dir> at the beginning of the project search path, in order,
12734 after the current working directory.
12735
12736 @ifclear vms
12737 @item -eL
12738 @cindex @option{-eL} (any project-aware tool)
12739 Follow all symbolic links when processing project files.
12740 @end ifclear
12741
12742 @item ^--subdirs^/SUBDIRS^=<subdir>
12743 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
12744 This switch is recognized by @command{gnatmake} and @command{gnatclean}. It
12745 indicate that the real directories (except the source directories) are the
12746 subdirectories <subdir> of the directories specified in the project files.
12747 This applies in particular to object directories, library directories and
12748 exec directories. If the subdirectories do not exist, they are created
12749 automatically.
12750
12751 @end table
12752
12753 @c ---------------------------------------------
12754 @node Switches and Project Files
12755 @subsection Switches and Project Files
12756 @c ---------------------------------------------
12757
12758 @noindent
12759 @ifset vms
12760 It is not currently possible to specify VMS style qualifiers in the project
12761 files; only Unix style ^switches^switches^ may be specified.
12762 @end ifset
12763
12764 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12765 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12766 attribute, a @code{Switches} attribute, or both;
12767 as their names imply, these ^switch^switch^-related
12768 attributes affect the ^switches^switches^ that are used for each of these GNAT
12769 components when
12770 @command{gnatmake} is invoked. As will be explained below, these
12771 component-specific ^switches^switches^ precede
12772 the ^switches^switches^ provided on the @command{gnatmake} command line.
12773
12774 The @code{^Default_Switches^Default_Switches^} attribute is an attribute
12775 indexed by language name (case insensitive) whose value is a string list.
12776 For example:
12777
12778 @smallexample @c projectfile
12779 @group
12780 package Compiler is
12781 for ^Default_Switches^Default_Switches^ ("Ada")
12782 use ("^-gnaty^-gnaty^",
12783 "^-v^-v^");
12784 end Compiler;
12785 @end group
12786 @end smallexample
12787
12788 @noindent
12789 The @code{Switches} attribute is indexed on a file name (which may or may
12790 not be case sensitive, depending
12791 on the operating system) whose value is a string list. For example:
12792
12793 @smallexample @c projectfile
12794 @group
12795 package Builder is
12796 for Switches ("main1.adb")
12797 use ("^-O2^-O2^");
12798 for Switches ("main2.adb")
12799 use ("^-g^-g^");
12800 end Builder;
12801 @end group
12802 @end smallexample
12803
12804 @noindent
12805 For the @code{Builder} package, the file names must designate source files
12806 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
12807 file names must designate @file{ALI} or source files for main subprograms.
12808 In each case just the file name without an explicit extension is acceptable.
12809
12810 For each tool used in a program build (@command{gnatmake}, the compiler, the
12811 binder, and the linker), the corresponding package @dfn{contributes} a set of
12812 ^switches^switches^ for each file on which the tool is invoked, based on the
12813 ^switch^switch^-related attributes defined in the package.
12814 In particular, the ^switches^switches^
12815 that each of these packages contributes for a given file @var{f} comprise:
12816
12817 @itemize @bullet
12818 @item the value of attribute @code{Switches (@var{f})},
12819 if it is specified in the package for the given file,
12820 @item otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12821 if it is specified in the package.
12822
12823 @end itemize
12824
12825 @noindent
12826 If neither of these attributes is defined in the package, then the package does
12827 not contribute any ^switches^switches^ for the given file.
12828
12829 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12830 two sets, in the following order: those contributed for the file
12831 by the @code{Builder} package;
12832 and the switches passed on the command line.
12833
12834 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12835 the ^switches^switches^ passed to the tool comprise three sets,
12836 in the following order:
12837
12838 @enumerate
12839 @item
12840 the applicable ^switches^switches^ contributed for the file
12841 by the @code{Builder} package in the project file supplied on the command line;
12842
12843 @item
12844 those contributed for the file by the package (in the relevant project file --
12845 see below) corresponding to the tool; and
12846
12847 @item
12848 the applicable switches passed on the command line.
12849 @end enumerate
12850
12851 The term @emph{applicable ^switches^switches^} reflects the fact that
12852 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12853 tools, depending on the individual ^switch^switch^.
12854
12855 @command{gnatmake} may invoke the compiler on source files from different
12856 projects. The Project Manager will use the appropriate project file to
12857 determine the @code{Compiler} package for each source file being compiled.
12858 Likewise for the @code{Binder} and @code{Linker} packages.
12859
12860 As an example, consider the following package in a project file:
12861
12862 @smallexample @c projectfile
12863 @group
12864 project Proj1 is
12865 package Compiler is
12866 for ^Default_Switches^Default_Switches^ ("Ada")
12867 use ("^-g^-g^");
12868 for Switches ("a.adb")
12869 use ("^-O1^-O1^");
12870 for Switches ("b.adb")
12871 use ("^-O2^-O2^",
12872 "^-gnaty^-gnaty^");
12873 end Compiler;
12874 end Proj1;
12875 @end group
12876 @end smallexample
12877
12878 @noindent
12879 If @command{gnatmake} is invoked with this project file, and it needs to
12880 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12881 @file{a.adb} will be compiled with the ^switch^switch^
12882 @option{^-O1^-O1^},
12883 @file{b.adb} with ^switches^switches^
12884 @option{^-O2^-O2^}
12885 and @option{^-gnaty^-gnaty^},
12886 and @file{c.adb} with @option{^-g^-g^}.
12887
12888 The following example illustrates the ordering of the ^switches^switches^
12889 contributed by different packages:
12890
12891 @smallexample @c projectfile
12892 @group
12893 project Proj2 is
12894 package Builder is
12895 for Switches ("main.adb")
12896 use ("^-g^-g^",
12897 "^-O1^-)1^",
12898 "^-f^-f^");
12899 end Builder;
12900 @end group
12901
12902 @group
12903 package Compiler is
12904 for Switches ("main.adb")
12905 use ("^-O2^-O2^");
12906 end Compiler;
12907 end Proj2;
12908 @end group
12909 @end smallexample
12910
12911 @noindent
12912 If you issue the command:
12913
12914 @smallexample
12915 gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
12916 @end smallexample
12917
12918 @noindent
12919 then the compiler will be invoked on @file{main.adb} with the following
12920 sequence of ^switches^switches^
12921
12922 @smallexample
12923 ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
12924 @end smallexample
12925
12926 @noindent
12927 with the last @option{^-O^-O^}
12928 ^switch^switch^ having precedence over the earlier ones;
12929 several other ^switches^switches^
12930 (such as @option{^-c^-c^}) are added implicitly.
12931
12932 The ^switches^switches^
12933 @option{^-g^-g^}
12934 and @option{^-O1^-O1^} are contributed by package
12935 @code{Builder}, @option{^-O2^-O2^} is contributed
12936 by the package @code{Compiler}
12937 and @option{^-O0^-O0^} comes from the command line.
12938
12939 The @option{^-g^-g^}
12940 ^switch^switch^ will also be passed in the invocation of
12941 @command{Gnatlink.}
12942
12943 A final example illustrates switch contributions from packages in different
12944 project files:
12945
12946 @smallexample @c projectfile
12947 @group
12948 project Proj3 is
12949 for Source_Files use ("pack.ads", "pack.adb");
12950 package Compiler is
12951 for ^Default_Switches^Default_Switches^ ("Ada")
12952 use ("^-gnata^-gnata^");
12953 end Compiler;
12954 end Proj3;
12955 @end group
12956
12957 @group
12958 with "Proj3";
12959 project Proj4 is
12960 for Source_Files use ("foo_main.adb", "bar_main.adb");
12961 package Builder is
12962 for Switches ("foo_main.adb")
12963 use ("^-s^-s^",
12964 "^-g^-g^");
12965 end Builder;
12966 end Proj4;
12967 @end group
12968
12969 @group
12970 -- Ada source file:
12971 with Pack;
12972 procedure Foo_Main is
12973 @dots{}
12974 end Foo_Main;
12975 @end group
12976 @end smallexample
12977
12978 @noindent
12979 If the command is
12980 @smallexample
12981 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
12982 @end smallexample
12983
12984 @noindent
12985 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
12986 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
12987 @option{^-gnato^-gnato^} (passed on the command line).
12988 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
12989 are @option{^-g^-g^} from @code{Proj4.Builder},
12990 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
12991 and @option{^-gnato^-gnato^} from the command line.
12992
12993 When using @command{gnatmake} with project files, some ^switches^switches^ or
12994 arguments may be expressed as relative paths. As the working directory where
12995 compilation occurs may change, these relative paths are converted to absolute
12996 paths. For the ^switches^switches^ found in a project file, the relative paths
12997 are relative to the project file directory, for the switches on the command
12998 line, they are relative to the directory where @command{gnatmake} is invoked.
12999 The ^switches^switches^ for which this occurs are:
13000 ^-I^-I^,
13001 ^-A^-A^,
13002 ^-L^-L^,
13003 ^-aO^-aO^,
13004 ^-aL^-aL^,
13005 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
13006 ^switch^switch^
13007 ^-o^-o^, object files specified in package @code{Linker} or after
13008 -largs on the command line). The exception to this rule is the ^switch^switch^
13009 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
13010
13011 @c ---------------------------------------------
13012 @node Specifying Configuration Pragmas
13013 @subsection Specifying Configuration Pragmas
13014 @c ---------------------------------------------
13015
13016 @noindent
13017 When using @command{gnatmake} with project files, if there exists a file
13018 @file{gnat.adc} that contains configuration pragmas, this file will be
13019 ignored.
13020
13021 Configuration pragmas can be defined by means of the following attributes in
13022 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
13023 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
13024
13025 Both these attributes are single string attributes. Their values is the path
13026 name of a file containing configuration pragmas. If a path name is relative,
13027 then it is relative to the project directory of the project file where the
13028 attribute is defined.
13029
13030 When compiling a source, the configuration pragmas used are, in order,
13031 those listed in the file designated by attribute
13032 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13033 project file, if it is specified, and those listed in the file designated by
13034 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13035 the project file of the source, if it exists.
13036
13037 @c ---------------------------------------------
13038 @node Project Files and Main Subprograms
13039 @subsection Project Files and Main Subprograms
13040 @c ---------------------------------------------
13041
13042 @noindent
13043 When using a project file, you can invoke @command{gnatmake}
13044 with one or several main subprograms, by specifying their source files on the
13045 command line.
13046
13047 @smallexample
13048 gnatmake ^-P^/PROJECT_FILE=^prj main1.adb main2.adb main3.adb
13049 @end smallexample
13050
13051 @noindent
13052 Each of these needs to be a source file of the same project, except
13053 when the switch ^-u^/UNIQUE^ is used.
13054
13055 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13056 same project, one of the project in the tree rooted at the project specified
13057 on the command line. The package @code{Builder} of this common project, the
13058 "main project" is the one that is considered by @command{gnatmake}.
13059
13060 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13061 imported directly or indirectly by the project specified on the command line.
13062 Note that if such a source file is not part of the project specified on the
13063 command line, the ^switches^switches^ found in package @code{Builder} of the
13064 project specified on the command line, if any, that are transmitted
13065 to the compiler will still be used, not those found in the project file of
13066 the source file.
13067
13068 When using a project file, you can also invoke @command{gnatmake} without
13069 explicitly specifying any main, and the effect depends on whether you have
13070 defined the @code{Main} attribute. This attribute has a string list value,
13071 where each element in the list is the name of a source file (the file
13072 extension is optional) that contains a unit that can be a main subprogram.
13073
13074 If the @code{Main} attribute is defined in a project file as a non-empty
13075 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13076 line, then invoking @command{gnatmake} with this project file but without any
13077 main on the command line is equivalent to invoking @command{gnatmake} with all
13078 the file names in the @code{Main} attribute on the command line.
13079
13080 Example:
13081 @smallexample @c projectfile
13082 @group
13083 project Prj is
13084 for Main use ("main1.adb", "main2.adb", "main3.adb");
13085 end Prj;
13086 @end group
13087 @end smallexample
13088
13089 @noindent
13090 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13091 is equivalent to
13092 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1.adb main2.adb main3.adb"}.
13093
13094 When the project attribute @code{Main} is not specified, or is specified
13095 as an empty string list, or when the switch @option{-u} is used on the command
13096 line, then invoking @command{gnatmake} with no main on the command line will
13097 result in all immediate sources of the project file being checked, and
13098 potentially recompiled. Depending on the presence of the switch @option{-u},
13099 sources from other project files on which the immediate sources of the main
13100 project file depend are also checked and potentially recompiled. In other
13101 words, the @option{-u} switch is applied to all of the immediate sources of the
13102 main project file.
13103
13104 When no main is specified on the command line and attribute @code{Main} exists
13105 and includes several mains, or when several mains are specified on the
13106 command line, the default ^switches^switches^ in package @code{Builder} will
13107 be used for all mains, even if there are specific ^switches^switches^
13108 specified for one or several mains.
13109
13110 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13111 the specific ^switches^switches^ for each main, if they are specified.
13112
13113 @c ---------------------------------------------
13114 @node Library Project Files
13115 @subsection Library Project Files
13116 @c ---------------------------------------------
13117
13118 @noindent
13119 When @command{gnatmake} is invoked with a main project file that is a library
13120 project file, it is not allowed to specify one or more mains on the command
13121 line.
13122
13123 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13124 ^-l^/ACTION=LINK^ have special meanings.
13125
13126 @itemize @bullet
13127 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13128 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13129 library.
13130
13131 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13132 to @command{gnatmake} that the binder generated file should be compiled
13133 (in the case of a stand-alone library) and that the library should be built.
13134 @end itemize
13135
13136 @c ---------------------------------------------
13137 @node The GNAT Driver and Project Files
13138 @section The GNAT Driver and Project Files
13139 @c ---------------------------------------------
13140
13141 @noindent
13142 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13143 can benefit from project files:
13144 (@command{^gnatbind^gnatbind^},
13145 @ifclear FSFEDITION
13146 @command{^gnatcheck^gnatcheck^},
13147 @end ifclear
13148 @command{^gnatclean^gnatclean^},
13149 @ifclear FSFEDITION
13150 @command{^gnatelim^gnatelim^},
13151 @end ifclear
13152 @command{^gnatfind^gnatfind^},
13153 @command{^gnatlink^gnatlink^},
13154 @command{^gnatls^gnatls^},
13155 @ifclear FSFEDITION
13156 @command{^gnatmetric^gnatmetric^},
13157 @command{^gnatpp^gnatpp^},
13158 @command{^gnatstub^gnatstub^},
13159 @end ifclear
13160 and @command{^gnatxref^gnatxref^}). However, none of these tools can be invoked
13161 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13162 They must be invoked through the @command{gnat} driver.
13163
13164 The @command{gnat} driver is a wrapper that accepts a number of commands and
13165 calls the corresponding tool. It was designed initially for VMS platforms (to
13166 convert VMS qualifiers to Unix-style switches), but it is now available on all
13167 GNAT platforms.
13168
13169 On non-VMS platforms, the @command{gnat} driver accepts the following commands
13170 (case insensitive):
13171
13172 @itemize @bullet
13173 @item BIND to invoke @command{^gnatbind^gnatbind^}
13174 @item CHOP to invoke @command{^gnatchop^gnatchop^}
13175 @item CLEAN to invoke @command{^gnatclean^gnatclean^}
13176 @item COMP or COMPILE to invoke the compiler
13177 @ifclear FSFEDITION
13178 @item ELIM to invoke @command{^gnatelim^gnatelim^}
13179 @end ifclear
13180 @item FIND to invoke @command{^gnatfind^gnatfind^}
13181 @item KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13182 @item LINK to invoke @command{^gnatlink^gnatlink^}
13183 @item LS or LIST to invoke @command{^gnatls^gnatls^}
13184 @item MAKE to invoke @command{^gnatmake^gnatmake^}
13185 @item NAME to invoke @command{^gnatname^gnatname^}
13186 @item PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13187 @ifclear FSFEDITION
13188 @item PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13189 @item METRIC to invoke @command{^gnatmetric^gnatmetric^}
13190 @item STUB to invoke @command{^gnatstub^gnatstub^}
13191 @end ifclear
13192 @item XREF to invoke @command{^gnatxref^gnatxref^}
13193
13194 @end itemize
13195
13196 @noindent
13197 (note that the compiler is invoked using the command
13198 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
13199
13200 On non-VMS platforms, between @command{gnat} and the command, two
13201 special switches may be used:
13202
13203 @itemize @bullet
13204 @item @command{-v} to display the invocation of the tool.
13205 @item @command{-dn} to prevent the @command{gnat} driver from removing
13206 the temporary files it has created. These temporary files are
13207 configuration files and temporary file list files.
13208
13209 @end itemize
13210
13211 @noindent
13212 The command may be followed by switches and arguments for the invoked
13213 tool.
13214
13215 @smallexample
13216 gnat bind -C main.ali
13217 gnat ls -a main
13218 gnat chop foo.txt
13219 @end smallexample
13220
13221 @noindent
13222 Switches may also be put in text files, one switch per line, and the text
13223 files may be specified with their path name preceded by '@@'.
13224
13225 @smallexample
13226 gnat bind @@args.txt main.ali
13227 @end smallexample
13228
13229 @noindent
13230 In addition, for commands BIND, COMP or COMPILE, FIND,
13231 @ifclear FSFEDITION
13232 ELIM,
13233 @end ifclear
13234 LS or LIST, LINK,
13235 @ifclear FSFEDITION
13236 METRIC,
13237 PP or PRETTY,
13238 STUB,
13239 @end ifclear
13240 and XREF, the project file related switches
13241 (@option{^-P^/PROJECT_FILE^},
13242 @option{^-X^/EXTERNAL_REFERENCE^} and
13243 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13244 the switches of the invoking tool.
13245
13246 @ifclear FSFEDITION
13247 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13248 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13249 the immediate sources of the specified project file.
13250 @end ifclear
13251
13252 @ifclear FSFEDITION
13253 When GNAT METRIC is used with a project file, but with no source
13254 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
13255 with all the immediate sources of the specified project file and with
13256 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
13257 of the project.
13258 @end ifclear
13259
13260 @ifclear FSFEDITION
13261 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
13262 a project file, no source is specified on the command line and
13263 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
13264 the underlying tool (^gnatpp^gnatpp^ or
13265 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
13266 not only for the immediate sources of the main project.
13267 @ifclear vms
13268 (-U stands for Universal or Union of the project files of the project tree)
13269 @end ifclear
13270 @end ifclear
13271
13272 For each of the following commands, there is optionally a corresponding
13273 package in the main project.
13274
13275 @itemize @bullet
13276 @item package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13277
13278 @ifclear FSFEDITION
13279 @item package @code{Check} for command CHECK (invoking
13280 @code{^gnatcheck^gnatcheck^})
13281 @end ifclear
13282
13283 @item package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13284
13285 @item package @code{Cross_Reference} for command XREF (invoking
13286 @code{^gnatxref^gnatxref^})
13287
13288 @ifclear FSFEDITION
13289 @item package @code{Eliminate} for command ELIM (invoking
13290 @code{^gnatelim^gnatelim^})
13291 @end ifclear
13292
13293 @item package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13294
13295 @item package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13296
13297 @ifclear FSFEDITION
13298 @item package @code{Gnatstub} for command STUB
13299 (invoking @code{^gnatstub^gnatstub^})
13300 @end ifclear
13301
13302 @item package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13303
13304 @ifclear FSFEDITION
13305 @item package @code{Check} for command CHECK
13306 (invoking @code{^gnatcheck^gnatcheck^})
13307 @end ifclear
13308
13309 @ifclear FSFEDITION
13310 @item package @code{Metrics} for command METRIC
13311 (invoking @code{^gnatmetric^gnatmetric^})
13312 @end ifclear
13313
13314 @ifclear FSFEDITION
13315 @item package @code{Pretty_Printer} for command PP or PRETTY
13316 (invoking @code{^gnatpp^gnatpp^})
13317 @end ifclear
13318
13319 @end itemize
13320
13321 @noindent
13322 Package @code{Gnatls} has a unique attribute @code{Switches},
13323 a simple variable with a string list value. It contains ^switches^switches^
13324 for the invocation of @code{^gnatls^gnatls^}.
13325
13326 @smallexample @c projectfile
13327 @group
13328 project Proj1 is
13329 package gnatls is
13330 for Switches
13331 use ("^-a^-a^",
13332 "^-v^-v^");
13333 end gnatls;
13334 end Proj1;
13335 @end group
13336 @end smallexample
13337
13338 @noindent
13339 All other packages have two attribute @code{Switches} and
13340 @code{^Default_Switches^Default_Switches^}.
13341
13342 @code{Switches} is an indexed attribute, indexed by the
13343 source file name, that has a string list value: the ^switches^switches^ to be
13344 used when the tool corresponding to the package is invoked for the specific
13345 source file.
13346
13347 @code{^Default_Switches^Default_Switches^} is an attribute,
13348 indexed by the programming language that has a string list value.
13349 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13350 ^switches^switches^ for the invocation of the tool corresponding
13351 to the package, except if a specific @code{Switches} attribute
13352 is specified for the source file.
13353
13354 @smallexample @c projectfile
13355 @group
13356 project Proj is
13357
13358 for Source_Dirs use ("**");
13359
13360 package gnatls is
13361 for Switches use
13362 ("^-a^-a^",
13363 "^-v^-v^");
13364 end gnatls;
13365 @end group
13366 @group
13367
13368 package Compiler is
13369 for ^Default_Switches^Default_Switches^ ("Ada")
13370 use ("^-gnatv^-gnatv^",
13371 "^-gnatwa^-gnatwa^");
13372 end Binder;
13373 @end group
13374 @group
13375
13376 package Binder is
13377 for ^Default_Switches^Default_Switches^ ("Ada")
13378 use ("^-C^-C^",
13379 "^-e^-e^");
13380 end Binder;
13381 @end group
13382 @group
13383
13384 package Linker is
13385 for ^Default_Switches^Default_Switches^ ("Ada")
13386 use ("^-C^-C^");
13387 for Switches ("main.adb")
13388 use ("^-C^-C^",
13389 "^-v^-v^",
13390 "^-v^-v^");
13391 end Linker;
13392 @end group
13393 @group
13394
13395 package Finder is
13396 for ^Default_Switches^Default_Switches^ ("Ada")
13397 use ("^-a^-a^",
13398 "^-f^-f^");
13399 end Finder;
13400 @end group
13401 @group
13402
13403 package Cross_Reference is
13404 for ^Default_Switches^Default_Switches^ ("Ada")
13405 use ("^-a^-a^",
13406 "^-f^-f^",
13407 "^-d^-d^",
13408 "^-u^-u^");
13409 end Cross_Reference;
13410 end Proj;
13411 @end group
13412 @end smallexample
13413
13414 @noindent
13415 With the above project file, commands such as
13416
13417 @smallexample
13418 ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13419 ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13420 ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13421 ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13422 ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13423 @end smallexample
13424
13425 @noindent
13426 will set up the environment properly and invoke the tool with the switches
13427 found in the package corresponding to the tool:
13428 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13429 except @code{Switches ("main.adb")}
13430 for @code{^gnatlink^gnatlink^}.
13431 @ifclear FSFEDITION
13432 It is also possible to invoke some of the tools,
13433 (@code{^gnatcheck^gnatcheck^},
13434 @code{^gnatmetric^gnatmetric^},
13435 and @code{^gnatpp^gnatpp^})
13436 on a set of project units thanks to the combination of the switches
13437 @option{-P}, @option{-U} and possibly the main unit when one is interested
13438 in its closure. For instance,
13439 @smallexample
13440 gnat metric -Pproj
13441 @end smallexample
13442
13443 @noindent
13444 will compute the metrics for all the immediate units of project
13445 @code{proj}.
13446 @smallexample
13447 gnat metric -Pproj -U
13448 @end smallexample
13449
13450 @noindent
13451 will compute the metrics for all the units of the closure of projects
13452 rooted at @code{proj}.
13453 @smallexample
13454 gnat metric -Pproj -U main_unit
13455 @end smallexample
13456
13457 @noindent
13458 will compute the metrics for the closure of units rooted at
13459 @code{main_unit}. This last possibility relies implicitly
13460 on @command{gnatbind}'s option @option{-R}. But if the argument files for the
13461 tool invoked by the @command{gnat} driver are explicitly specified
13462 either directly or through the tool @option{-files} option, then the tool
13463 is called only for these explicitly specified files.
13464 @end ifclear
13465
13466 @c *****************************************
13467 @c * Cross-referencing tools
13468 @c *****************************************
13469
13470 @node The Cross-Referencing Tools gnatxref and gnatfind
13471 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13472 @findex gnatxref
13473 @findex gnatfind
13474
13475 @noindent
13476 The compiler generates cross-referencing information (unless
13477 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13478 This information indicates where in the source each entity is declared and
13479 referenced. Note that entities in package Standard are not included, but
13480 entities in all other predefined units are included in the output.
13481
13482 Before using any of these two tools, you need to compile successfully your
13483 application, so that GNAT gets a chance to generate the cross-referencing
13484 information.
13485
13486 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13487 information to provide the user with the capability to easily locate the
13488 declaration and references to an entity. These tools are quite similar,
13489 the difference being that @code{gnatfind} is intended for locating
13490 definitions and/or references to a specified entity or entities, whereas
13491 @code{gnatxref} is oriented to generating a full report of all
13492 cross-references.
13493
13494 To use these tools, you must not compile your application using the
13495 @option{-gnatx} switch on the @command{gnatmake} command line
13496 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13497 information will not be generated.
13498
13499 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
13500 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
13501
13502 @menu
13503 * Switches for gnatxref::
13504 * Switches for gnatfind::
13505 * Project Files for gnatxref and gnatfind::
13506 * Regular Expressions in gnatfind and gnatxref::
13507 * Examples of gnatxref Usage::
13508 * Examples of gnatfind Usage::
13509 @end menu
13510
13511 @node Switches for gnatxref
13512 @section @code{gnatxref} Switches
13513
13514 @noindent
13515 The command invocation for @code{gnatxref} is:
13516 @smallexample
13517 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
13518 @c Expanding @ovar macro inline (explanation in macro def comments)
13519 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
13520 @end smallexample
13521
13522 @noindent
13523 where
13524
13525 @table @var
13526 @item sourcefile1
13527 @itemx sourcefile2
13528 identifies the source files for which a report is to be generated. The
13529 ``with''ed units will be processed too. You must provide at least one file.
13530
13531 These file names are considered to be regular expressions, so for instance
13532 specifying @file{source*.adb} is the same as giving every file in the current
13533 directory whose name starts with @file{source} and whose extension is
13534 @file{adb}.
13535
13536 You shouldn't specify any directory name, just base names. @command{gnatxref}
13537 and @command{gnatfind} will be able to locate these files by themselves using
13538 the source path. If you specify directories, no result is produced.
13539
13540 @end table
13541
13542 @noindent
13543 The switches can be:
13544 @table @option
13545 @c !sort!
13546 @item --version
13547 @cindex @option{--version} @command{gnatxref}
13548 Display Copyright and version, then exit disregarding all other options.
13549
13550 @item --help
13551 @cindex @option{--help} @command{gnatxref}
13552 If @option{--version} was not used, display usage, then exit disregarding
13553 all other options.
13554
13555 @item ^-a^/ALL_FILES^
13556 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13557 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13558 the read-only files found in the library search path. Otherwise, these files
13559 will be ignored. This option can be used to protect Gnat sources or your own
13560 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13561 much faster, and their output much smaller. Read-only here refers to access
13562 or permissions status in the file system for the current user.
13563
13564 @item -aIDIR
13565 @cindex @option{-aIDIR} (@command{gnatxref})
13566 When looking for source files also look in directory DIR. The order in which
13567 source file search is undertaken is the same as for @command{gnatmake}.
13568
13569 @item -aODIR
13570 @cindex @option{-aODIR} (@command{gnatxref})
13571 When searching for library and object files, look in directory
13572 DIR. The order in which library files are searched is the same as for
13573 @command{gnatmake}.
13574
13575 @item -nostdinc
13576 @cindex @option{-nostdinc} (@command{gnatxref})
13577 Do not look for sources in the system default directory.
13578
13579 @item -nostdlib
13580 @cindex @option{-nostdlib} (@command{gnatxref})
13581 Do not look for library files in the system default directory.
13582
13583 @item --ext=@var{extension}
13584 @cindex @option{--ext} (@command{gnatxref})
13585 Specify an alternate ali file extension. The default is @code{ali} and other
13586 extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
13587 may be specified via this switch. Note that if this switch overrides the
13588 default, which means that only the new extension will be considered.
13589
13590 @item --RTS=@var{rts-path}
13591 @cindex @option{--RTS} (@command{gnatxref})
13592 Specifies the default location of the runtime library. Same meaning as the
13593 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13594
13595 @item ^-d^/DERIVED_TYPES^
13596 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13597 If this switch is set @code{gnatxref} will output the parent type
13598 reference for each matching derived types.
13599
13600 @item ^-f^/FULL_PATHNAME^
13601 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13602 If this switch is set, the output file names will be preceded by their
13603 directory (if the file was found in the search path). If this switch is
13604 not set, the directory will not be printed.
13605
13606 @item ^-g^/IGNORE_LOCALS^
13607 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13608 If this switch is set, information is output only for library-level
13609 entities, ignoring local entities. The use of this switch may accelerate
13610 @code{gnatfind} and @code{gnatxref}.
13611
13612 @item -IDIR
13613 @cindex @option{-IDIR} (@command{gnatxref})
13614 Equivalent to @samp{-aODIR -aIDIR}.
13615
13616 @item -pFILE
13617 @cindex @option{-pFILE} (@command{gnatxref})
13618 Specify a project file to use @xref{GNAT Project Manager}.
13619 If you need to use the @file{.gpr}
13620 project files, you should use gnatxref through the GNAT driver
13621 (@command{gnat xref -Pproject}).
13622
13623 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13624 project file in the current directory.
13625
13626 If a project file is either specified or found by the tools, then the content
13627 of the source directory and object directory lines are added as if they
13628 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13629 and @samp{^-aO^OBJECT_SEARCH^}.
13630 @item ^-u^/UNUSED^
13631 Output only unused symbols. This may be really useful if you give your
13632 main compilation unit on the command line, as @code{gnatxref} will then
13633 display every unused entity and 'with'ed package.
13634
13635 @ifclear vms
13636 @item -v
13637 Instead of producing the default output, @code{gnatxref} will generate a
13638 @file{tags} file that can be used by vi. For examples how to use this
13639 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
13640 to the standard output, thus you will have to redirect it to a file.
13641 @end ifclear
13642
13643 @end table
13644
13645 @noindent
13646 All these switches may be in any order on the command line, and may even
13647 appear after the file names. They need not be separated by spaces, thus
13648 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13649 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13650
13651 @node Switches for gnatfind
13652 @section @code{gnatfind} Switches
13653
13654 @noindent
13655 The command line for @code{gnatfind} is:
13656
13657 @smallexample
13658 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13659 @c @r{[}@var{file1} @var{file2} @dots{}]
13660 @c Expanding @ovar macro inline (explanation in macro def comments)
13661 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13662 @r{[}@var{file1} @var{file2} @dots{}@r{]}
13663 @end smallexample
13664
13665 @noindent
13666 where
13667
13668 @table @var
13669 @item pattern
13670 An entity will be output only if it matches the regular expression found
13671 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
13672
13673 Omitting the pattern is equivalent to specifying @samp{*}, which
13674 will match any entity. Note that if you do not provide a pattern, you
13675 have to provide both a sourcefile and a line.
13676
13677 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13678 for matching purposes. At the current time there is no support for
13679 8-bit codes other than Latin-1, or for wide characters in identifiers.
13680
13681 @item sourcefile
13682 @code{gnatfind} will look for references, bodies or declarations
13683 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
13684 and column @var{column}. See @ref{Examples of gnatfind Usage}
13685 for syntax examples.
13686
13687 @item line
13688 is a decimal integer identifying the line number containing
13689 the reference to the entity (or entities) to be located.
13690
13691 @item column
13692 is a decimal integer identifying the exact location on the
13693 line of the first character of the identifier for the
13694 entity reference. Columns are numbered from 1.
13695
13696 @item file1 file2 @dots{}
13697 The search will be restricted to these source files. If none are given, then
13698 the search will be done for every library file in the search path.
13699 These file must appear only after the pattern or sourcefile.
13700
13701 These file names are considered to be regular expressions, so for instance
13702 specifying @file{source*.adb} is the same as giving every file in the current
13703 directory whose name starts with @file{source} and whose extension is
13704 @file{adb}.
13705
13706 The location of the spec of the entity will always be displayed, even if it
13707 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{} The
13708 occurrences of the entity in the separate units of the ones given on the
13709 command line will also be displayed.
13710
13711 Note that if you specify at least one file in this part, @code{gnatfind} may
13712 sometimes not be able to find the body of the subprograms.
13713
13714 @end table
13715
13716 @noindent
13717 At least one of 'sourcefile' or 'pattern' has to be present on
13718 the command line.
13719
13720 The following switches are available:
13721 @table @option
13722 @c !sort!
13723
13724 @cindex @option{--version} @command{gnatfind}
13725 Display Copyright and version, then exit disregarding all other options.
13726
13727 @item --help
13728 @cindex @option{--help} @command{gnatfind}
13729 If @option{--version} was not used, display usage, then exit disregarding
13730 all other options.
13731
13732 @item ^-a^/ALL_FILES^
13733 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
13734 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13735 the read-only files found in the library search path. Otherwise, these files
13736 will be ignored. This option can be used to protect Gnat sources or your own
13737 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13738 much faster, and their output much smaller. Read-only here refers to access
13739 or permission status in the file system for the current user.
13740
13741 @item -aIDIR
13742 @cindex @option{-aIDIR} (@command{gnatfind})
13743 When looking for source files also look in directory DIR. The order in which
13744 source file search is undertaken is the same as for @command{gnatmake}.
13745
13746 @item -aODIR
13747 @cindex @option{-aODIR} (@command{gnatfind})
13748 When searching for library and object files, look in directory
13749 DIR. The order in which library files are searched is the same as for
13750 @command{gnatmake}.
13751
13752 @item -nostdinc
13753 @cindex @option{-nostdinc} (@command{gnatfind})
13754 Do not look for sources in the system default directory.
13755
13756 @item -nostdlib
13757 @cindex @option{-nostdlib} (@command{gnatfind})
13758 Do not look for library files in the system default directory.
13759
13760 @item --ext=@var{extension}
13761 @cindex @option{--ext} (@command{gnatfind})
13762 Specify an alternate ali file extension. The default is @code{ali} and other
13763 extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
13764 may be specified via this switch. Note that if this switch overrides the
13765 default, which means that only the new extension will be considered.
13766
13767 @item --RTS=@var{rts-path}
13768 @cindex @option{--RTS} (@command{gnatfind})
13769 Specifies the default location of the runtime library. Same meaning as the
13770 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13771
13772 @item ^-d^/DERIVED_TYPE_INFORMATION^
13773 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
13774 If this switch is set, then @code{gnatfind} will output the parent type
13775 reference for each matching derived types.
13776
13777 @item ^-e^/EXPRESSIONS^
13778 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
13779 By default, @code{gnatfind} accept the simple regular expression set for
13780 @samp{pattern}. If this switch is set, then the pattern will be
13781 considered as full Unix-style regular expression.
13782
13783 @item ^-f^/FULL_PATHNAME^
13784 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
13785 If this switch is set, the output file names will be preceded by their
13786 directory (if the file was found in the search path). If this switch is
13787 not set, the directory will not be printed.
13788
13789 @item ^-g^/IGNORE_LOCALS^
13790 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
13791 If this switch is set, information is output only for library-level
13792 entities, ignoring local entities. The use of this switch may accelerate
13793 @code{gnatfind} and @code{gnatxref}.
13794
13795 @item -IDIR
13796 @cindex @option{-IDIR} (@command{gnatfind})
13797 Equivalent to @samp{-aODIR -aIDIR}.
13798
13799 @item -pFILE
13800 @cindex @option{-pFILE} (@command{gnatfind})
13801 Specify a project file (@pxref{GNAT Project Manager}) to use.
13802 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13803 project file in the current directory.
13804
13805 If a project file is either specified or found by the tools, then the content
13806 of the source directory and object directory lines are added as if they
13807 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
13808 @samp{^-aO^/OBJECT_SEARCH^}.
13809
13810 @item ^-r^/REFERENCES^
13811 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
13812 By default, @code{gnatfind} will output only the information about the
13813 declaration, body or type completion of the entities. If this switch is
13814 set, the @code{gnatfind} will locate every reference to the entities in
13815 the files specified on the command line (or in every file in the search
13816 path if no file is given on the command line).
13817
13818 @item ^-s^/PRINT_LINES^
13819 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
13820 If this switch is set, then @code{gnatfind} will output the content
13821 of the Ada source file lines were the entity was found.
13822
13823 @item ^-t^/TYPE_HIERARCHY^
13824 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
13825 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13826 the specified type. It act like -d option but recursively from parent
13827 type to parent type. When this switch is set it is not possible to
13828 specify more than one file.
13829
13830 @end table
13831
13832 @noindent
13833 All these switches may be in any order on the command line, and may even
13834 appear after the file names. They need not be separated by spaces, thus
13835 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13836 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13837
13838 As stated previously, gnatfind will search in every directory in the
13839 search path. You can force it to look only in the current directory if
13840 you specify @code{*} at the end of the command line.
13841
13842 @node Project Files for gnatxref and gnatfind
13843 @section Project Files for @command{gnatxref} and @command{gnatfind}
13844
13845 @noindent
13846 Project files allow a programmer to specify how to compile its
13847 application, where to find sources, etc. These files are used
13848 @ifclear vms
13849 primarily by GPS, but they can also be used
13850 @end ifclear
13851 by the two tools
13852 @code{gnatxref} and @code{gnatfind}.
13853
13854 A project file name must end with @file{.gpr}. If a single one is
13855 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13856 extract the information from it. If multiple project files are found, none of
13857 them is read, and you have to use the @samp{-p} switch to specify the one
13858 you want to use.
13859
13860 The following lines can be included, even though most of them have default
13861 values which can be used in most cases.
13862 The lines can be entered in any order in the file.
13863 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
13864 each line. If you have multiple instances, only the last one is taken into
13865 account.
13866
13867 @table @code
13868 @item src_dir=DIR
13869 [default: @code{"^./^[]^"}]
13870 specifies a directory where to look for source files. Multiple @code{src_dir}
13871 lines can be specified and they will be searched in the order they
13872 are specified.
13873
13874 @item obj_dir=DIR
13875 [default: @code{"^./^[]^"}]
13876 specifies a directory where to look for object and library files. Multiple
13877 @code{obj_dir} lines can be specified, and they will be searched in the order
13878 they are specified
13879
13880 @item comp_opt=SWITCHES
13881 [default: @code{""}]
13882 creates a variable which can be referred to subsequently by using
13883 the @code{$@{comp_opt@}} notation. This is intended to store the default
13884 switches given to @command{gnatmake} and @command{gcc}.
13885
13886 @item bind_opt=SWITCHES
13887 [default: @code{""}]
13888 creates a variable which can be referred to subsequently by using
13889 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13890 switches given to @command{gnatbind}.
13891
13892 @item link_opt=SWITCHES
13893 [default: @code{""}]
13894 creates a variable which can be referred to subsequently by using
13895 the @samp{$@{link_opt@}} notation. This is intended to store the default
13896 switches given to @command{gnatlink}.
13897
13898 @item main=EXECUTABLE
13899 [default: @code{""}]
13900 specifies the name of the executable for the application. This variable can
13901 be referred to in the following lines by using the @samp{$@{main@}} notation.
13902
13903 @ifset vms
13904 @item comp_cmd=COMMAND
13905 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
13906 @end ifset
13907 @ifclear vms
13908 @item comp_cmd=COMMAND
13909 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
13910 @end ifclear
13911 specifies the command used to compile a single file in the application.
13912
13913 @ifset vms
13914 @item make_cmd=COMMAND
13915 [default: @code{"GNAT MAKE $@{main@}
13916 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
13917 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
13918 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
13919 @end ifset
13920 @ifclear vms
13921 @item make_cmd=COMMAND
13922 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
13923 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
13924 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
13925 @end ifclear
13926 specifies the command used to recompile the whole application.
13927
13928 @item run_cmd=COMMAND
13929 [default: @code{"$@{main@}"}]
13930 specifies the command used to run the application.
13931
13932 @item debug_cmd=COMMAND
13933 [default: @code{"gdb $@{main@}"}]
13934 specifies the command used to debug the application
13935
13936 @end table
13937
13938 @noindent
13939 @command{gnatxref} and @command{gnatfind} only take into account the
13940 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
13941
13942 @node Regular Expressions in gnatfind and gnatxref
13943 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
13944
13945 @noindent
13946 As specified in the section about @command{gnatfind}, the pattern can be a
13947 regular expression. Actually, there are to set of regular expressions
13948 which are recognized by the program:
13949
13950 @table @code
13951 @item globbing patterns
13952 These are the most usual regular expression. They are the same that you
13953 generally used in a Unix shell command line, or in a DOS session.
13954
13955 Here is a more formal grammar:
13956 @smallexample
13957 @group
13958 @iftex
13959 @leftskip=.5cm
13960 @end iftex
13961 regexp ::= term
13962 term ::= elmt -- matches elmt
13963 term ::= elmt elmt -- concatenation (elmt then elmt)
13964 term ::= * -- any string of 0 or more characters
13965 term ::= ? -- matches any character
13966 term ::= [char @{char@}] -- matches any character listed
13967 term ::= [char - char] -- matches any character in range
13968 @end group
13969 @end smallexample
13970
13971 @item full regular expression
13972 The second set of regular expressions is much more powerful. This is the
13973 type of regular expressions recognized by utilities such a @file{grep}.
13974
13975 The following is the form of a regular expression, expressed in Ada
13976 reference manual style BNF is as follows
13977
13978 @smallexample
13979 @iftex
13980 @leftskip=.5cm
13981 @end iftex
13982 @group
13983 regexp ::= term @{| term@} -- alternation (term or term @dots{})
13984
13985 term ::= item @{item@} -- concatenation (item then item)
13986
13987 item ::= elmt -- match elmt
13988 item ::= elmt * -- zero or more elmt's
13989 item ::= elmt + -- one or more elmt's
13990 item ::= elmt ? -- matches elmt or nothing
13991 @end group
13992 @group
13993 elmt ::= nschar -- matches given character
13994 elmt ::= [nschar @{nschar@}] -- matches any character listed
13995 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
13996 elmt ::= [char - char] -- matches chars in given range
13997 elmt ::= \ char -- matches given character
13998 elmt ::= . -- matches any single character
13999 elmt ::= ( regexp ) -- parens used for grouping
14000
14001 char ::= any character, including special characters
14002 nschar ::= any character except ()[].*+?^^^
14003 @end group
14004 @end smallexample
14005
14006 Following are a few examples:
14007
14008 @table @samp
14009 @item abcde|fghi
14010 will match any of the two strings @samp{abcde} and @samp{fghi},
14011
14012 @item abc*d
14013 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
14014 @samp{abcccd}, and so on,
14015
14016 @item [a-z]+
14017 will match any string which has only lowercase characters in it (and at
14018 least one character.
14019
14020 @end table
14021 @end table
14022
14023 @node Examples of gnatxref Usage
14024 @section Examples of @code{gnatxref} Usage
14025
14026 @subsection General Usage
14027
14028 @noindent
14029 For the following examples, we will consider the following units:
14030
14031 @smallexample @c ada
14032 @group
14033 @cartouche
14034 main.ads:
14035 1: with Bar;
14036 2: package Main is
14037 3: procedure Foo (B : in Integer);
14038 4: C : Integer;
14039 5: private
14040 6: D : Integer;
14041 7: end Main;
14042
14043 main.adb:
14044 1: package body Main is
14045 2: procedure Foo (B : in Integer) is
14046 3: begin
14047 4: C := B;
14048 5: D := B;
14049 6: Bar.Print (B);
14050 7: Bar.Print (C);
14051 8: end Foo;
14052 9: end Main;
14053
14054 bar.ads:
14055 1: package Bar is
14056 2: procedure Print (B : Integer);
14057 3: end bar;
14058 @end cartouche
14059 @end group
14060 @end smallexample
14061
14062 @table @code
14063
14064 @noindent
14065 The first thing to do is to recompile your application (for instance, in
14066 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14067 the cross-referencing information.
14068 You can then issue any of the following commands:
14069
14070 @item gnatxref main.adb
14071 @code{gnatxref} generates cross-reference information for main.adb
14072 and every unit 'with'ed by main.adb.
14073
14074 The output would be:
14075 @smallexample
14076 @iftex
14077 @leftskip=0cm
14078 @end iftex
14079 B Type: Integer
14080 Decl: bar.ads 2:22
14081 B Type: Integer
14082 Decl: main.ads 3:20
14083 Body: main.adb 2:20
14084 Ref: main.adb 4:13 5:13 6:19
14085 Bar Type: Unit
14086 Decl: bar.ads 1:9
14087 Ref: main.adb 6:8 7:8
14088 main.ads 1:6
14089 C Type: Integer
14090 Decl: main.ads 4:5
14091 Modi: main.adb 4:8
14092 Ref: main.adb 7:19
14093 D Type: Integer
14094 Decl: main.ads 6:5
14095 Modi: main.adb 5:8
14096 Foo Type: Unit
14097 Decl: main.ads 3:15
14098 Body: main.adb 2:15
14099 Main Type: Unit
14100 Decl: main.ads 2:9
14101 Body: main.adb 1:14
14102 Print Type: Unit
14103 Decl: bar.ads 2:15
14104 Ref: main.adb 6:12 7:12
14105 @end smallexample
14106
14107 @noindent
14108 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14109 its body is in main.adb, line 1, column 14 and is not referenced any where.
14110
14111 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14112 is referenced in main.adb, line 6 column 12 and line 7 column 12.
14113
14114 @item gnatxref package1.adb package2.ads
14115 @code{gnatxref} will generates cross-reference information for
14116 package1.adb, package2.ads and any other package 'with'ed by any
14117 of these.
14118
14119 @end table
14120
14121 @ifclear vms
14122 @subsection Using gnatxref with vi
14123
14124 @code{gnatxref} can generate a tags file output, which can be used
14125 directly from @command{vi}. Note that the standard version of @command{vi}
14126 will not work properly with overloaded symbols. Consider using another
14127 free implementation of @command{vi}, such as @command{vim}.
14128
14129 @smallexample
14130 $ gnatxref -v gnatfind.adb > tags
14131 @end smallexample
14132
14133 @noindent
14134 will generate the tags file for @code{gnatfind} itself (if the sources
14135 are in the search path!).
14136
14137 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
14138 (replacing @var{entity} by whatever you are looking for), and vi will
14139 display a new file with the corresponding declaration of entity.
14140 @end ifclear
14141
14142 @node Examples of gnatfind Usage
14143 @section Examples of @code{gnatfind} Usage
14144
14145 @table @code
14146
14147 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14148 Find declarations for all entities xyz referenced at least once in
14149 main.adb. The references are search in every library file in the search
14150 path.
14151
14152 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14153 switch is set)
14154
14155 The output will look like:
14156 @smallexample
14157 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14158 ^directory/^[directory]^main.adb:24:10: xyz <= body
14159 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14160 @end smallexample
14161
14162 @noindent
14163 that is to say, one of the entities xyz found in main.adb is declared at
14164 line 12 of main.ads (and its body is in main.adb), and another one is
14165 declared at line 45 of foo.ads
14166
14167 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14168 This is the same command as the previous one, instead @code{gnatfind} will
14169 display the content of the Ada source file lines.
14170
14171 The output will look like:
14172
14173 @smallexample
14174 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14175 procedure xyz;
14176 ^directory/^[directory]^main.adb:24:10: xyz <= body
14177 procedure xyz is
14178 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14179 xyz : Integer;
14180 @end smallexample
14181
14182 @noindent
14183 This can make it easier to find exactly the location your are looking
14184 for.
14185
14186 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14187 Find references to all entities containing an x that are
14188 referenced on line 123 of main.ads.
14189 The references will be searched only in main.ads and foo.adb.
14190
14191 @item gnatfind main.ads:123
14192 Find declarations and bodies for all entities that are referenced on
14193 line 123 of main.ads.
14194
14195 This is the same as @code{gnatfind "*":main.adb:123}.
14196
14197 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14198 Find the declaration for the entity referenced at column 45 in
14199 line 123 of file main.adb in directory mydir. Note that it
14200 is usual to omit the identifier name when the column is given,
14201 since the column position identifies a unique reference.
14202
14203 The column has to be the beginning of the identifier, and should not
14204 point to any character in the middle of the identifier.
14205
14206 @end table
14207
14208 @ifclear FSFEDITION
14209 @c *********************************
14210 @node The GNAT Pretty-Printer gnatpp
14211 @chapter The GNAT Pretty-Printer @command{gnatpp}
14212 @findex gnatpp
14213 @cindex Pretty-Printer
14214
14215 @menu
14216 * Switches for gnatpp::
14217 * Formatting Rules::
14218 @end menu
14219
14220 @noindent
14221 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14222 for source reformatting / pretty-printing.
14223 It takes an Ada source file as input and generates a reformatted
14224 version as output.
14225 You can specify various style directives via switches; e.g.,
14226 identifier case conventions, rules of indentation, and comment layout.
14227
14228 Note: A newly-redesigned set of formatting algorithms used by gnatpp
14229 is now available.
14230 To invoke the old formatting algorithms, use the @option{--pp-old} switch.
14231 Support for @option{--pp-old} will be removed in some future version.
14232
14233 To produce a reformatted file, @command{gnatpp} invokes the Ada
14234 compiler and generates and uses the ASIS tree for the input source;
14235 thus the input must be legal Ada code, and the tool should have all the
14236 information needed to compile the input source. To provide this information,
14237 you may specify as a tool parameter the project file the input source belongs to
14238 (or you may call @command{gnatpp}
14239 through the @command{gnat} driver (see @ref{The GNAT Driver and
14240 Project Files}). Another possibility is to specify the source search
14241 path and needed configuration files in @option{-cargs} section of @command{gnatpp}
14242 call, see the description of the @command{gnatpp} switches below.
14243
14244 @command{gnatpp} cannot process sources that contain
14245 preprocessing directives.
14246
14247 The @command{gnatpp} command has the form
14248
14249 @smallexample
14250 @c $ gnatpp @ovar{switches} @var{filename}
14251 @c Expanding @ovar macro inline (explanation in macro def comments)
14252 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
14253 @end smallexample
14254
14255 @noindent
14256 where
14257 @itemize @bullet
14258 @item
14259 @var{switches} is an optional sequence of switches defining such properties as
14260 the formatting rules, the source search path, and the destination for the
14261 output source file
14262
14263 @item
14264 @var{filename} is the name (including the extension) of the source file to
14265 reformat; wildcards or several file names on the same gnatpp command are
14266 allowed. The file name may contain path information; it does not have to
14267 follow the GNAT file naming rules
14268
14269 @item
14270 @samp{@var{gcc_switches}} is a list of switches for
14271 @command{gcc}. They will be passed on to all compiler invocations made by
14272 @command{gnatpp} to generate the ASIS trees. Here you can provide
14273 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
14274 use the @option{-gnatec} switch to set the configuration file, etc.
14275 @end itemize
14276
14277 @node Switches for gnatpp
14278 @section Switches for @command{gnatpp}
14279
14280 @noindent
14281 The following subsections describe the various switches accepted by
14282 @command{gnatpp}, organized by category.
14283
14284 @ifclear vms
14285 You specify a switch by supplying a name and generally also a value.
14286 In many cases the values for a switch with a given name are incompatible with
14287 each other
14288 (for example the switch that controls the casing of a reserved word may have
14289 exactly one value: upper case, lower case, or
14290 mixed case) and thus exactly one such switch can be in effect for an
14291 invocation of @command{gnatpp}.
14292 If more than one is supplied, the last one is used.
14293 However, some values for the same switch are mutually compatible.
14294 You may supply several such switches to @command{gnatpp}, but then
14295 each must be specified in full, with both the name and the value.
14296 Abbreviated forms (the name appearing once, followed by each value) are
14297 not permitted.
14298 @end ifclear
14299
14300 @ifset vms
14301 In many cases the set of options for a given qualifier are incompatible with
14302 each other (for example the qualifier that controls the casing of a reserved
14303 word may have exactly one option, which specifies either upper case, lower
14304 case, or mixed case), and thus exactly one such option can be in effect for
14305 an invocation of @command{gnatpp}.
14306 If more than one is supplied, the last one is used.
14307 @end ifset
14308
14309 @menu
14310 * Alignment Control::
14311 * Casing Control::
14312 * General Text Layout Control::
14313 * Other Formatting Options::
14314 * Setting the Source Search Path::
14315 * Output File Control::
14316 * Other gnatpp Switches::
14317 @end menu
14318
14319 @node Alignment Control
14320 @subsection Alignment Control
14321 @cindex Alignment control in @command{gnatpp}
14322
14323 @noindent
14324 Programs can be easier to read if certain constructs are vertically aligned.
14325 By default alignment of the following constructs is set ON:
14326 @code{:} in declarations, @code{:=} in initializations in declarations
14327 @code{:=} in assignment statements, @code{=>} in associations, and
14328 @code{at} keywords in the component clauses in record
14329 representation clauses.
14330
14331 @table @option
14332 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14333
14334 @item ^-A0^/ALIGN=OFF^
14335 Set alignment to OFF
14336
14337 @item ^-A1^/ALIGN=ON^
14338 Set alignment to ON
14339 @end table
14340
14341 @node Casing Control
14342 @subsection Casing Control
14343 @cindex Casing control in @command{gnatpp}
14344
14345 @noindent
14346 @command{gnatpp} allows you to specify the casing for reserved words,
14347 pragma names, attribute designators and identifiers.
14348 For identifiers you may define a
14349 general rule for name casing but also override this rule
14350 via a set of dictionary files.
14351
14352 Three types of casing are supported: lower case, upper case, and mixed case.
14353 ``Mixed case'' means that the first letter, and also each letter immediately
14354 following an underscore, are converted to their uppercase forms;
14355 all the other letters are converted to their lowercase forms.
14356
14357 @table @option
14358 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14359 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14360 Attribute designators are lower case
14361
14362 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14363 Attribute designators are upper case
14364
14365 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14366 Attribute designators are mixed case (this is the default)
14367
14368 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14369 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14370 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14371 lower case (this is the default)
14372
14373 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14374 Keywords are upper case
14375
14376 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14377 @item ^-nD^/NAME_CASING=AS_DECLARED^
14378 Name casing for defining occurrences are as they appear in the source file
14379 (this is the default)
14380
14381 @item ^-nU^/NAME_CASING=UPPER_CASE^
14382 Names are in upper case
14383
14384 @item ^-nL^/NAME_CASING=LOWER_CASE^
14385 Names are in lower case
14386
14387 @item ^-nM^/NAME_CASING=MIXED_CASE^
14388 Names are in mixed case
14389
14390 @cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
14391 @item ^-neD^/ENUM_CASING=AS_DECLARED^
14392 Enumeration literal casing for defining occurrences are as they appear in the
14393 source file. Overrides ^-n^/NAME_CASING^ casing setting.
14394
14395 @item ^-neU^/ENUM_CASING=UPPER_CASE^
14396 Enumeration literals are in upper case. Overrides ^-n^/NAME_CASING^ casing
14397 setting.
14398
14399 @item ^-neL^/ENUM_CASING=LOWER_CASE^
14400 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
14401 setting.
14402
14403 @item ^-neM^/ENUM_CASING=MIXED_CASE^
14404 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
14405 setting.
14406
14407 @cindex @option{^-nt@var{x}^/TYPE_CASING^} (@command{gnatpp})
14408 @item ^-neD^/TYPE_CASING=AS_DECLARED^
14409 Names introduced by type and subtype declarations are always
14410 cased as they appear in the declaration in the source file.
14411 Overrides ^-n^/NAME_CASING^ casing setting.
14412
14413 @item ^-ntU^/TYPE_CASING=UPPER_CASE^
14414 Names introduced by type and subtype declarations are always in
14415 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
14416
14417 @item ^-ntL^/TYPE_CASING=LOWER_CASE^
14418 Names introduced by type and subtype declarations are always in
14419 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
14420
14421 @item ^-ntM^/TYPE_CASING=MIXED_CASE^
14422 Names introduced by type and subtype declarations are always in
14423 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
14424
14425 @item ^-nnU^/NUMBER_CASING=UPPER_CASE^
14426 Names introduced by number declarations are always in
14427 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
14428
14429 @item ^-nnL^/NUMBER_CASING=LOWER_CASE^
14430 Names introduced by number declarations are always in
14431 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
14432
14433 @item ^-nnM^/NUMBER_CASING=MIXED_CASE^
14434 Names introduced by number declarations are always in
14435 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
14436
14437 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14438 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14439 Pragma names are lower case
14440
14441 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14442 Pragma names are upper case
14443
14444 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14445 Pragma names are mixed case (this is the default)
14446
14447 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14448 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14449 Use @var{file} as a @emph{dictionary file} that defines
14450 the casing for a set of specified names,
14451 thereby overriding the effect on these names by
14452 any explicit or implicit
14453 ^-n^/NAME_CASING^ switch.
14454 To supply more than one dictionary file,
14455 use ^several @option{-D} switches^a list of files as options^.
14456
14457 @noindent
14458 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14459 to define the casing for the Ada predefined names and
14460 the names declared in the GNAT libraries.
14461
14462 @item ^-D-^/SPECIFIC_CASING^
14463 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14464 Do not use the default dictionary file;
14465 instead, use the casing
14466 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14467 dictionary file(s)
14468 @end table
14469
14470 @noindent
14471 The structure of a dictionary file, and details on the conventions
14472 used in the default dictionary file, are defined in @ref{Name Casing}.
14473
14474 The @option{^-D-^/SPECIFIC_CASING^} and
14475 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14476 compatible.
14477
14478 @noindent
14479 This group of @command{gnatpp} switches controls the layout of comments and
14480 complex syntactic constructs. See @ref{Formatting Comments} for details
14481 on their effect.
14482
14483 @table @option
14484 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14485 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14486 All comments remain unchanged.
14487
14488 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14489 GNAT-style comment line indentation.
14490 This is the default.
14491
14492 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14493 GNAT-style comment beginning.
14494
14495 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14496 Fill comment blocks.
14497
14498 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
14499 Keep unchanged special form comments.
14500 This is the default.
14501
14502 @item --comments-only
14503 @cindex @option{--comments-only} @command{gnatpp}
14504 Format just the comments.
14505
14506 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
14507 @item ^--no-separate-is^/NO_SEPARATE_IS^
14508 Do not place the keyword @code{is} on a separate line in a subprogram body in
14509 case if the spec occupies more than one line.
14510
14511 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
14512 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
14513 Place the keyword @code{loop} in FOR and WHILE loop statements and the
14514 keyword @code{then} in IF statements on a separate line.
14515
14516 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
14517 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
14518 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
14519 keyword @code{then} in IF statements on a separate line. This option is
14520 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
14521
14522 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
14523 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
14524 Start each USE clause in a context clause from a separate line.
14525
14526 @cindex @option{^--insert-blank-lines^/INSERT_BLANK_LINES^} (@command{gnatpp})
14527 @item ^--insert-blank-lines^/INSERT_BLANK_LINES^
14528 Insert blank lines where appropriate (between bodies and other large
14529 constructs).
14530
14531 @cindex @option{^--preserve-blank-lines^/PRESERVE_BLANK_LINES^} (@command{gnatpp})
14532 @item ^--preserve-blank-lines^/PRESERVE_BLANK_LINES^
14533 Preserve blank lines in the input. By default, gnatpp will squeeze
14534 multiple blank lines down to one.
14535
14536 @end table
14537
14538 @ifclear vms
14539 @noindent
14540 The @option{-c} switches are compatible with one another, except that
14541 the @option{-c0} switch disables all other comment formatting
14542 switches.
14543 @end ifclear
14544
14545 @ifset vms
14546 @noindent
14547 For the @option{/COMMENTS_LAYOUT} qualifier,
14548 The @option{GNAT_BEGINNING}, @option{REFORMAT}, and @option{DEFAULT}
14549 options are compatible with one another.
14550 @end ifset
14551
14552 @node General Text Layout Control
14553 @subsection General Text Layout Control
14554
14555 @noindent
14556 These switches allow control over line length and indentation.
14557
14558 @table @option
14559 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
14560 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14561 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
14562
14563 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
14564 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14565 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
14566
14567 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
14568 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14569 Indentation level for continuation lines (relative to the line being
14570 continued), @var{nnn} from 1@dots{}9.
14571 The default
14572 value is one less than the (normal) indentation level, unless the
14573 indentation is set to 1 (in which case the default value for continuation
14574 line indentation is also 1)
14575 @end table
14576
14577 @node Other Formatting Options
14578 @subsection Other Formatting Options
14579
14580 @noindent
14581 These switches control other formatting not listed above.
14582
14583 @table @option
14584 @item --decimal-grouping=@var{n}
14585 @cindex @option{--decimal-grouping} @command{gnatpp}
14586 Put underscores in decimal literals (numeric literals without a base)
14587 every @var{n} characters. If a literal already has one or more
14588 underscores, it is not modified. For example, with
14589 @code{--decimal-grouping=3}, @code{1000000} will be changed to
14590 @code{1_000_000}.
14591
14592 @item --based-grouping=@var{n}
14593 @cindex @option{--based-grouping} @command{gnatpp}
14594 Same as @code{--decimal-grouping}, but for based literals. For
14595 example, with @code{--based-grouping=4}, @code{16#0001FFFE#} will be
14596 changed to @code{16#0001_FFFE#}.
14597
14598 @item ^--RM-style-spacing^/RM_STYLE_SPACING^
14599 @cindex @option{^--RM-style-spacing^/RM_STYLE_SPACING^} (@command{gnatpp})
14600 Do not insert an extra blank before various occurrences of
14601 `(' and `:'. This also turns off alignment.
14602
14603 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14604 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14605 Insert a Form Feed character after a pragma Page.
14606
14607 @item ^--call_threshold=@var{nnn}^/MAX_ACT=@var{nnn}^
14608 @cindex @option{^--call_threshold^/MAX_ACT^} (@command{gnatpp})
14609 If the number of parameter associations is greater than @var{nnn} and if at
14610 least one association uses named notation, start each association from
14611 a new line. If @var{nnn} is 0, no check for the number of associations
14612 is made; this is the default.
14613
14614 @item ^--par_threshold=@var{nnn}^/MAX_PAR=@var{nnn}^
14615 @cindex @option{^--par_threshold^/MAX_PAR^} (@command{gnatpp})
14616 If the number of parameter specifications is greater than @var{nnn}
14617 (or equal to @var{nnn} in case of a function), start each specification from
14618 a new line. This feature is disabled by default.
14619 @end table
14620
14621 @node Setting the Source Search Path
14622 @subsection Setting the Source Search Path
14623
14624 @noindent
14625 To define the search path for the input source file, @command{gnatpp}
14626 uses the same switches as the GNAT compiler, with the same effects:
14627
14628 @table @option
14629 @item ^-I^/SEARCH=^@var{dir}
14630 @cindex @option{^-I^/SEARCH^} (@command{gnatpp})
14631
14632 @item ^-I-^/NOCURRENT_DIRECTORY^
14633 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatpp})
14634
14635 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14636 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatpp})
14637
14638 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14639 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@command{gnatpp})
14640
14641 @end table
14642
14643 @node Output File Control
14644 @subsection Output File Control
14645
14646 @noindent
14647 By default the output is sent to a file whose name is obtained by appending
14648 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file.
14649 If the file with this name already exists, it is overwritten.
14650 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14651 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14652 as output file.
14653 The output may be redirected by the following switches:
14654
14655 @table @option
14656 @item ^--output-dir=@var{dir}^/OUTPUT_DIR=@var{dir}^
14657 @cindex @option{^--output-dir^/OUTPUT_DIR^} (@command{gnatpp})
14658 Generate output file in directory @file{dir} with the same name as the input
14659 file. If @file{dir} is the same as the directory containing the input file,
14660 the input file is not processed; use @option{^-rnb^/REPLACE_NO_BACKUP^}
14661 if you want to update the input file in place.
14662
14663 @item ^-pipe^/STANDARD_OUTPUT^
14664 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@command{gnatpp})
14665 Send the output to @code{Standard_Output}
14666
14667 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14668 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14669 Write the output into @var{output_file}.
14670 If @var{output_file} already exists, @command{gnatpp} terminates without
14671 reading or processing the input file.
14672
14673 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14674 @cindex @option{^-of^/FORCED_OUTPUT^} (@command{gnatpp})
14675 Write the output into @var{output_file}, overwriting the existing file
14676 (if one is present).
14677
14678 @item ^-r^/REPLACE^
14679 @cindex @option{^-r^/REPLACE^} (@command{gnatpp})
14680 Replace the input source file with the reformatted output, and copy the
14681 original input source into the file whose name is obtained by appending the
14682 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14683 If a file with this name already exists, @command{gnatpp} terminates without
14684 reading or processing the input file.
14685
14686 @item ^-rf^/OVERRIDING_REPLACE^
14687 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14688 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14689 already exists, it is overwritten.
14690
14691 @item ^-rnb^/REPLACE_NO_BACKUP^
14692 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@command{gnatpp})
14693 Replace the input source file with the reformatted output without
14694 creating any backup copy of the input source.
14695
14696 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
14697 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
14698 Specifies the line-ending style of the reformatted output file. The @var{xxx}
14699 ^string specified with the switch^option^ may be:
14700 @itemize @bullet
14701 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
14702 @item ``@option{^crlf^CRLF^}''
14703 the same as @option{^dos^DOS^}
14704 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
14705 @item ``@option{^lf^LF^}''
14706 the same as @option{^unix^UNIX^}
14707 @end itemize
14708
14709 @item ^-W^/RESULT_ENCODING=^@var{e}
14710 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
14711 Specify the wide character encoding method for the input and output files.
14712 @var{e} is one of the following:
14713
14714 @itemize @bullet
14715
14716 @item ^h^HEX^
14717 Hex encoding
14718
14719 @item ^u^UPPER^
14720 Upper half encoding
14721
14722 @item ^s^SHIFT_JIS^
14723 Shift/JIS encoding
14724
14725 @item ^e^EUC^
14726 EUC encoding
14727
14728 @item ^8^UTF8^
14729 UTF-8 encoding
14730
14731 @item ^b^BRACKETS^
14732 Brackets encoding (default value)
14733 @end itemize
14734
14735 @end table
14736
14737 @noindent
14738 Options @option{^-o^/OUTPUT^} and
14739 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14740 contains only one file to reformat.
14741 Option
14742 @option{^--eol^/END_OF_LINE^}
14743 and
14744 @option{^-W^/RESULT_ENCODING^}
14745 cannot be used together
14746 with @option{^-pipe^/STANDARD_OUTPUT^} option.
14747
14748 @node Other gnatpp Switches
14749 @subsection Other @code{gnatpp} Switches
14750
14751 @noindent
14752 The additional @command{gnatpp} switches are defined in this subsection.
14753
14754 @table @option
14755 @item --version
14756 @cindex @option{--version} @command{gnatpp}
14757 Display copyright and version, then exit disregarding all other options.
14758
14759 @item --help
14760 @cindex @option{--help} @command{gnatpp}
14761 Display usage, then exit disregarding all other options.
14762
14763 @item -P @var{file}
14764 @cindex @option{-P} @command{gnatpp}
14765 Indicates the name of the project file that describes the set of sources
14766 to be processed. The exact set of argument sources depends on other options
14767 specified; see below.
14768
14769 @item -U
14770 @cindex @option{-U} @command{gnatpp}
14771 If a project file is specified and no argument source is explicitly
14772 specified (either directly or by means of @option{-files} option), process
14773 all the units of the closure of the argument project. Otherwise this option
14774 has no effect.
14775
14776 @item -U @var{main_unit}
14777 If a project file is specified and no argument source is explicitly
14778 specified (either directly or by means of @option{-files} option), process
14779 the closure of units rooted at @var{main_unit}. Otherwise this option
14780 has no effect.
14781
14782 @item -X@var{name}=@var{value}
14783 @cindex @option{-X} @command{gnatpp}
14784 Indicates that external variable @var{name} in the argument project
14785 has the value @var{value}. Has no effect if no project is specified as
14786 tool argument.
14787
14788 @item --incremental
14789 @cindex @option{--incremental} @command{gnatpp}
14790 Incremental processing on a per-file basis. Source files are only
14791 processed if they have been modified, or if files they depend on have
14792 been modified. This is similar to the way gnatmake/gprbuild only
14793 compiles files that need to be recompiled.
14794
14795 @item --pp-off=@var{xxx}
14796 @cindex @option{--pp-off} @command{gnatpp}
14797 Use @code{--xxx} as the command to turn off pretty printing, instead
14798 of the default @code{--!pp off}.
14799
14800 @item --pp-on=@var{xxx}
14801 @cindex @option{--pp-on} @command{gnatpp}
14802 Use @code{--xxx} as the command to turn pretty printing back on, instead
14803 of the default @code{--!pp on}.
14804
14805 @item --pp-old
14806 @cindex @option{--pp-old} @command{gnatpp}
14807 Use the old formatting algorithms.
14808
14809 @item ^-files @var{filename}^/FILES=@var{filename}^
14810 @cindex @option{^-files^/FILES^} (@code{gnatpp})
14811 Take the argument source files from the specified file. This file should be an
14812 ordinary text file containing file names separated by spaces or
14813 line breaks. You can use this switch more than once in the same call to
14814 @command{gnatpp}. You also can combine this switch with an explicit list of
14815 files.
14816
14817 @item ^-j^/PROCESSES=^@var{n}
14818 @cindex @option{^-j^/PROCESSES^} (@command{gnatpp})
14819 Without @option{--incremental}, use @var{n} processes to carry out the
14820 tree creations (internal representations of the argument sources). On
14821 a multiprocessor machine this speeds up processing of big sets of
14822 argument sources. If @var{n} is 0, then the maximum number of parallel
14823 tree creations is the number of core processors on the platform. This
14824 option cannot be used together with @option{^-r^/REPLACE^},
14825 @option{^-rf^/OVERRIDING_REPLACE^} or
14826 @option{^-rnb^/REPLACE_NO_BACKUP^} option.
14827
14828 With @option{--incremental}, use @var{n} @command{gnatpp} processes to
14829 perform pretty-printing in parallel. @var{n} = 0 means the same as
14830 above. In this case, @option{^-r^/REPLACE^},
14831 @option{^-rf^/OVERRIDING_REPLACE^} or
14832 @option{^-rnb^/REPLACE_NO_BACKUP^} options are allowed.
14833
14834 @cindex @option{^-t^/TIME^} (@command{gnatpp})
14835 @item ^-t^/TIME^
14836 Print out execution time.
14837
14838 @item ^-v^/VERBOSE^
14839 @cindex @option{^-v^/VERBOSE^} (@command{gnatpp})
14840 Verbose mode
14841
14842 @item ^-q^/QUIET^
14843 @cindex @option{^-q^/QUIET^} (@command{gnatpp})
14844 Quiet mode
14845 @end table
14846
14847 @noindent
14848 If a project file is specified and no argument source is explicitly
14849 specified (either directly or by means of @option{-files} option), and no
14850 @option{-U} is specified, then the set of processed sources is
14851 all the immediate units of the argument project.
14852
14853
14854 @node Formatting Rules
14855 @section Formatting Rules
14856
14857 @noindent
14858 The following subsections show how @command{gnatpp} treats white space,
14859 comments, program layout, and name casing.
14860 They provide detailed descriptions of the switches shown above.
14861
14862 @menu
14863 * Disabling Pretty Printing::
14864 * White Space and Empty Lines::
14865 * Formatting Comments::
14866 * Name Casing::
14867 @end menu
14868
14869 @node Disabling Pretty Printing
14870 @subsection Disabling Pretty Printing
14871
14872 @noindent
14873 Pretty printing is highly heuristic in nature, and sometimes doesn't
14874 do exactly what you want. If you wish to format a certain region of
14875 code by hand, you can turn off pretty printing in that region by
14876 surrounding it with special comments that start with @code{--!pp off}
14877 and @code{--!pp on}. The text in that region will then be reproduced
14878 verbatim in the output with no formatting.
14879
14880 To disable pretty printing for the whole file, put @code{--!pp off} at
14881 the top, with no following @code{--!pp on}.
14882
14883 The comments must appear on a line by themselves, with nothing
14884 preceding except spaces. The initial text of the comment must be
14885 exactly @code{--!pp off} or @code{--!pp on} (case sensitive), but may
14886 be followed by arbitrary additional text. For example:
14887
14888 @smallexample @c ada
14889 @cartouche
14890 package Interrupts is
14891 --!pp off -- turn off pretty printing so "Interrupt_Kind" lines up
14892 type Interrupt_Kind is
14893 (Asynchronous_Interrupt_Kind,
14894 Synchronous_Interrupt_Kind,
14895 Green_Interrupt_Kind);
14896 --!pp on -- reenable pretty printing
14897
14898 ...
14899 @end cartouche
14900 @end smallexample
14901
14902 You can specify different comment strings using the @code{--pp-off}
14903 and @code{--pp-on} switches. For example, if you say @code{gnatpp
14904 --pp-off=' pp-' *.ad?} then gnatpp will recognize comments of the form
14905 @code{-- pp-} instead of @code{--!pp off} for disabling pretty
14906 printing. Note that the leading @code{--} of the comment is not
14907 included in the argument to these switches.
14908
14909 @node White Space and Empty Lines
14910 @subsection White Space and Empty Lines
14911
14912 @noindent
14913 @command{gnatpp} does not have an option to control space characters.
14914 It will add or remove spaces according to the style illustrated by the
14915 examples in the @cite{Ada Reference Manual}.
14916 The output file will contain no lines with trailing white space.
14917
14918 By default, a sequence of one or more blank lines in the input is
14919 converted to a single blank line in the output; multiple blank lines
14920 are squeezed down to one.
14921 The @option{^--preserve-blank-lines^/PRESERVE_BLANK_LINES^} option
14922 turns off the squeezing; each blank line in the input is copied
14923 to the output.
14924 The @option{^--insert-blank-lines^/INSERT_BLANK_LINES^} option
14925 causes additional blank lines to be inserted if not already
14926 present in the input (e.g. between bodies).
14927
14928 @node Formatting Comments
14929 @subsection Formatting Comments
14930
14931 @noindent
14932 Comments in Ada code are of two kinds:
14933 @itemize @bullet
14934 @item
14935 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14936 white space) on a line
14937
14938 @item
14939 an @emph{end-of-line comment}, which follows some other Ada code on
14940 the same line.
14941 @end itemize
14942
14943 @noindent
14944 A whole-line comment is indented according to the surrounding code,
14945 with some exceptions.
14946 Comments that start in column 1 are kept there.
14947 If possible, comments are not moved so far to the right that the maximum
14948 line length is exceeded.
14949 The @option{^-c0^/COMMENTS_LAYOUT=UNTOUCHED^} option
14950 turns off comment formatting.
14951 Special-form comments such as SPARK-style @code{--#...} are left alone.
14952
14953 For an end-of-line comment, @command{gnatpp} tries to leave the same
14954 number of spaces between the end of the preceding Ada code and the
14955 beginning of the comment as appear in the original source.
14956
14957 @noindent
14958 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
14959 (GNAT style comment beginning) has the following
14960 effect:
14961
14962 @itemize @bullet
14963 @item
14964 For each whole-line comment that does not end with two hyphens,
14965 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
14966 to ensure that there are at least two spaces between these hyphens and the
14967 first non-blank character of the comment.
14968 @end itemize
14969
14970 @noindent
14971 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that
14972 whole-line comments that form a paragraph will be filled in typical
14973 word processor style (that is, moving words between lines to make the
14974 lines other than the last similar in length ).
14975
14976 @noindent
14977 The @option{--comments-only} switch specifies that only the comments
14978 are formatted; the rest of the program text is left alone. The
14979 comments are formatted according to the -c3 and -c4 switches; other
14980 formatting switches are ignored. For example, @option{--comments-only
14981 -c4} means to fill comment paragraphs, and do nothing else. Likewise,
14982 @option{--comments-only -c3} ensures comments start with at least two
14983 spaces after @code{--}, and @option{--comments-only -c3 -c4} does
14984 both. If @option{--comments-only} is given without @option{-c3} or
14985 @option{-c4}, then gnatpp doesn't format anything.
14986
14987 @node Name Casing
14988 @subsection Name Casing
14989
14990 @noindent
14991 @command{gnatpp} always converts the usage occurrence of a (simple) name to
14992 the same casing as the corresponding defining identifier.
14993
14994 You control the casing for defining occurrences via the
14995 @option{^-n^/NAME_CASING^} switch.
14996 @ifclear vms
14997 With @option{-nD} (``as declared'', which is the default),
14998 @end ifclear
14999 @ifset vms
15000 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
15001 @end ifset
15002 defining occurrences appear exactly as in the source file
15003 where they are declared.
15004 The other ^values for this switch^options for this qualifier^ ---
15005 @option{^-nU^UPPER_CASE^},
15006 @option{^-nL^LOWER_CASE^},
15007 @option{^-nM^MIXED_CASE^} ---
15008 result in
15009 ^upper, lower, or mixed case, respectively^the corresponding casing^.
15010 If @command{gnatpp} changes the casing of a defining
15011 occurrence, it analogously changes the casing of all the
15012 usage occurrences of this name.
15013
15014 If the defining occurrence of a name is not in the source compilation unit
15015 currently being processed by @command{gnatpp}, the casing of each reference to
15016 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
15017 switch (subject to the dictionary file mechanism described below).
15018 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
15019 had affected the
15020 casing for the defining occurrence of the name.
15021
15022 The options
15023 @option{^-a@var{x}^/ATTRIBUTE^},
15024 @option{^-k@var{x}^/KEYWORD_CASING^},
15025 @option{^-ne@var{x}^/ENUM_CASING^},
15026 @option{^-nt@var{x}^/TYPE_CASING^},
15027 @option{^-nn@var{x}^/NUMBER_CASING^}, and
15028 @option{^-p@var{x}^/PRAGMA_CASING^}
15029 allow finer-grained control over casing for
15030 attributes, keywords, enumeration literals,
15031 types, named numbers and pragmas, respectively.
15032 @option{^-nt@var{x}^/TYPE_CASING^} covers subtypes and
15033 task and protected bodies as well.
15034
15035 Some names may need to be spelled with casing conventions that are not
15036 covered by the upper-, lower-, and mixed-case transformations.
15037 You can arrange correct casing by placing such names in a
15038 @emph{dictionary file},
15039 and then supplying a @option{^-D^/DICTIONARY^} switch.
15040 The casing of names from dictionary files overrides
15041 any @option{^-n^/NAME_CASING^} switch.
15042
15043 To handle the casing of Ada predefined names and the names from GNAT libraries,
15044 @command{gnatpp} assumes a default dictionary file.
15045 The name of each predefined entity is spelled with the same casing as is used
15046 for the entity in the @cite{Ada Reference Manual} (usually mixed case).
15047 The name of each entity in the GNAT libraries is spelled with the same casing
15048 as is used in the declaration of that entity.
15049
15050 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of
15051 the default dictionary file. Instead, the casing for predefined and
15052 GNAT-defined names will be established by the
15053 @option{^-n^/NAME_CASING^} switch or explicit dictionary files. For
15054 example, by default the names @code{Ada.Text_IO} and
15055 @code{GNAT.OS_Lib} will appear as just shown, even in the presence of
15056 a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch. To ensure that even
15057 such names are rendered in uppercase, additionally supply the
15058 @w{@option{^-D-^/SPECIFIC_CASING^}} switch (or else place these names
15059 in upper case in a dictionary file).
15060
15061 A dictionary file is a plain text file; each line in this file can be
15062 either a blank line (containing only space characters), an Ada comment
15063 line, or the specification of exactly one @emph{casing schema}.
15064
15065 A casing schema is a string that has the following syntax:
15066
15067 @smallexample
15068 @cartouche
15069 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
15070
15071 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15072 @end cartouche
15073 @end smallexample
15074
15075 @noindent
15076 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15077 @var{identifier} lexical element and the @var{letter_or_digit} category.)
15078
15079 The casing schema string can be followed by white space and/or an Ada-style
15080 comment; any amount of white space is allowed before the string.
15081
15082 If a dictionary file is passed as
15083 @ifclear vms
15084 the value of a @option{-D@var{file}} switch
15085 @end ifclear
15086 @ifset vms
15087 an option to the @option{/DICTIONARY} qualifier
15088 @end ifset
15089 then for every
15090 simple name and every identifier, @command{gnatpp} checks if the dictionary
15091 defines the casing for the name or for some of its parts (the term ``subword''
15092 is used below to denote the part of a name which is delimited by ``_'' or by
15093 the beginning or end of the word and which does not contain any ``_'' inside):
15094
15095 @itemize @bullet
15096 @item
15097 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15098 the casing defined by the dictionary; no subwords are checked for this word
15099
15100 @item
15101 for every subword @command{gnatpp} checks if the dictionary contains the
15102 corresponding string of the form @code{*@var{simple_identifier}*},
15103 and if it does, the casing of this @var{simple_identifier} is used
15104 for this subword
15105
15106 @item
15107 if the whole name does not contain any ``_'' inside, and if for this name
15108 the dictionary contains two entries - one of the form @var{identifier},
15109 and another - of the form *@var{simple_identifier}*, then the first one
15110 is applied to define the casing of this name
15111
15112 @item
15113 if more than one dictionary file is passed as @command{gnatpp} switches, each
15114 dictionary adds new casing exceptions and overrides all the existing casing
15115 exceptions set by the previous dictionaries
15116
15117 @item
15118 when @command{gnatpp} checks if the word or subword is in the dictionary,
15119 this check is not case sensitive
15120 @end itemize
15121
15122 @noindent
15123 For example, suppose we have the following source to reformat:
15124
15125 @smallexample @c ada
15126 @cartouche
15127 procedure test is
15128 name1 : integer := 1;
15129 name4_name3_name2 : integer := 2;
15130 name2_name3_name4 : Boolean;
15131 name1_var : Float;
15132 begin
15133 name2_name3_name4 := name4_name3_name2 > name1;
15134 end;
15135 @end cartouche
15136 @end smallexample
15137
15138 @noindent
15139 And suppose we have two dictionaries:
15140
15141 @smallexample
15142 @cartouche
15143 @i{dict1:}
15144 NAME1
15145 *NaMe3*
15146 *Name1*
15147 @end cartouche
15148
15149 @cartouche
15150 @i{dict2:}
15151 *NAME3*
15152 @end cartouche
15153 @end smallexample
15154
15155 @noindent
15156 If @command{gnatpp} is called with the following switches:
15157
15158 @smallexample
15159 @ifclear vms
15160 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15161 @end ifclear
15162 @ifset vms
15163 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15164 @end ifset
15165 @end smallexample
15166
15167 @noindent
15168 then we will get the following name casing in the @command{gnatpp} output:
15169
15170 @smallexample @c ada
15171 @cartouche
15172 procedure Test is
15173 NAME1 : Integer := 1;
15174 Name4_NAME3_Name2 : Integer := 2;
15175 Name2_NAME3_Name4 : Boolean;
15176 Name1_Var : Float;
15177 begin
15178 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
15179 end Test;
15180 @end cartouche
15181 @end smallexample
15182 @end ifclear
15183
15184 @ifclear FSFEDITION
15185 @ifclear vms
15186 @c *********************************
15187 @node The Ada-to-XML converter gnat2xml
15188 @chapter The Ada-to-XML converter @command{gnat2xml}
15189 @findex gnat2xml
15190 @cindex XML generation
15191
15192 @noindent
15193 The @command{gnat2xml} tool is an ASIS-based utility that converts
15194 Ada source code into XML.
15195
15196 @menu
15197 * Switches for gnat2xml::
15198 * Other Programs::
15199 * Structure of the XML::
15200 @end menu
15201
15202 @node Switches for gnat2xml
15203 @section Switches for @command{gnat2xml}
15204
15205 @noindent
15206 @command{gnat2xml} takes Ada source code as input, and produces XML
15207 that conforms to the schema.
15208
15209 Usage:
15210
15211 @smallexample
15212 gnat2xml [options] filenames [-files filename] [-cargs gcc_switches]
15213 @end smallexample
15214
15215 @noindent
15216 options:
15217 @smallexample
15218 -h
15219 --help -- generate usage information and quit, ignoring all other options
15220 --version -- print version and quit, ignoring all other options
15221
15222 -P @file{file} -- indicates the name of the project file that describes
15223 the set of sources to be processed. The exact set of argument
15224 sources depends on other options specified, see below.
15225
15226 -U -- if a project file is specified and no argument source is explicitly
15227 specified, process all the units of the closure of the argument project.
15228 Otherwise this option has no effect.
15229
15230 -U @var{main_unit} -- if a project file is specified and no argument source
15231 is explicitly specified (either directly or by means of @option{-files}
15232 option), process the closure of units rooted at @var{main_unit}.
15233 Otherwise this option has no effect.
15234
15235 -X@var{name}=@var{value} -- indicates that external variable @var{name} in
15236 the argument project has the value @var{value}. Has no effect if no
15237 project is specified as tool argument.
15238
15239 --incremental -- incremental processing on a per-file basis. Source files are
15240 only processed if they have been modified, or if files they depend
15241 on have been modified. This is similar to the way gnatmake/gprbuild
15242 only compiles files that need to be recompiled.
15243
15244 -j@var{n} -- In @option{--incremental} mode, use @var{n} @command{gnat2xml}
15245 processes to perform XML generation in parallel. If @var{n} is 0, then
15246 the maximum number of parallel tree creations is the number of core
15247 processors on the platform.
15248
15249 --output-dir=@var{dir} -- generate one .xml file for each Ada source file, in
15250 directory @file{dir}. (Default is to generate the XML to standard
15251 output.)
15252
15253 -I <include-dir>
15254 directories to search for dependencies
15255 You can also set the ADA_INCLUDE_PATH environment variable for this.
15256
15257 --compact -- debugging version, with interspersed source, and a more
15258 compact representation of "sloc". This version does not conform
15259 to any schema.
15260
15261 -files=filename - the name of a text file containing a list
15262 of Ada source files to process
15263
15264 -q -- quiet
15265 -v -- verbose
15266
15267 -cargs ... -- options to pass to gcc
15268 @end smallexample
15269
15270 @noindent
15271 If a project file is specified and no argument source is explicitly
15272 specified, and no @option{-U} is specified, then the set of processed
15273 sources is all the immediate units of the argument project.
15274
15275 Example:
15276
15277 @smallexample
15278 gnat2xml -v -output-dir=xml-files *.ad[sb]
15279 @end smallexample
15280
15281 @noindent
15282 The above will create *.xml files in the @file{xml-files} subdirectory.
15283 For example, if there is an Ada package Mumble.Dumble, whose spec and
15284 body source code lives in mumble-dumble.ads and mumble-dumble.adb,
15285 the above will produce xml-files/mumble-dumble.ads.xml and
15286 xml-files/mumble-dumble.adb.xml.
15287
15288 @node Other Programs
15289 @section Other Programs
15290
15291 @noindent
15292 The distribution includes two other programs that are related to
15293 @command{gnat2xml}:
15294
15295 @command{gnat2xsd} is the schema generator, which generates the schema
15296 to standard output, based on the structure of Ada as encoded by
15297 ASIS. You don't need to run @command{gnat2xsd} in order to use
15298 @command{gnat2xml}. To generate the schema, type:
15299
15300 @smallexample
15301 gnat2xsd > ada-schema.xsd
15302 @end smallexample
15303
15304 @noindent
15305 @command{gnat2xml} generates XML files that will validate against
15306 @file{ada-schema.xsd}.
15307
15308 @command{xml2gnat} is a back-translator that translates the XML back
15309 into Ada source code. The Ada generated by @command{xml2gnat} has
15310 identical semantics to the original Ada code passed to
15311 @command{gnat2xml}. It is not textually identical, however --- for
15312 example, no attempt is made to preserve the original indentation.
15313
15314 @node Structure of the XML
15315 @section Structure of the XML
15316
15317 @noindent
15318 The primary documentation for the structure of the XML generated by
15319 @command{gnat2xml} is the schema (see @command{gnat2xsd} above). The
15320 following documentation gives additional details needed to understand
15321 the schema and therefore the XML.
15322
15323 The elements listed under Defining Occurrences, Usage Occurrences, and
15324 Other Elements represent the syntactic structure of the Ada program.
15325 Element names are given in lower case, with the corresponding element
15326 type Capitalized_Like_This. The element and element type names are
15327 derived directly from the ASIS enumeration type Flat_Element_Kinds,
15328 declared in Asis.Extensions.Flat_Kinds, with the leading ``An_'' or ``A_''
15329 removed. For example, the ASIS enumeration literal
15330 An_Assignment_Statement corresponds to the XML element
15331 assignment_statement of XML type Assignment_Statement.
15332
15333 To understand the details of the schema and the corresponding XML, it is
15334 necessary to understand the ASIS standard, as well as the GNAT-specific
15335 extension to ASIS.
15336
15337 A defining occurrence is an identifier (or character literal or operator
15338 symbol) declared by a declaration. A usage occurrence is an identifier
15339 (or ...) that references such a declared entity. For example, in:
15340
15341 @smallexample
15342 type T is range 1..10;
15343 X, Y : constant T := 1;
15344 @end smallexample
15345
15346 @noindent
15347 The first ``T'' is the defining occurrence of a type. The ``X'' is the
15348 defining occurrence of a constant, as is the ``Y'', and the second ``T'' is
15349 a usage occurrence referring to the defining occurrence of T.
15350
15351 Each element has a 'sloc' (source location), and subelements for each
15352 syntactic subtree, reflecting the Ada grammar as implemented by ASIS.
15353 The types of subelements are as defined in the ASIS standard. For
15354 example, for the right-hand side of an assignment_statement we have
15355 the following comment in asis-statements.ads:
15356
15357 @smallexample
15358 ------------------------------------------------------------------------------
15359 -- 18.3 function Assignment_Expression
15360 ------------------------------------------------------------------------------
15361
15362 function Assignment_Expression
15363 (Statement : Asis.Statement)
15364 return Asis.Expression;
15365
15366 ------------------------------------------------------------------------------
15367 ...
15368 -- Returns the expression from the right hand side of the assignment.
15369 ...
15370 -- Returns Element_Kinds:
15371 -- An_Expression
15372 @end smallexample
15373
15374 @noindent
15375 The corresponding sub-element of type Assignment_Statement is:
15376
15377 @smallexample
15378 <xsd:element name="assignment_expression_q" type="Expression_Class"/>
15379 @end smallexample
15380
15381 @noindent
15382 where Expression_Class is defined by an xsd:choice of all the
15383 various kinds of expression.
15384
15385 The 'sloc' of each element indicates the starting and ending line and
15386 column numbers. Column numbers are character counts; that is, a tab
15387 counts as 1, not as however many spaces it might expand to.
15388
15389 Subelements of type Element have names ending in ``_q'' (for ASIS
15390 ``Query''), and those of type Element_List end in ``_ql'' (``Query returning
15391 List'').
15392
15393 Some subelements are ``Boolean''. For example, Private_Type_Definition
15394 has has_abstract_q and has_limited_q, to indicate whether those
15395 keywords are present, as in @code{type T is abstract limited
15396 private;}. False is represented by a Nil_Element. True is represented
15397 by an element type specific to that query (for example, Abstract and
15398 Limited).
15399
15400 The root of the tree is a Compilation_Unit, with attributes:
15401
15402 @itemize @bullet
15403 @item
15404 unit_kind, unit_class, and unit_origin. These are strings that match the
15405 enumeration literals of types Unit_Kinds, Unit_Classes, and Unit_Origins
15406 in package Asis.
15407
15408 @item
15409 unit_full_name is the full expanded name of the unit, starting from a
15410 root library unit. So for @code{package P.Q.R is ...},
15411 @code{unit_full_name="P.Q.R"}. Same for @code{separate (P.Q) package R is ...}.
15412
15413 @item
15414 def_name is the same as unit_full_name for library units; for subunits,
15415 it is just the simple name.
15416
15417 @item
15418 source_file is the name of the Ada source file. For example, for
15419 the spec of @code{P.Q.R}, @code{source_file="p-q-r.ads"}. This allows one to
15420 interpret the source locations --- the ``sloc'' of all elements
15421 within this Compilation_Unit refers to line and column numbers
15422 within the named file.
15423 @end itemize
15424
15425 @noindent
15426 Defining occurrences have these attributes:
15427
15428 @itemize @bullet
15429 @item
15430 def_name is the simple name of the declared entity, as written in the Ada
15431 source code.
15432
15433 @item
15434 def is a unique URI of the form:
15435
15436 ada://kind/fully/qualified/name
15437
15438 where:
15439
15440 kind indicates the kind of Ada entity being declared (see below), and
15441
15442 fully/qualified/name, is the fully qualified name of the Ada
15443 entity, with each of ``fully'', ``qualified'', and ``name'' being
15444 mangled for uniqueness. We do not document the mangling
15445 algorithm, which is subject to change; we just guarantee that the
15446 names are unique in the face of overloading.
15447
15448 @item
15449 type is the type of the declared object, or @code{null} for
15450 declarations of things other than objects.
15451 @end itemize
15452
15453 @noindent
15454 Usage occurrences have these attributes:
15455
15456 @itemize @bullet
15457 @item
15458 ref_name is the same as the def_name of the corresponding defining
15459 occurrence. This attribute is not of much use, because of
15460 overloading; use ref for lookups, instead.
15461
15462 @item
15463 ref is the same as the def of the corresponding defining
15464 occurrence.
15465 @end itemize
15466
15467 @noindent
15468 In summary, @code{def_name} and @code{ref_name} are as in the source
15469 code of the declaration, possibly overloaded, whereas @code{def} and
15470 @code{ref} are unique-ified.
15471
15472 Literal elements have this attribute:
15473
15474 @itemize @bullet
15475 @item
15476 lit_val is the value of the literal as written in the source text,
15477 appropriately escaped (e.g. @code{"} ---> @code{&quot;}). This applies
15478 only to numeric and string literals. Enumeration literals in Ada are
15479 not really "literals" in the usual sense; they are usage occurrences,
15480 and have ref_name and ref as described above. Note also that string
15481 literals used as operator symbols are treated as defining or usage
15482 occurrences, not as literals.
15483 @end itemize
15484
15485 @noindent
15486 Elements that can syntactically represent names and expressions (which
15487 includes usage occurrences, plus function calls and so forth) have this
15488 attribute:
15489
15490 @itemize @bullet
15491 @item
15492 type. If the element represents an expression or the name of an object,
15493 'type' is the 'def' for the defining occurrence of the type of that
15494 expression or name. Names of other kinds of entities, such as package
15495 names and type names, do not have a type in Ada; these have type="null"
15496 in the XML.
15497 @end itemize
15498
15499 @noindent
15500 Pragma elements have this attribute:
15501
15502 @itemize @bullet
15503 @item
15504 pragma_name is the name of the pragma. For language-defined pragmas, the
15505 pragma name is redundant with the element kind (for example, an
15506 assert_pragma element necessarily has pragma_name="Assert"). However, all
15507 implementation-defined pragmas are lumped together in ASIS as a single
15508 element kind (for example, the GNAT-specific pragma Unreferenced is
15509 represented by an implementation_defined_pragma element with
15510 pragma_name="Unreferenced").
15511 @end itemize
15512
15513 @noindent
15514 Defining occurrences of formal parameters and generic formal objects have this
15515 attribute:
15516
15517 @itemize @bullet
15518 @item
15519 mode indicates that the parameter is of mode 'in', 'in out', or 'out'.
15520 @end itemize
15521
15522 @noindent
15523 All elements other than Not_An_Element have this attribute:
15524
15525 @itemize @bullet
15526 @item
15527 checks is a comma-separated list of run-time checks that are needed
15528 for that element. The possible checks are: do_accessibility_check,
15529 do_discriminant_check,do_division_check,do_length_check,
15530 do_overflow_check,do_range_check,do_storage_check,do_tag_check.
15531 @end itemize
15532
15533 @noindent
15534 The "kind" part of the "def" and "ref" attributes is taken from the ASIS
15535 enumeration type Flat_Declaration_Kinds, declared in
15536 Asis.Extensions.Flat_Kinds, with the leading "An_" or "A_" removed, and
15537 any trailing "_Declaration" or "_Specification" removed. Thus, the
15538 possible kinds are as follows:
15539
15540 @smallexample
15541 ordinary_type
15542 task_type
15543 protected_type
15544 incomplete_type
15545 tagged_incomplete_type
15546 private_type
15547 private_extension
15548 subtype
15549 variable
15550 constant
15551 deferred_constant
15552 single_task
15553 single_protected
15554 integer_number
15555 real_number
15556 enumeration_literal
15557 discriminant
15558 component
15559 loop_parameter
15560 generalized_iterator
15561 element_iterator
15562 procedure
15563 function
15564 parameter
15565 procedure_body
15566 function_body
15567 return_variable
15568 return_constant
15569 null_procedure
15570 expression_function
15571 package
15572 package_body
15573 object_renaming
15574 exception_renaming
15575 package_renaming
15576 procedure_renaming
15577 function_renaming
15578 generic_package_renaming
15579 generic_procedure_renaming
15580 generic_function_renaming
15581 task_body
15582 protected_body
15583 entry
15584 entry_body
15585 entry_index
15586 procedure_body_stub
15587 function_body_stub
15588 package_body_stub
15589 task_body_stub
15590 protected_body_stub
15591 exception
15592 choice_parameter
15593 generic_procedure
15594 generic_function
15595 generic_package
15596 package_instantiation
15597 procedure_instantiation
15598 function_instantiation
15599 formal_object
15600 formal_type
15601 formal_incomplete_type
15602 formal_procedure
15603 formal_function
15604 formal_package
15605 formal_package_declaration_with_box
15606 @end smallexample
15607 @end ifclear
15608 @end ifclear
15609
15610
15611 @ifclear FSFEDITION
15612 @c *********************************
15613 @node The GNAT Metrics Tool gnatmetric
15614 @chapter The GNAT Metrics Tool @command{gnatmetric}
15615 @findex gnatmetric
15616 @cindex Metric tool
15617
15618 @noindent
15619 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
15620 for computing various program metrics.
15621 It takes an Ada source file as input and generates a file containing the
15622 metrics data as output. Various switches control which
15623 metrics are computed and output.
15624
15625 @menu
15626 * Switches for gnatmetric::
15627 @end menu
15628
15629 To compute program metrics, @command{gnatmetric} invokes the Ada
15630 compiler and generates and uses the ASIS tree for the input source;
15631 thus the input must be legal Ada code, and the tool should have all the
15632 information needed to compile the input source. To provide this information,
15633 you may specify as a tool parameter the project file the input source belongs to
15634 (or you may call @command{gnatmetric}
15635 through the @command{gnat} driver (see @ref{The GNAT Driver and
15636 Project Files}). Another possibility is to specify the source search
15637 path and needed configuration files in @option{-cargs} section of @command{gnatmetric}
15638 call, see the description of the @command{gnatmetric} switches below.
15639
15640 The @command{gnatmetric} command has the form
15641
15642 @smallexample
15643 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15644 @c Expanding @ovar macro inline (explanation in macro def comments)
15645 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15646 @end smallexample
15647
15648 @noindent
15649 where
15650 @itemize @bullet
15651 @item
15652 @var{switches} specify the metrics to compute and define the destination for
15653 the output
15654
15655 @item
15656 Each @var{filename} is the name (including the extension) of a source
15657 file to process. ``Wildcards'' are allowed, and
15658 the file name may contain path information.
15659 If no @var{filename} is supplied, then the @var{switches} list must contain
15660 at least one
15661 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15662 Including both a @option{-files} switch and one or more
15663 @var{filename} arguments is permitted.
15664
15665 @item
15666 @samp{@var{gcc_switches}} is a list of switches for
15667 @command{gcc}. They will be passed on to all compiler invocations made by
15668 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15669 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
15670 and use the @option{-gnatec} switch to set the configuration file,
15671 use the @option{-gnat05} switch if sources should be compiled in
15672 Ada 2005 mode etc.
15673 @end itemize
15674
15675 @node Switches for gnatmetric
15676 @section Switches for @command{gnatmetric}
15677
15678 @noindent
15679 The following subsections describe the various switches accepted by
15680 @command{gnatmetric}, organized by category.
15681
15682 @menu
15683 * Output Files Control::
15684 * Disable Metrics For Local Units::
15685 * Specifying a set of metrics to compute::
15686 * Other gnatmetric Switches::
15687 @ignore
15688 * Generate project-wide metrics::
15689 @end ignore
15690 @end menu
15691
15692 @node Output Files Control
15693 @subsection Output File Control
15694 @cindex Output file control in @command{gnatmetric}
15695
15696 @noindent
15697 @command{gnatmetric} has two output formats. It can generate a
15698 textual (human-readable) form, and also XML. By default only textual
15699 output is generated.
15700
15701 When generating the output in textual form, @command{gnatmetric} creates
15702 for each Ada source file a corresponding text file
15703 containing the computed metrics, except for the case when the set of metrics
15704 specified by gnatmetric parameters consists only of metrics that are computed
15705 for the whole set of analyzed sources, but not for each Ada source.
15706 By default, the name of the file containing metric information for a source
15707 is obtained by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the
15708 name of the input source file. If not otherwise specified and no project file
15709 is specified as @command{gnatmetric} option this file is placed in the same
15710 directory as where the source file is located. If @command{gnatmetric} has a
15711 project file as its parameter, it places all the generated files in the
15712 object directory of the project (or in the project source directory if the
15713 project does not define an objects directory), if @option{--subdirs} option
15714 is specified, the files are placed in the subrirectory of this directory
15715 specified by this option.
15716
15717 All the output information generated in XML format is placed in a single
15718 file. By default the name of this file is ^@file{metrix.xml}^@file{METRIX$XML}^.
15719 If not otherwise specified and if no project file is specified
15720 as @command{gnatmetric} option this file is placed in the
15721 current directory.
15722
15723 Some of the computed metrics are summed over the units passed to
15724 @command{gnatmetric}; for example, the total number of lines of code.
15725 By default this information is sent to @file{stdout}, but a file
15726 can be specified with the @option{-og} switch.
15727
15728 The following switches control the @command{gnatmetric} output:
15729
15730 @table @option
15731 @cindex @option{^-x^/XML^} (@command{gnatmetric})
15732 @item ^-x^/XML^
15733 Generate the XML output
15734
15735 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
15736 @item ^-xs^/XSD^
15737 Generate the XML output and the XML schema file that describes the structure
15738 of the XML metric report, this schema is assigned to the XML file. The schema
15739 file has the same name as the XML output file with @file{.xml} suffix replaced
15740 with @file{.xsd}
15741
15742 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
15743 @item ^-nt^/NO_TEXT^
15744 Do not generate the output in text form (implies @option{^-x^/XML^})
15745
15746 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
15747 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
15748 Put text files with detailed metrics into @var{output_dir}
15749
15750 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
15751 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
15752 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
15753 in the name of the output file.
15754
15755 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
15756 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
15757 Put global metrics into @var{file_name}
15758
15759 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
15760 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
15761 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
15762
15763 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
15764 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
15765 Use ``short'' source file names in the output. (The @command{gnatmetric}
15766 output includes the name(s) of the Ada source file(s) from which the metrics
15767 are computed. By default each name includes the absolute path. The
15768 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
15769 to exclude all directory information from the file names that are output.)
15770
15771 @end table
15772
15773 @node Disable Metrics For Local Units
15774 @subsection Disable Metrics For Local Units
15775 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15776
15777 @noindent
15778 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15779 one compilation
15780 unit per one source file. It computes line metrics for the whole source
15781 file, and it also computes syntax
15782 and complexity metrics for the file's outermost unit.
15783
15784 By default, @command{gnatmetric} will also compute all metrics for certain
15785 kinds of locally declared program units:
15786
15787 @itemize @bullet
15788 @item
15789 subprogram (and generic subprogram) bodies;
15790
15791 @item
15792 package (and generic package) specs and bodies;
15793
15794 @item
15795 task object and type specifications and bodies;
15796
15797 @item
15798 protected object and type specifications and bodies.
15799 @end itemize
15800
15801 @noindent
15802 These kinds of entities will be referred to as
15803 @emph{eligible local program units}, or simply @emph{eligible local units},
15804 @cindex Eligible local unit (for @command{gnatmetric})
15805 in the discussion below.
15806
15807 Note that a subprogram declaration, generic instantiation,
15808 or renaming declaration only receives metrics
15809 computation when it appear as the outermost entity
15810 in a source file.
15811
15812 Suppression of metrics computation for eligible local units can be
15813 obtained via the following switch:
15814
15815 @table @option
15816 @cindex @option{^-nolocal^/SUPPRESS^} (@command{gnatmetric})
15817 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
15818 Do not compute detailed metrics for eligible local program units
15819
15820 @end table
15821
15822 @node Specifying a set of metrics to compute
15823 @subsection Specifying a set of metrics to compute
15824
15825 @noindent
15826 By default all the metrics are computed and reported. The switches
15827 described in this subsection allow you to control, on an individual
15828 basis, whether metrics are computed and
15829 reported. If at least one positive metric
15830 switch is specified (that is, a switch that defines that a given
15831 metric or set of metrics is to be computed), then only
15832 explicitly specified metrics are reported.
15833
15834 @menu
15835 * Line Metrics Control::
15836 * Syntax Metrics Control::
15837 * Complexity Metrics Control::
15838 * Coupling Metrics Control::
15839 @end menu
15840
15841 @node Line Metrics Control
15842 @subsubsection Line Metrics Control
15843 @cindex Line metrics control in @command{gnatmetric}
15844
15845 @noindent
15846 For any (legal) source file, and for each of its
15847 eligible local program units, @command{gnatmetric} computes the following
15848 metrics:
15849
15850 @itemize @bullet
15851 @item
15852 the total number of lines;
15853
15854 @item
15855 the total number of code lines (i.e., non-blank lines that are not comments)
15856
15857 @item
15858 the number of comment lines
15859
15860 @item
15861 the number of code lines containing end-of-line comments;
15862
15863 @item
15864 the comment percentage: the ratio between the number of lines that contain
15865 comments and the number of all non-blank lines, expressed as a percentage;
15866
15867 @item
15868 the number of empty lines and lines containing only space characters and/or
15869 format effectors (blank lines)
15870
15871 @item
15872 the average number of code lines in subprogram bodies, task bodies, entry
15873 bodies and statement sequences in package bodies (this metric is only computed
15874 across the whole set of the analyzed units)
15875
15876 @end itemize
15877
15878 @noindent
15879 @command{gnatmetric} sums the values of the line metrics for all the
15880 files being processed and then generates the cumulative results. The tool
15881 also computes for all the files being processed the average number of code
15882 lines in bodies.
15883
15884 You can use the following switches to select the specific line metrics
15885 to be computed and reported.
15886
15887 @table @option
15888 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
15889
15890 @ifclear vms
15891 @cindex @option{--no-lines@var{x}}
15892 @end ifclear
15893
15894 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
15895 Report all the line metrics
15896
15897 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
15898 Do not report any of line metrics
15899
15900 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
15901 Report the number of all lines
15902
15903 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
15904 Do not report the number of all lines
15905
15906 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
15907 Report the number of code lines
15908
15909 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
15910 Do not report the number of code lines
15911
15912 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
15913 Report the number of comment lines
15914
15915 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
15916 Do not report the number of comment lines
15917
15918 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
15919 Report the number of code lines containing
15920 end-of-line comments
15921
15922 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
15923 Do not report the number of code lines containing
15924 end-of-line comments
15925
15926 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
15927 Report the comment percentage in the program text
15928
15929 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
15930 Do not report the comment percentage in the program text
15931
15932 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
15933 Report the number of blank lines
15934
15935 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
15936 Do not report the number of blank lines
15937
15938 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
15939 Report the average number of code lines in subprogram bodies, task bodies,
15940 entry bodies and statement sequences in package bodies. The metric is computed
15941 and reported for the whole set of processed Ada sources only.
15942
15943 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
15944 Do not report the average number of code lines in subprogram bodies,
15945 task bodies, entry bodies and statement sequences in package bodies.
15946
15947 @end table
15948
15949 @node Syntax Metrics Control
15950 @subsubsection Syntax Metrics Control
15951 @cindex Syntax metrics control in @command{gnatmetric}
15952
15953 @noindent
15954 @command{gnatmetric} computes various syntactic metrics for the
15955 outermost unit and for each eligible local unit:
15956
15957 @table @emph
15958 @item LSLOC (``Logical Source Lines Of Code'')
15959 The total number of declarations and the total number of statements. Note
15960 that the definition of declarations is the one given in the reference
15961 manual:
15962
15963 @noindent
15964 ``Each of the following is defined to be a declaration: any basic_declaration;
15965 an enumeration_literal_specification; a discriminant_specification;
15966 a component_declaration; a loop_parameter_specification; a
15967 parameter_specification; a subprogram_body; an entry_declaration;
15968 an entry_index_specification; a choice_parameter_specification;
15969 a generic_formal_parameter_declaration.''
15970
15971 This means for example that each enumeration literal adds one to the count,
15972 as well as each subprogram parameter.
15973
15974 Thus the results from this metric will be significantly greater than might
15975 be expected from a naive view of counting semicolons.
15976
15977 @item Maximal static nesting level of inner program units
15978 According to
15979 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
15980 package, a task unit, a protected unit, a
15981 protected entry, a generic unit, or an explicitly declared subprogram other
15982 than an enumeration literal.''
15983
15984 @item Maximal nesting level of composite syntactic constructs
15985 This corresponds to the notion of the
15986 maximum nesting level in the GNAT built-in style checks
15987 (@pxref{Style Checking})
15988 @end table
15989
15990 @noindent
15991 For the outermost unit in the file, @command{gnatmetric} additionally computes
15992 the following metrics:
15993
15994 @table @emph
15995 @item Public subprograms
15996 This metric is computed for package specs. It is the
15997 number of subprograms and generic subprograms declared in the visible
15998 part (including the visible part of nested packages, protected objects, and
15999 protected types).
16000
16001 @item All subprograms
16002 This metric is computed for bodies and subunits. The
16003 metric is equal to a total number of subprogram bodies in the compilation
16004 unit.
16005 Neither generic instantiations nor renamings-as-a-body nor body stubs
16006 are counted. Any subprogram body is counted, independently of its nesting
16007 level and enclosing constructs. Generic bodies and bodies of protected
16008 subprograms are counted in the same way as ``usual'' subprogram bodies.
16009
16010 @item Public types
16011 This metric is computed for package specs and
16012 generic package declarations. It is the total number of types
16013 that can be referenced from outside this compilation unit, plus the
16014 number of types from all the visible parts of all the visible generic
16015 packages. Generic formal types are not counted. Only types, not subtypes,
16016 are included.
16017
16018 @noindent
16019 Along with the total number of public types, the following
16020 types are counted and reported separately:
16021
16022 @itemize @bullet
16023 @item
16024 Abstract types
16025
16026 @item
16027 Root tagged types (abstract, non-abstract, private, non-private). Type
16028 extensions are @emph{not} counted
16029
16030 @item
16031 Private types (including private extensions)
16032
16033 @item
16034 Task types
16035
16036 @item
16037 Protected types
16038
16039 @end itemize
16040
16041 @item All types
16042 This metric is computed for any compilation unit. It is equal to the total
16043 number of the declarations of different types given in the compilation unit.
16044 The private and the corresponding full type declaration are counted as one
16045 type declaration. Incomplete type declarations and generic formal types
16046 are not counted.
16047 No distinction is made among different kinds of types (abstract,
16048 private etc.); the total number of types is computed and reported.
16049
16050 @end table
16051
16052 @noindent
16053 By default, all the syntax metrics are computed and reported. You can use the
16054 following switches to select specific syntax metrics.
16055
16056 @table @option
16057
16058 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
16059
16060 @ifclear vms
16061 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
16062 @end ifclear
16063
16064 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
16065 Report all the syntax metrics
16066
16067 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
16068 Do not report any of syntax metrics
16069
16070 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
16071 Report the total number of declarations
16072
16073 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
16074 Do not report the total number of declarations
16075
16076 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
16077 Report the total number of statements
16078
16079 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
16080 Do not report the total number of statements
16081
16082 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
16083 Report the number of public subprograms in a compilation unit
16084
16085 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
16086 Do not report the number of public subprograms in a compilation unit
16087
16088 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
16089 Report the number of all the subprograms in a compilation unit
16090
16091 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
16092 Do not report the number of all the subprograms in a compilation unit
16093
16094 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
16095 Report the number of public types in a compilation unit
16096
16097 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
16098 Do not report the number of public types in a compilation unit
16099
16100 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
16101 Report the number of all the types in a compilation unit
16102
16103 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
16104 Do not report the number of all the types in a compilation unit
16105
16106 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
16107 Report the maximal program unit nesting level
16108
16109 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
16110 Do not report the maximal program unit nesting level
16111
16112 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
16113 Report the maximal construct nesting level
16114
16115 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
16116 Do not report the maximal construct nesting level
16117
16118 @end table
16119
16120 @node Complexity Metrics Control
16121 @subsubsection Complexity Metrics Control
16122 @cindex Complexity metrics control in @command{gnatmetric}
16123
16124 @noindent
16125 For a program unit that is an executable body (a subprogram body (including
16126 generic bodies), task body, entry body or a package body containing
16127 its own statement sequence) @command{gnatmetric} computes the following
16128 complexity metrics:
16129
16130 @itemize @bullet
16131 @item
16132 McCabe cyclomatic complexity;
16133
16134 @item
16135 McCabe essential complexity;
16136
16137 @item
16138 maximal loop nesting level;
16139
16140 @item
16141 extra exit points (for subprograms);
16142 @end itemize
16143
16144 @noindent
16145 The McCabe cyclomatic complexity metric is defined
16146 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
16147
16148 According to McCabe, both control statements and short-circuit control forms
16149 should be taken into account when computing cyclomatic complexity.
16150 For Ada 2012 we have also take into account conditional expressions
16151 and quantified expressions. For each body, we compute three metric values:
16152
16153 @itemize @bullet
16154 @item
16155 the complexity introduced by control
16156 statements only, without taking into account short-circuit forms,
16157
16158 @item
16159 the complexity introduced by short-circuit control forms only, and
16160
16161 @item
16162 the total
16163 cyclomatic complexity, which is the sum of these two values.
16164 @end itemize
16165
16166 @noindent
16167
16168 The cyclomatic complexity is also computed for Ada 2012 expression functions.
16169 An expression function cannot have statements as its components, so only one
16170 metric value is computed as a cyclomatic complexity of an expression function.
16171
16172 The origin of cyclomatic complexity metric is the need to estimate the number
16173 of independent paths in the control flow graph that in turn gives the number
16174 of tests needed to satisfy paths coverage testing completeness criterion.
16175 Considered from the testing point of view, a static Ada @code{loop} (that is,
16176 the @code{loop} statement having static subtype in loop parameter
16177 specification) does not add to cyclomatic complexity. By providing
16178 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
16179 may specify that such loops should not be counted when computing the
16180 cyclomatic complexity metric
16181
16182 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
16183 counted for the code that is reduced by excluding all the pure structural Ada
16184 control statements. An compound statement is considered as a non-structural
16185 if it contains a @code{raise} or @code{return} statement as it subcomponent,
16186 or if it contains a @code{goto} statement that transfers the control outside
16187 the operator. A selective accept statement with @code{terminate} alternative
16188 is considered as non-structural statement. When computing this metric,
16189 @code{exit} statements are treated in the same way as @code{goto}
16190 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
16191
16192 The Ada essential complexity metric defined here is intended to quantify
16193 the extent to which the software is unstructured. It is adapted from
16194 the McCabe essential complexity metric defined in
16195 @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more
16196 suitable for typical Ada usage. For example, short circuit forms
16197 are not penalized as unstructured in the Ada essential complexity metric.
16198
16199 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
16200 the code in the exception handlers and in all the nested program units. The
16201 code of assertions and predicates (that is, subprogram preconditions and
16202 postconditions, subtype predicates and type invariants) is also skipped.
16203
16204 By default, all the complexity metrics are computed and reported.
16205 For more fine-grained control you can use
16206 the following switches:
16207
16208 @table @option
16209 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
16210
16211 @ifclear vms
16212 @cindex @option{--no-complexity@var{x}}
16213 @end ifclear
16214
16215 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
16216 Report all the complexity metrics
16217
16218 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
16219 Do not report any of complexity metrics
16220
16221 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
16222 Report the McCabe Cyclomatic Complexity
16223
16224 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
16225 Do not report the McCabe Cyclomatic Complexity
16226
16227 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
16228 Report the Essential Complexity
16229
16230 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
16231 Do not report the Essential Complexity
16232
16233 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
16234 Report maximal loop nesting level
16235
16236 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
16237 Do not report maximal loop nesting level
16238
16239 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
16240 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
16241 task bodies, entry bodies and statement sequences in package bodies.
16242 The metric is computed and reported for whole set of processed Ada sources
16243 only.
16244
16245 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
16246 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
16247 bodies, task bodies, entry bodies and statement sequences in package bodies
16248
16249 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
16250 @item ^-ne^/NO_EXITS_AS_GOTOS^
16251 Do not consider @code{exit} statements as @code{goto}s when
16252 computing Essential Complexity
16253
16254 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
16255 @item ^--no-static-loop^/NO_STATIC_LOOP^
16256 Do not consider static loops when computing cyclomatic complexity
16257
16258 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
16259 Report the extra exit points for subprogram bodies. As an exit point, this
16260 metric counts @code{return} statements and raise statements in case when the
16261 raised exception is not handled in the same body. In case of a function this
16262 metric subtracts 1 from the number of exit points, because a function body
16263 must contain at least one @code{return} statement.
16264
16265 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
16266 Do not report the extra exit points for subprogram bodies
16267 @end table
16268
16269
16270 @node Coupling Metrics Control
16271 @subsubsection Coupling Metrics Control
16272 @cindex Coupling metrics control in @command{gnatmetric}
16273
16274 @noindent
16275 @cindex Coupling metrics (in @command{gnatmetric})
16276 Coupling metrics measure the dependencies between a given entity and other
16277 entities in the program. This information is useful since high coupling
16278 may signal potential issues with maintainability as the program evolves.
16279
16280 @command{gnatmetric} computes the following coupling metrics:
16281
16282 @itemize @bullet
16283
16284 @item
16285 @emph{object-oriented coupling}, for classes in traditional object-oriented
16286 sense;
16287
16288 @item
16289 @emph{unit coupling}, for all the program units making up a program;
16290
16291 @item
16292 @emph{control coupling}, reflecting dependencies between a unit and
16293 other units that contain subprograms.
16294 @end itemize
16295
16296 @noindent
16297 Two kinds of coupling metrics are computed:
16298
16299 @itemize @bullet
16300 @item fan-out coupling (``efferent coupling''):
16301 @cindex fan-out coupling
16302 @cindex efferent coupling
16303 the number of entities the given entity depends upon. This metric
16304 reflects how the given entity depends on the changes in the
16305 ``external world''.
16306
16307 @item fan-in coupling (``afferent'' coupling):
16308 @cindex fan-in coupling
16309 @cindex afferent coupling
16310 the number of entities that depend on a given entity.
16311 This metric reflects how the ``external world'' depends on the changes in a
16312 given entity.
16313 @end itemize
16314
16315 @noindent
16316 Object-oriented coupling metrics measure the dependencies
16317 between a given class (or a group of classes) and the other classes in the
16318 program. In this subsection the term ``class'' is used in its traditional
16319 object-oriented programming sense (an instantiable module that contains data
16320 and/or method members). A @emph{category} (of classes) is a group of closely
16321 related classes that are reused and/or modified together.
16322
16323 A class @code{K}'s fan-out coupling is the number of classes
16324 that @code{K} depends upon.
16325 A category's fan-out coupling is the number of classes outside the
16326 category that the classes inside the category depend upon.
16327
16328 A class @code{K}'s fan-in coupling is the number of classes
16329 that depend upon @code{K}.
16330 A category's fan-in coupling is the number of classes outside the
16331 category that depend on classes belonging to the category.
16332
16333 Ada's object-oriented paradigm separates the instantiable entity
16334 (type) from the module (package), so the definition of the coupling
16335 metrics for Ada maps the class and class category notions
16336 onto Ada constructs.
16337
16338 For the coupling metrics, several kinds of modules that define a tagged type
16339 or an interface type -- library packages, library generic packages, and
16340 library generic package instantiations -- are considered to be classes.
16341 A category consists of a library package (or
16342 a library generic package) that defines a tagged or an interface type,
16343 together with all its descendant (generic) packages that define tagged
16344 or interface types. Thus a
16345 category is an Ada hierarchy of library-level program units. Class
16346 coupling in Ada is referred to as ``tagged coupling'', and category coupling
16347 is referred to as ``hierarchy coupling''.
16348
16349 For any package serving as a class, its body and subunits (if any) are
16350 considered together with its spec when computing dependencies, and coupling
16351 metrics are reported for spec units only. Dependencies between classes
16352 mean Ada semantic dependencies. For object-oriented coupling
16353 metrics, only dependencies on units treated as classes are
16354 considered.
16355
16356 Similarly, for unit and control coupling an entity is considered to be the
16357 conceptual construct consisting of the entity's specification, body, and
16358 any subunits (transitively).
16359 @command{gnatmetric} computes
16360 the dependencies of all these units as a whole, but
16361 metrics are only reported for spec
16362 units (or for a subprogram body unit in case if there is no
16363 separate spec for the given subprogram).
16364
16365 For unit coupling, dependencies are computed between all kinds of program
16366 units. For control coupling, the dependencies of a given unit are limited to
16367 those units that define subprograms. Thus control fan-out coupling is reported
16368 for all units, but control fan-in coupling is only reported for units
16369 that define subprograms.
16370
16371 The following simple example illustrates the difference between unit coupling
16372 and control coupling metrics:
16373
16374 @smallexample @c ada
16375 @group
16376 package Lib_1 is
16377 function F_1 (I : Integer) return Integer;
16378 end Lib_1;
16379 @end group
16380
16381 @group
16382 package Lib_2 is
16383 type T_2 is new Integer;
16384 end Lib_2;
16385 @end group
16386
16387 @group
16388 package body Lib_1 is
16389 function F_1 (I : Integer) return Integer is
16390 begin
16391 return I + 1;
16392 end F_1;
16393 end Lib_1;
16394 @end group
16395
16396 @group
16397 with Lib_2; use Lib_2;
16398 package Pack is
16399 Var : T_2;
16400 function Fun (I : Integer) return Integer;
16401 end Pack;
16402 @end group
16403
16404 @group
16405 with Lib_1; use Lib_1;
16406 package body Pack is
16407 function Fun (I : Integer) return Integer is
16408 begin
16409 return F_1 (I);
16410 end Fun;
16411 end Pack;
16412 @end group
16413 @end smallexample
16414
16415 @noindent
16416 If we apply @command{gnatmetric} with the @option{--coupling-all} option to
16417 these units, the result will be:
16418
16419 @smallexample
16420 @group
16421 Coupling metrics:
16422 =================
16423 Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads)
16424 control fan-out coupling : 0
16425 control fan-in coupling : 1
16426 unit fan-out coupling : 0
16427 unit fan-in coupling : 1
16428 @end group
16429
16430 @group
16431 Unit Pack (C:\customers\662\L406-007\pack.ads)
16432 control fan-out coupling : 1
16433 control fan-in coupling : 0
16434 unit fan-out coupling : 2
16435 unit fan-in coupling : 0
16436 @end group
16437
16438 @group
16439 Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads)
16440 control fan-out coupling : 0
16441 unit fan-out coupling : 0
16442 unit fan-in coupling : 1
16443 @end group
16444 @end smallexample
16445
16446 @noindent
16447 The result does not contain values for object-oriented
16448 coupling because none of the argument units contains a tagged type and
16449 therefore none of these units can be treated as a class.
16450
16451 The @code{Pack} package (spec and body) depends on two
16452 units -- @code{Lib_1} @code{and Lib_2} -- and so its unit fan-out coupling
16453 is 2. Since nothing depends on it, its unit fan-in coupling is 0, as
16454 is its control fan-in coupling. Only one of the units @code{Pack} depends
16455 upon defines a subprogram, so its control fan-out coupling is 1.
16456
16457 @code{Lib_2} depends on nothing, so its fan-out metrics are 0. It does
16458 not define any subprograms, so it has no control fan-in metric.
16459 One unit (@code{Pack}) depends on it , so its unit fan-in coupling is 1.
16460
16461 @code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram.
16462 Its control fan-in coupling is 1 (because there is one unit
16463 depending on it).
16464
16465 When computing coupling metrics, @command{gnatmetric} counts only
16466 dependencies between units that are arguments of the @command{gnatmetric}
16467 invocation. Coupling metrics are program-wide (or project-wide) metrics, so
16468 you should invoke @command{gnatmetric} for
16469 the complete set of sources comprising your program. This can be done
16470 by invoking @command{gnatmetric} with the corresponding project file
16471 and with the @option{-U} option.
16472
16473 By default, all the coupling metrics are disabled. You can use the following
16474 switches to specify the coupling metrics to be computed and reported:
16475
16476 @table @option
16477
16478 @ifclear vms
16479 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
16480 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
16481 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
16482 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
16483 @end ifclear
16484
16485 @ifset vms
16486 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
16487 @end ifset
16488
16489 @item ^--coupling-all^/COUPLING_METRICS=ALL^
16490 Report all the coupling metrics
16491
16492 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
16493 Report tagged (class) fan-out coupling
16494
16495 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
16496 Report tagged (class) fan-in coupling
16497
16498 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
16499 Report hierarchy (category) fan-out coupling
16500
16501 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
16502 Report hierarchy (category) fan-in coupling
16503
16504 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
16505 Report unit fan-out coupling
16506
16507 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
16508 Report unit fan-in coupling
16509
16510 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
16511 Report control fan-out coupling
16512
16513 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
16514 Report control fan-in coupling
16515 @end table
16516
16517 @node Other gnatmetric Switches
16518 @subsection Other @code{gnatmetric} Switches
16519
16520 @noindent
16521 Additional @command{gnatmetric} switches are as follows:
16522
16523 @table @option
16524 @item --version
16525 @cindex @option{--version} @command{gnatmetric}
16526 Display Copyright and version, then exit disregarding all other options.
16527
16528 @item --help
16529 @cindex @option{--help} @command{gnatmetric}
16530 Display usage, then exit disregarding all other options.
16531
16532 @item -P @var{file}
16533 @cindex @option{-P} @command{gnatmetric}
16534 Indicates the name of the project file that describes the set of sources
16535 to be processed. The exact set of argument sources depends on other options
16536 specified, see below.
16537
16538 @item -U
16539 @cindex @option{-U} @command{gnatmetric}
16540 If a project file is specified and no argument source is explicitly
16541 specified (either directly or by means of @option{-files} option), process
16542 all the units of the closure of the argument project. Otherwise this option
16543 has no effect.
16544
16545 @item -U @var{main_unit}
16546 If a project file is specified and no argument source is explicitly
16547 specified (either directly or by means of @option{-files} option), process
16548 the closure of units rooted at @var{main_unit}. Otherwise this option
16549 has no effect.
16550
16551 @item -X@var{name}=@var{value}
16552 @cindex @option{-X} @command{gnatmetric}
16553 Indicates that external variable @var{name} in the argument project
16554 has the value @var{value}. Has no effect if no project is specified as
16555 tool argument.
16556
16557 @item --subdirs=@var{dir}
16558 @cindex @option{--subdirs=@var{dir}} @command{gnatmetric}
16559 Use the specified subdirectory of the project objects file (or of the
16560 project file directory if the project does not specify an object directory)
16561 for tool output files. Has no effect if no project is specified as
16562 tool argument r if @option{--no_objects_dir} is specified.
16563
16564 @item --no_objects_dir
16565 @cindex @option{--no_objects_dir} @command{gnatmetric}
16566 Place all the result files into the current directory instead of
16567 project objects directory. This corresponds to the @command{gnatcheck}
16568 behavior when it is called with the project file from the
16569 GNAT driver. Has no effect if no project is specified.
16570
16571 @item ^-files @var{filename}^/FILES=@var{filename}^
16572 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
16573 Take the argument source files from the specified file. This file should be an
16574 ordinary text file containing file names separated by spaces or
16575 line breaks. You can use this switch more than once in the same call to
16576 @command{gnatmetric}. You also can combine this switch with
16577 an explicit list of files.
16578
16579 @item ^-j^/PROCESSES=^@var{n}
16580 @cindex @option{^-j^/PROCESSES^} (@command{gnatmetric})
16581 Use @var{n} processes to carry out the tree creations (internal representations
16582 of the argument sources). On a multiprocessor machine this speeds up processing
16583 of big sets of argument sources. If @var{n} is 0, then the maximum number of
16584 parallel tree creations is the number of core processors on the platform.
16585
16586 @cindex @option{^-t^/TIME^} (@command{gnatmetric})
16587 @item ^-t^/TIME^
16588 Print out execution time.
16589
16590 @item ^-v^/VERBOSE^
16591 @cindex @option{^-v^/VERBOSE^} (@command{gnatmetric})
16592 Verbose mode;
16593 @command{gnatmetric} generates version information and then
16594 a trace of sources being processed.
16595
16596 @item ^-q^/QUIET^
16597 @cindex @option{^-q^/QUIET^} (@command{gnatmetric})
16598 Quiet mode.
16599 @end table
16600
16601 @noindent
16602 If a project file is specified and no argument source is explicitly
16603 specified (either directly or by means of @option{-files} option), and no
16604 @option{-U} is specified, then the set of processed sources is
16605 all the immediate units of the argument project.
16606
16607
16608 @ignore
16609 @node Generate project-wide metrics
16610 @subsection Generate project-wide metrics
16611
16612 In order to compute metrics on all units of a given project, you can use
16613 the @command{gnat} driver along with the @option{-P} option:
16614 @smallexample
16615 gnat metric -Pproj
16616 @end smallexample
16617
16618 @noindent
16619 If the project @code{proj} depends upon other projects, you can compute
16620 the metrics on the project closure using the @option{-U} option:
16621 @smallexample
16622 gnat metric -Pproj -U
16623 @end smallexample
16624
16625 @noindent
16626 Finally, if not all the units are relevant to a particular main
16627 program in the project closure, you can generate metrics for the set
16628 of units needed to create a given main program (unit closure) using
16629 the @option{-U} option followed by the name of the main unit:
16630 @smallexample
16631 gnat metric -Pproj -U main
16632 @end smallexample
16633 @end ignore
16634 @end ifclear
16635
16636
16637 @c ***********************************
16638 @node File Name Krunching with gnatkr
16639 @chapter File Name Krunching with @code{gnatkr}
16640 @findex gnatkr
16641
16642 @noindent
16643 This chapter discusses the method used by the compiler to shorten
16644 the default file names chosen for Ada units so that they do not
16645 exceed the maximum length permitted. It also describes the
16646 @code{gnatkr} utility that can be used to determine the result of
16647 applying this shortening.
16648 @menu
16649 * About gnatkr::
16650 * Using gnatkr::
16651 * Krunching Method::
16652 * Examples of gnatkr Usage::
16653 @end menu
16654
16655 @node About gnatkr
16656 @section About @code{gnatkr}
16657
16658 @noindent
16659 The default file naming rule in GNAT
16660 is that the file name must be derived from
16661 the unit name. The exact default rule is as follows:
16662 @itemize @bullet
16663 @item
16664 Take the unit name and replace all dots by hyphens.
16665 @item
16666 If such a replacement occurs in the
16667 second character position of a name, and the first character is
16668 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
16669 then replace the dot by the character
16670 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
16671 instead of a minus.
16672 @end itemize
16673 The reason for this exception is to avoid clashes
16674 with the standard names for children of System, Ada, Interfaces,
16675 and GNAT, which use the prefixes
16676 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
16677 respectively.
16678
16679 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
16680 switch of the compiler activates a ``krunching''
16681 circuit that limits file names to nn characters (where nn is a decimal
16682 integer). For example, using OpenVMS,
16683 where the maximum file name length is
16684 39, the value of nn is usually set to 39, but if you want to generate
16685 a set of files that would be usable if ported to a system with some
16686 different maximum file length, then a different value can be specified.
16687 The default value of 39 for OpenVMS need not be specified.
16688
16689 The @code{gnatkr} utility can be used to determine the krunched name for
16690 a given file, when krunched to a specified maximum length.
16691
16692 @node Using gnatkr
16693 @section Using @code{gnatkr}
16694
16695 @noindent
16696 The @code{gnatkr} command has the form
16697
16698 @ifclear vms
16699 @smallexample
16700 @c $ gnatkr @var{name} @ovar{length}
16701 @c Expanding @ovar macro inline (explanation in macro def comments)
16702 $ gnatkr @var{name} @r{[}@var{length}@r{]}
16703 @end smallexample
16704 @end ifclear
16705
16706 @ifset vms
16707 @smallexample
16708 $ gnatkr @var{name} /COUNT=nn
16709 @end smallexample
16710 @end ifset
16711
16712 @noindent
16713 @var{name} is the uncrunched file name, derived from the name of the unit
16714 in the standard manner described in the previous section (i.e., in particular
16715 all dots are replaced by hyphens). The file name may or may not have an
16716 extension (defined as a suffix of the form period followed by arbitrary
16717 characters other than period). If an extension is present then it will
16718 be preserved in the output. For example, when krunching @file{hellofile.ads}
16719 to eight characters, the result will be hellofil.ads.
16720
16721 Note: for compatibility with previous versions of @code{gnatkr} dots may
16722 appear in the name instead of hyphens, but the last dot will always be
16723 taken as the start of an extension. So if @code{gnatkr} is given an argument
16724 such as @file{Hello.World.adb} it will be treated exactly as if the first
16725 period had been a hyphen, and for example krunching to eight characters
16726 gives the result @file{hellworl.adb}.
16727
16728 Note that the result is always all lower case (except on OpenVMS where it is
16729 all upper case). Characters of the other case are folded as required.
16730
16731 @var{length} represents the length of the krunched name. The default
16732 when no argument is given is ^8^39^ characters. A length of zero stands for
16733 unlimited, in other words do not chop except for system files where the
16734 implied crunching length is always eight characters.
16735
16736 @noindent
16737 The output is the krunched name. The output has an extension only if the
16738 original argument was a file name with an extension.
16739
16740 @node Krunching Method
16741 @section Krunching Method
16742
16743 @noindent
16744 The initial file name is determined by the name of the unit that the file
16745 contains. The name is formed by taking the full expanded name of the
16746 unit and replacing the separating dots with hyphens and
16747 using ^lowercase^uppercase^
16748 for all letters, except that a hyphen in the second character position is
16749 replaced by a ^tilde^dollar sign^ if the first character is
16750 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
16751 The extension is @code{.ads} for a
16752 spec and @code{.adb} for a body.
16753 Krunching does not affect the extension, but the file name is shortened to
16754 the specified length by following these rules:
16755
16756 @itemize @bullet
16757 @item
16758 The name is divided into segments separated by hyphens, tildes or
16759 underscores and all hyphens, tildes, and underscores are
16760 eliminated. If this leaves the name short enough, we are done.
16761
16762 @item
16763 If the name is too long, the longest segment is located (left-most
16764 if there are two of equal length), and shortened by dropping
16765 its last character. This is repeated until the name is short enough.
16766
16767 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16768 to fit the name into 8 characters as required by some operating systems.
16769
16770 @smallexample
16771 our-strings-wide_fixed 22
16772 our strings wide fixed 19
16773 our string wide fixed 18
16774 our strin wide fixed 17
16775 our stri wide fixed 16
16776 our stri wide fixe 15
16777 our str wide fixe 14
16778 our str wid fixe 13
16779 our str wid fix 12
16780 ou str wid fix 11
16781 ou st wid fix 10
16782 ou st wi fix 9
16783 ou st wi fi 8
16784 Final file name: oustwifi.adb
16785 @end smallexample
16786
16787 @item
16788 The file names for all predefined units are always krunched to eight
16789 characters. The krunching of these predefined units uses the following
16790 special prefix replacements:
16791
16792 @table @file
16793 @item ada-
16794 replaced by @file{^a^A^-}
16795
16796 @item gnat-
16797 replaced by @file{^g^G^-}
16798
16799 @item interfaces-
16800 replaced by @file{^i^I^-}
16801
16802 @item system-
16803 replaced by @file{^s^S^-}
16804 @end table
16805
16806 These system files have a hyphen in the second character position. That
16807 is why normal user files replace such a character with a
16808 ^tilde^dollar sign^, to
16809 avoid confusion with system file names.
16810
16811 As an example of this special rule, consider
16812 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16813
16814 @smallexample
16815 ada-strings-wide_fixed 22
16816 a- strings wide fixed 18
16817 a- string wide fixed 17
16818 a- strin wide fixed 16
16819 a- stri wide fixed 15
16820 a- stri wide fixe 14
16821 a- str wide fixe 13
16822 a- str wid fixe 12
16823 a- str wid fix 11
16824 a- st wid fix 10
16825 a- st wi fix 9
16826 a- st wi fi 8
16827 Final file name: a-stwifi.adb
16828 @end smallexample
16829 @end itemize
16830
16831 Of course no file shortening algorithm can guarantee uniqueness over all
16832 possible unit names, and if file name krunching is used then it is your
16833 responsibility to ensure that no name clashes occur. The utility
16834 program @code{gnatkr} is supplied for conveniently determining the
16835 krunched name of a file.
16836
16837 @node Examples of gnatkr Usage
16838 @section Examples of @code{gnatkr} Usage
16839
16840 @smallexample
16841 @iftex
16842 @leftskip=0cm
16843 @end iftex
16844 @ifclear vms
16845 $ gnatkr very_long_unit_name.ads --> velounna.ads
16846 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16847 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16848 $ gnatkr grandparent-parent-child --> grparchi
16849 @end ifclear
16850 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16851 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16852 @end smallexample
16853
16854 @node Preprocessing with gnatprep
16855 @chapter Preprocessing with @code{gnatprep}
16856 @findex gnatprep
16857
16858 @noindent
16859 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
16860 preprocessing.
16861 Although designed for use with GNAT, @code{gnatprep} does not depend on any
16862 special GNAT features.
16863 For further discussion of conditional compilation in general, see
16864 @ref{Conditional Compilation}.
16865
16866 @menu
16867 * Preprocessing Symbols::
16868 * Using gnatprep::
16869 * Switches for gnatprep::
16870 * Form of Definitions File::
16871 * Form of Input Text for gnatprep::
16872 @end menu
16873
16874 @node Preprocessing Symbols
16875 @section Preprocessing Symbols
16876
16877 @noindent
16878 Preprocessing symbols are defined in definition files and referred to in
16879 sources to be preprocessed. A Preprocessing symbol is an identifier, following
16880 normal Ada (case-insensitive) rules for its syntax, with the restriction that
16881 all characters need to be in the ASCII set (no accented letters).
16882
16883 @node Using gnatprep
16884 @section Using @code{gnatprep}
16885
16886 @noindent
16887 To call @code{gnatprep} use
16888
16889 @smallexample
16890 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
16891 @c Expanding @ovar macro inline (explanation in macro def comments)
16892 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
16893 @end smallexample
16894
16895 @noindent
16896 where
16897 @table @var
16898 @item switches
16899 is an optional sequence of switches as described in the next section.
16900
16901 @item infile
16902 is the full name of the input file, which is an Ada source
16903 file containing preprocessor directives.
16904
16905 @item outfile
16906 is the full name of the output file, which is an Ada source
16907 in standard Ada form. When used with GNAT, this file name will
16908 normally have an ads or adb suffix.
16909
16910 @item deffile
16911 is the full name of a text file containing definitions of
16912 preprocessing symbols to be referenced by the preprocessor. This argument is
16913 optional, and can be replaced by the use of the @option{-D} switch.
16914
16915 @end table
16916
16917 @node Switches for gnatprep
16918 @section Switches for @code{gnatprep}
16919
16920 @table @option
16921 @c !sort!
16922
16923 @item ^-b^/BLANK_LINES^
16924 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16925 Causes both preprocessor lines and the lines deleted by
16926 preprocessing to be replaced by blank lines in the output source file,
16927 preserving line numbers in the output file.
16928
16929 @item ^-c^/COMMENTS^
16930 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16931 Causes both preprocessor lines and the lines deleted
16932 by preprocessing to be retained in the output source as comments marked
16933 with the special string @code{"--! "}. This option will result in line numbers
16934 being preserved in the output file.
16935
16936 @item ^-C^/REPLACE_IN_COMMENTS^
16937 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
16938 Causes comments to be scanned. Normally comments are ignored by gnatprep.
16939 If this option is specified, then comments are scanned and any $symbol
16940 substitutions performed as in program text. This is particularly useful
16941 when structured comments are used (e.g., when writing programs in the
16942 SPARK dialect of Ada). Note that this switch is not available when
16943 doing integrated preprocessing (it would be useless in this context
16944 since comments are ignored by the compiler in any case).
16945
16946 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16947 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16948 Defines a new preprocessing symbol, associated with value. If no value is given
16949 on the command line, then symbol is considered to be @code{True}. This switch
16950 can be used in place of a definition file.
16951
16952 @ifset vms
16953 @item /REMOVE
16954 @cindex @option{/REMOVE} (@command{gnatprep})
16955 This is the default setting which causes lines deleted by preprocessing
16956 to be entirely removed from the output file.
16957 @end ifset
16958
16959 @item ^-r^/REFERENCE^
16960 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16961 Causes a @code{Source_Reference} pragma to be generated that
16962 references the original input file, so that error messages will use
16963 the file name of this original file. The use of this switch implies
16964 that preprocessor lines are not to be removed from the file, so its
16965 use will force @option{^-b^/BLANK_LINES^} mode if
16966 @option{^-c^/COMMENTS^}
16967 has not been specified explicitly.
16968
16969 Note that if the file to be preprocessed contains multiple units, then
16970 it will be necessary to @code{gnatchop} the output file from
16971 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16972 in the preprocessed file, it will be respected by
16973 @code{gnatchop ^-r^/REFERENCE^}
16974 so that the final chopped files will correctly refer to the original
16975 input source file for @code{gnatprep}.
16976
16977 @item ^-s^/SYMBOLS^
16978 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16979 Causes a sorted list of symbol names and values to be
16980 listed on the standard output file.
16981
16982 @item ^-u^/UNDEFINED^
16983 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16984 Causes undefined symbols to be treated as having the value FALSE in the context
16985 of a preprocessor test. In the absence of this option, an undefined symbol in
16986 a @code{#if} or @code{#elsif} test will be treated as an error.
16987
16988 @end table
16989
16990 @ifclear vms
16991 @noindent
16992 Note: if neither @option{-b} nor @option{-c} is present,
16993 then preprocessor lines and
16994 deleted lines are completely removed from the output, unless -r is
16995 specified, in which case -b is assumed.
16996 @end ifclear
16997
16998 @node Form of Definitions File
16999 @section Form of Definitions File
17000
17001 @noindent
17002 The definitions file contains lines of the form
17003
17004 @smallexample
17005 symbol := value
17006 @end smallexample
17007
17008 @noindent
17009 where symbol is a preprocessing symbol, and value is one of the following:
17010
17011 @itemize @bullet
17012 @item
17013 Empty, corresponding to a null substitution
17014 @item
17015 A string literal using normal Ada syntax
17016 @item
17017 Any sequence of characters from the set
17018 (letters, digits, period, underline).
17019 @end itemize
17020
17021 @noindent
17022 Comment lines may also appear in the definitions file, starting with
17023 the usual @code{--},
17024 and comments may be added to the definitions lines.
17025
17026 @node Form of Input Text for gnatprep
17027 @section Form of Input Text for @code{gnatprep}
17028
17029 @noindent
17030 The input text may contain preprocessor conditional inclusion lines,
17031 as well as general symbol substitution sequences.
17032
17033 The preprocessor conditional inclusion commands have the form
17034
17035 @smallexample
17036 @group
17037 @cartouche
17038 #if @i{expression} @r{[}then@r{]}
17039 lines
17040 #elsif @i{expression} @r{[}then@r{]}
17041 lines
17042 #elsif @i{expression} @r{[}then@r{]}
17043 lines
17044 @dots{}
17045 #else
17046 lines
17047 #end if;
17048 @end cartouche
17049 @end group
17050 @end smallexample
17051
17052 @noindent
17053 In this example, @i{expression} is defined by the following grammar:
17054 @smallexample
17055 @i{expression} ::= <symbol>
17056 @i{expression} ::= <symbol> = "<value>"
17057 @i{expression} ::= <symbol> = <symbol>
17058 @i{expression} ::= <symbol> = <integer>
17059 @i{expression} ::= <symbol> > <integer>
17060 @i{expression} ::= <symbol> >= <integer>
17061 @i{expression} ::= <symbol> < <integer>
17062 @i{expression} ::= <symbol> <= <integer>
17063 @i{expression} ::= <symbol> 'Defined
17064 @i{expression} ::= not @i{expression}
17065 @i{expression} ::= @i{expression} and @i{expression}
17066 @i{expression} ::= @i{expression} or @i{expression}
17067 @i{expression} ::= @i{expression} and then @i{expression}
17068 @i{expression} ::= @i{expression} or else @i{expression}
17069 @i{expression} ::= ( @i{expression} )
17070 @end smallexample
17071
17072 The following restriction exists: it is not allowed to have "and" or "or"
17073 following "not" in the same expression without parentheses. For example, this
17074 is not allowed:
17075
17076 @smallexample
17077 not X or Y
17078 @end smallexample
17079
17080 This should be one of the following:
17081
17082 @smallexample
17083 (not X) or Y
17084 not (X or Y)
17085 @end smallexample
17086
17087 @noindent
17088 For the first test (@i{expression} ::= <symbol>) the symbol must have
17089 either the value true or false, that is to say the right-hand of the
17090 symbol definition must be one of the (case-insensitive) literals
17091 @code{True} or @code{False}. If the value is true, then the
17092 corresponding lines are included, and if the value is false, they are
17093 excluded.
17094
17095 When comparing a symbol to an integer, the integer is any non negative
17096 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
17097 2#11#. The symbol value must also be a non negative integer. Integer values
17098 in the range 0 .. 2**31-1 are supported.
17099
17100 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
17101 the symbol has been defined in the definition file or by a @option{-D}
17102 switch on the command line. Otherwise, the test is false.
17103
17104 The equality tests are case insensitive, as are all the preprocessor lines.
17105
17106 If the symbol referenced is not defined in the symbol definitions file,
17107 then the effect depends on whether or not switch @option{-u}
17108 is specified. If so, then the symbol is treated as if it had the value
17109 false and the test fails. If this switch is not specified, then
17110 it is an error to reference an undefined symbol. It is also an error to
17111 reference a symbol that is defined with a value other than @code{True}
17112 or @code{False}.
17113
17114 The use of the @code{not} operator inverts the sense of this logical test.
17115 The @code{not} operator cannot be combined with the @code{or} or @code{and}
17116 operators, without parentheses. For example, "if not X or Y then" is not
17117 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
17118
17119 The @code{then} keyword is optional as shown
17120
17121 The @code{#} must be the first non-blank character on a line, but
17122 otherwise the format is free form. Spaces or tabs may appear between
17123 the @code{#} and the keyword. The keywords and the symbols are case
17124 insensitive as in normal Ada code. Comments may be used on a
17125 preprocessor line, but other than that, no other tokens may appear on a
17126 preprocessor line. Any number of @code{elsif} clauses can be present,
17127 including none at all. The @code{else} is optional, as in Ada.
17128
17129 The @code{#} marking the start of a preprocessor line must be the first
17130 non-blank character on the line, i.e., it must be preceded only by
17131 spaces or horizontal tabs.
17132
17133 Symbol substitution outside of preprocessor lines is obtained by using
17134 the sequence
17135
17136 @smallexample
17137 $symbol
17138 @end smallexample
17139
17140 @noindent
17141 anywhere within a source line, except in a comment or within a
17142 string literal. The identifier
17143 following the @code{$} must match one of the symbols defined in the symbol
17144 definition file, and the result is to substitute the value of the
17145 symbol in place of @code{$symbol} in the output file.
17146
17147 Note that although the substitution of strings within a string literal
17148 is not possible, it is possible to have a symbol whose defined value is
17149 a string literal. So instead of setting XYZ to @code{hello} and writing:
17150
17151 @smallexample
17152 Header : String := "$XYZ";
17153 @end smallexample
17154
17155 @noindent
17156 you should set XYZ to @code{"hello"} and write:
17157
17158 @smallexample
17159 Header : String := $XYZ;
17160 @end smallexample
17161
17162 @noindent
17163 and then the substitution will occur as desired.
17164
17165 @node The GNAT Library Browser gnatls
17166 @chapter The GNAT Library Browser @code{gnatls}
17167 @findex gnatls
17168 @cindex Library browser
17169
17170 @noindent
17171 @code{gnatls} is a tool that outputs information about compiled
17172 units. It gives the relationship between objects, unit names and source
17173 files. It can also be used to check the source dependencies of a unit
17174 as well as various characteristics.
17175
17176 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
17177 driver (see @ref{The GNAT Driver and Project Files}).
17178
17179 @menu
17180 * Running gnatls::
17181 * Switches for gnatls::
17182 * Examples of gnatls Usage::
17183 @end menu
17184
17185 @node Running gnatls
17186 @section Running @code{gnatls}
17187
17188 @noindent
17189 The @code{gnatls} command has the form
17190
17191 @smallexample
17192 $ gnatls switches @var{object_or_ali_file}
17193 @end smallexample
17194
17195 @noindent
17196 The main argument is the list of object or @file{ali} files
17197 (@pxref{The Ada Library Information Files})
17198 for which information is requested.
17199
17200 In normal mode, without additional option, @code{gnatls} produces a
17201 four-column listing. Each line represents information for a specific
17202 object. The first column gives the full path of the object, the second
17203 column gives the name of the principal unit in this object, the third
17204 column gives the status of the source and the fourth column gives the
17205 full path of the source representing this unit.
17206 Here is a simple example of use:
17207
17208 @smallexample
17209 $ gnatls *.o
17210 ^./^[]^demo1.o demo1 DIF demo1.adb
17211 ^./^[]^demo2.o demo2 OK demo2.adb
17212 ^./^[]^hello.o h1 OK hello.adb
17213 ^./^[]^instr-child.o instr.child MOK instr-child.adb
17214 ^./^[]^instr.o instr OK instr.adb
17215 ^./^[]^tef.o tef DIF tef.adb
17216 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
17217 ^./^[]^tgef.o tgef DIF tgef.adb
17218 @end smallexample
17219
17220 @noindent
17221 The first line can be interpreted as follows: the main unit which is
17222 contained in
17223 object file @file{demo1.o} is demo1, whose main source is in
17224 @file{demo1.adb}. Furthermore, the version of the source used for the
17225 compilation of demo1 has been modified (DIF). Each source file has a status
17226 qualifier which can be:
17227
17228 @table @code
17229 @item OK (unchanged)
17230 The version of the source file used for the compilation of the
17231 specified unit corresponds exactly to the actual source file.
17232
17233 @item MOK (slightly modified)
17234 The version of the source file used for the compilation of the
17235 specified unit differs from the actual source file but not enough to
17236 require recompilation. If you use gnatmake with the qualifier
17237 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
17238 MOK will not be recompiled.
17239
17240 @item DIF (modified)
17241 No version of the source found on the path corresponds to the source
17242 used to build this object.
17243
17244 @item ??? (file not found)
17245 No source file was found for this unit.
17246
17247 @item HID (hidden, unchanged version not first on PATH)
17248 The version of the source that corresponds exactly to the source used
17249 for compilation has been found on the path but it is hidden by another
17250 version of the same source that has been modified.
17251
17252 @end table
17253
17254 @node Switches for gnatls
17255 @section Switches for @code{gnatls}
17256
17257 @noindent
17258 @code{gnatls} recognizes the following switches:
17259
17260 @table @option
17261 @c !sort!
17262 @cindex @option{--version} @command{gnatls}
17263 Display Copyright and version, then exit disregarding all other options.
17264
17265 @item --help
17266 @cindex @option{--help} @command{gnatls}
17267 If @option{--version} was not used, display usage, then exit disregarding
17268 all other options.
17269
17270 @item ^-a^/ALL_UNITS^
17271 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
17272 Consider all units, including those of the predefined Ada library.
17273 Especially useful with @option{^-d^/DEPENDENCIES^}.
17274
17275 @item ^-d^/DEPENDENCIES^
17276 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
17277 List sources from which specified units depend on.
17278
17279 @item ^-h^/OUTPUT=OPTIONS^
17280 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
17281 Output the list of options.
17282
17283 @item ^-o^/OUTPUT=OBJECTS^
17284 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
17285 Only output information about object files.
17286
17287 @item ^-s^/OUTPUT=SOURCES^
17288 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
17289 Only output information about source files.
17290
17291 @item ^-u^/OUTPUT=UNITS^
17292 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
17293 Only output information about compilation units.
17294
17295 @item ^-files^/FILES^=@var{file}
17296 @cindex @option{^-files^/FILES^} (@code{gnatls})
17297 Take as arguments the files listed in text file @var{file}.
17298 Text file @var{file} may contain empty lines that are ignored.
17299 Each nonempty line should contain the name of an existing file.
17300 Several such switches may be specified simultaneously.
17301
17302 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17303 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
17304 @itemx ^-I^/SEARCH=^@var{dir}
17305 @itemx ^-I-^/NOCURRENT_DIRECTORY^
17306 @itemx -nostdinc
17307 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
17308 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
17309 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
17310 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
17311 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
17312 flags (@pxref{Switches for gnatmake}).
17313
17314 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^@var{dir}
17315 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (@code{gnatls})
17316 Add @var{dir} at the beginning of the project search dir.
17317
17318 @item --RTS=@var{rts-path}
17319 @cindex @option{--RTS} (@code{gnatls})
17320 Specifies the default location of the runtime library. Same meaning as the
17321 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
17322
17323 @item ^-v^/OUTPUT=VERBOSE^
17324 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
17325 Verbose mode. Output the complete source, object and project paths. Do not use
17326 the default column layout but instead use long format giving as much as
17327 information possible on each requested units, including special
17328 characteristics such as:
17329
17330 @table @code
17331 @item Preelaborable
17332 The unit is preelaborable in the Ada sense.
17333
17334 @item No_Elab_Code
17335 No elaboration code has been produced by the compiler for this unit.
17336
17337 @item Pure
17338 The unit is pure in the Ada sense.
17339
17340 @item Elaborate_Body
17341 The unit contains a pragma Elaborate_Body.
17342
17343 @item Remote_Types
17344 The unit contains a pragma Remote_Types.
17345
17346 @item Shared_Passive
17347 The unit contains a pragma Shared_Passive.
17348
17349 @item Predefined
17350 This unit is part of the predefined environment and cannot be modified
17351 by the user.
17352
17353 @item Remote_Call_Interface
17354 The unit contains a pragma Remote_Call_Interface.
17355
17356 @end table
17357
17358 @end table
17359
17360 @node Examples of gnatls Usage
17361 @section Example of @code{gnatls} Usage
17362 @ifclear vms
17363
17364 @noindent
17365 Example of using the verbose switch. Note how the source and
17366 object paths are affected by the -I switch.
17367
17368 @smallexample
17369 $ gnatls -v -I.. demo1.o
17370
17371 GNATLS 5.03w (20041123-34)
17372 Copyright 1997-2004 Free Software Foundation, Inc.
17373
17374 Source Search Path:
17375 <Current_Directory>
17376 ../
17377 /home/comar/local/adainclude/
17378
17379 Object Search Path:
17380 <Current_Directory>
17381 ../
17382 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17383
17384 Project Search Path:
17385 <Current_Directory>
17386 /home/comar/local/lib/gnat/
17387
17388 ./demo1.o
17389 Unit =>
17390 Name => demo1
17391 Kind => subprogram body
17392 Flags => No_Elab_Code
17393 Source => demo1.adb modified
17394 @end smallexample
17395
17396 @noindent
17397 The following is an example of use of the dependency list.
17398 Note the use of the -s switch
17399 which gives a straight list of source files. This can be useful for
17400 building specialized scripts.
17401
17402 @smallexample
17403 $ gnatls -d demo2.o
17404 ./demo2.o demo2 OK demo2.adb
17405 OK gen_list.ads
17406 OK gen_list.adb
17407 OK instr.ads
17408 OK instr-child.ads
17409
17410 $ gnatls -d -s -a demo1.o
17411 demo1.adb
17412 /home/comar/local/adainclude/ada.ads
17413 /home/comar/local/adainclude/a-finali.ads
17414 /home/comar/local/adainclude/a-filico.ads
17415 /home/comar/local/adainclude/a-stream.ads
17416 /home/comar/local/adainclude/a-tags.ads
17417 gen_list.ads
17418 gen_list.adb
17419 /home/comar/local/adainclude/gnat.ads
17420 /home/comar/local/adainclude/g-io.ads
17421 instr.ads
17422 /home/comar/local/adainclude/system.ads
17423 /home/comar/local/adainclude/s-exctab.ads
17424 /home/comar/local/adainclude/s-finimp.ads
17425 /home/comar/local/adainclude/s-finroo.ads
17426 /home/comar/local/adainclude/s-secsta.ads
17427 /home/comar/local/adainclude/s-stalib.ads
17428 /home/comar/local/adainclude/s-stoele.ads
17429 /home/comar/local/adainclude/s-stratt.ads
17430 /home/comar/local/adainclude/s-tasoli.ads
17431 /home/comar/local/adainclude/s-unstyp.ads
17432 /home/comar/local/adainclude/unchconv.ads
17433 @end smallexample
17434 @end ifclear
17435
17436 @ifset vms
17437 @smallexample
17438 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
17439
17440 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
17441 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
17442 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
17443 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
17444 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
17445 demo1.adb
17446 gen_list.ads
17447 gen_list.adb
17448 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
17449 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
17450 instr.ads
17451 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
17452 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
17453 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
17454 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
17455 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
17456 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
17457 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
17458 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
17459 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
17460 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
17461 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
17462 @end smallexample
17463 @end ifset
17464
17465 @node Cleaning Up with gnatclean
17466 @chapter Cleaning Up with @code{gnatclean}
17467 @findex gnatclean
17468 @cindex Cleaning tool
17469
17470 @noindent
17471 @code{gnatclean} is a tool that allows the deletion of files produced by the
17472 compiler, binder and linker, including ALI files, object files, tree files,
17473 expanded source files, library files, interface copy source files, binder
17474 generated files and executable files.
17475
17476 @menu
17477 * Running gnatclean::
17478 * Switches for gnatclean::
17479 @c * Examples of gnatclean Usage::
17480 @end menu
17481
17482 @node Running gnatclean
17483 @section Running @code{gnatclean}
17484
17485 @noindent
17486 The @code{gnatclean} command has the form:
17487
17488 @smallexample
17489 $ gnatclean switches @var{names}
17490 @end smallexample
17491
17492 @noindent
17493 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
17494 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
17495 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
17496
17497 @noindent
17498 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17499 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
17500 the linker. In informative-only mode, specified by switch
17501 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
17502 normal mode is listed, but no file is actually deleted.
17503
17504 @node Switches for gnatclean
17505 @section Switches for @code{gnatclean}
17506
17507 @noindent
17508 @code{gnatclean} recognizes the following switches:
17509
17510 @table @option
17511 @c !sort!
17512 @cindex @option{--version} @command{gnatclean}
17513 Display Copyright and version, then exit disregarding all other options.
17514
17515 @item --help
17516 @cindex @option{--help} @command{gnatclean}
17517 If @option{--version} was not used, display usage, then exit disregarding
17518 all other options.
17519
17520 @item ^--subdirs^/SUBDIRS^=subdir
17521 Actual object directory of each project file is the subdirectory subdir of the
17522 object directory specified or defaulted in the project file.
17523
17524 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
17525 By default, shared library projects are not allowed to import static library
17526 projects. When this switch is used on the command line, this restriction is
17527 relaxed.
17528
17529 @item ^-c^/COMPILER_FILES_ONLY^
17530 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
17531 Only attempt to delete the files produced by the compiler, not those produced
17532 by the binder or the linker. The files that are not to be deleted are library
17533 files, interface copy files, binder generated files and executable files.
17534
17535 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
17536 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17537 Indicate that ALI and object files should normally be found in directory
17538 @var{dir}.
17539
17540 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17541 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17542 When using project files, if some errors or warnings are detected during
17543 parsing and verbose mode is not in effect (no use of switch
17544 ^-v^/VERBOSE^), then error lines start with the full path name of the project
17545 file, rather than its simple file name.
17546
17547 @item ^-h^/HELP^
17548 @cindex @option{^-h^/HELP^} (@code{gnatclean})
17549 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17550
17551 @item ^-n^/NODELETE^
17552 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17553 Informative-only mode. Do not delete any files. Output the list of the files
17554 that would have been deleted if this switch was not specified.
17555
17556 @item ^-P^/PROJECT_FILE=^@var{project}
17557 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17558 Use project file @var{project}. Only one such switch can be used.
17559 When cleaning a project file, the files produced by the compilation of the
17560 immediate sources or inherited sources of the project files are to be
17561 deleted. This is not depending on the presence or not of executable names
17562 on the command line.
17563
17564 @item ^-q^/QUIET^
17565 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
17566 Quiet output. If there are no errors, do not output anything, except in
17567 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17568 (switch ^-n^/NODELETE^).
17569
17570 @item ^-r^/RECURSIVE^
17571 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17572 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17573 clean all imported and extended project files, recursively. If this switch
17574 is not specified, only the files related to the main project file are to be
17575 deleted. This switch has no effect if no project file is specified.
17576
17577 @item ^-v^/VERBOSE^
17578 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17579 Verbose mode.
17580
17581 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17582 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17583 Indicates the verbosity of the parsing of GNAT project files.
17584 @xref{Switches Related to Project Files}.
17585
17586 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17587 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17588 Indicates that external variable @var{name} has the value @var{value}.
17589 The Project Manager will use this value for occurrences of
17590 @code{external(name)} when parsing the project file.
17591 @xref{Switches Related to Project Files}.
17592
17593 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17594 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17595 When searching for ALI and object files, look in directory
17596 @var{dir}.
17597
17598 @item ^-I^/SEARCH=^@var{dir}
17599 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17600 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17601
17602 @item ^-I-^/NOCURRENT_DIRECTORY^
17603 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
17604 @cindex Source files, suppressing search
17605 Do not look for ALI or object files in the directory
17606 where @code{gnatclean} was invoked.
17607
17608 @end table
17609
17610 @c @node Examples of gnatclean Usage
17611 @c @section Examples of @code{gnatclean} Usage
17612
17613 @ifclear vms
17614 @node GNAT and Libraries
17615 @chapter GNAT and Libraries
17616 @cindex Library, building, installing, using
17617
17618 @noindent
17619 This chapter describes how to build and use libraries with GNAT, and also shows
17620 how to recompile the GNAT run-time library. You should be familiar with the
17621 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
17622 chapter.
17623
17624 @menu
17625 * Introduction to Libraries in GNAT::
17626 * General Ada Libraries::
17627 * Stand-alone Ada Libraries::
17628 * Rebuilding the GNAT Run-Time Library::
17629 @end menu
17630
17631 @node Introduction to Libraries in GNAT
17632 @section Introduction to Libraries in GNAT
17633
17634 @noindent
17635 A library is, conceptually, a collection of objects which does not have its
17636 own main thread of execution, but rather provides certain services to the
17637 applications that use it. A library can be either statically linked with the
17638 application, in which case its code is directly included in the application,
17639 or, on platforms that support it, be dynamically linked, in which case
17640 its code is shared by all applications making use of this library.
17641
17642 GNAT supports both types of libraries.
17643 In the static case, the compiled code can be provided in different ways. The
17644 simplest approach is to provide directly the set of objects resulting from
17645 compilation of the library source files. Alternatively, you can group the
17646 objects into an archive using whatever commands are provided by the operating
17647 system. For the latter case, the objects are grouped into a shared library.
17648
17649 In the GNAT environment, a library has three types of components:
17650 @itemize @bullet
17651 @item
17652 Source files.
17653 @item
17654 @file{ALI} files.
17655 @xref{The Ada Library Information Files}.
17656 @item
17657 Object files, an archive or a shared library.
17658 @end itemize
17659
17660 @noindent
17661 A GNAT library may expose all its source files, which is useful for
17662 documentation purposes. Alternatively, it may expose only the units needed by
17663 an external user to make use of the library. That is to say, the specs
17664 reflecting the library services along with all the units needed to compile
17665 those specs, which can include generic bodies or any body implementing an
17666 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17667 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17668
17669 All compilation units comprising an application, including those in a library,
17670 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17671 computes the elaboration order from the @file{ALI} files and this is why they
17672 constitute a mandatory part of GNAT libraries.
17673 @emph{Stand-alone libraries} are the exception to this rule because a specific
17674 library elaboration routine is produced independently of the application(s)
17675 using the library.
17676
17677 @node General Ada Libraries
17678 @section General Ada Libraries
17679
17680 @menu
17681 * Building a library::
17682 * Installing a library::
17683 * Using a library::
17684 @end menu
17685
17686 @node Building a library
17687 @subsection Building a library
17688
17689 @noindent
17690 The easiest way to build a library is to use the Project Manager,
17691 which supports a special type of project called a @emph{Library Project}
17692 (@pxref{Library Projects}).
17693
17694 A project is considered a library project, when two project-level attributes
17695 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17696 control different aspects of library configuration, additional optional
17697 project-level attributes can be specified:
17698 @table @code
17699 @item Library_Kind
17700 This attribute controls whether the library is to be static or dynamic
17701
17702 @item Library_Version
17703 This attribute specifies the library version; this value is used
17704 during dynamic linking of shared libraries to determine if the currently
17705 installed versions of the binaries are compatible.
17706
17707 @item Library_Options
17708 @item Library_GCC
17709 These attributes specify additional low-level options to be used during
17710 library generation, and redefine the actual application used to generate
17711 library.
17712 @end table
17713
17714 @noindent
17715 The GNAT Project Manager takes full care of the library maintenance task,
17716 including recompilation of the source files for which objects do not exist
17717 or are not up to date, assembly of the library archive, and installation of
17718 the library (i.e., copying associated source, object and @file{ALI} files
17719 to the specified location).
17720
17721 Here is a simple library project file:
17722 @smallexample @c ada
17723 project My_Lib is
17724 for Source_Dirs use ("src1", "src2");
17725 for Object_Dir use "obj";
17726 for Library_Name use "mylib";
17727 for Library_Dir use "lib";
17728 for Library_Kind use "dynamic";
17729 end My_lib;
17730 @end smallexample
17731
17732 @noindent
17733 and the compilation command to build and install the library:
17734
17735 @smallexample @c ada
17736 $ gnatmake -Pmy_lib
17737 @end smallexample
17738
17739 @noindent
17740 It is not entirely trivial to perform manually all the steps required to
17741 produce a library. We recommend that you use the GNAT Project Manager
17742 for this task. In special cases where this is not desired, the necessary
17743 steps are discussed below.
17744
17745 There are various possibilities for compiling the units that make up the
17746 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17747 with a conventional script. For simple libraries, it is also possible to create
17748 a dummy main program which depends upon all the packages that comprise the
17749 interface of the library. This dummy main program can then be given to
17750 @command{gnatmake}, which will ensure that all necessary objects are built.
17751
17752 After this task is accomplished, you should follow the standard procedure
17753 of the underlying operating system to produce the static or shared library.
17754
17755 Here is an example of such a dummy program:
17756 @smallexample @c ada
17757 @group
17758 with My_Lib.Service1;
17759 with My_Lib.Service2;
17760 with My_Lib.Service3;
17761 procedure My_Lib_Dummy is
17762 begin
17763 null;
17764 end;
17765 @end group
17766 @end smallexample
17767
17768 @noindent
17769 Here are the generic commands that will build an archive or a shared library.
17770
17771 @smallexample
17772 # compiling the library
17773 $ gnatmake -c my_lib_dummy.adb
17774
17775 # we don't need the dummy object itself
17776 $ rm my_lib_dummy.o my_lib_dummy.ali
17777
17778 # create an archive with the remaining objects
17779 $ ar rc libmy_lib.a *.o
17780 # some systems may require "ranlib" to be run as well
17781
17782 # or create a shared library
17783 $ gcc -shared -o libmy_lib.so *.o
17784 # some systems may require the code to have been compiled with -fPIC
17785
17786 # remove the object files that are now in the library
17787 $ rm *.o
17788
17789 # Make the ALI files read-only so that gnatmake will not try to
17790 # regenerate the objects that are in the library
17791 $ chmod -w *.ali
17792 @end smallexample
17793
17794 @noindent
17795 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
17796 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
17797 be accessed by the directive @option{-l@var{xxx}} at link time.
17798
17799 @node Installing a library
17800 @subsection Installing a library
17801 @cindex @code{ADA_PROJECT_PATH}
17802 @cindex @code{GPR_PROJECT_PATH}
17803
17804 @noindent
17805 If you use project files, library installation is part of the library build
17806 process (@pxref{Installing a library with project files}).
17807
17808 When project files are not an option, it is also possible, but not recommended,
17809 to install the library so that the sources needed to use the library are on the
17810 Ada source path and the ALI files & libraries be on the Ada Object path (see
17811 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17812 administrator can place general-purpose libraries in the default compiler
17813 paths, by specifying the libraries' location in the configuration files
17814 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17815 must be located in the GNAT installation tree at the same place as the gcc spec
17816 file. The location of the gcc spec file can be determined as follows:
17817 @smallexample
17818 $ gcc -v
17819 @end smallexample
17820
17821 @noindent
17822 The configuration files mentioned above have a simple format: each line
17823 must contain one unique directory name.
17824 Those names are added to the corresponding path
17825 in their order of appearance in the file. The names can be either absolute
17826 or relative; in the latter case, they are relative to where theses files
17827 are located.
17828
17829 The files @file{ada_source_path} and @file{ada_object_path} might not be
17830 present in a
17831 GNAT installation, in which case, GNAT will look for its run-time library in
17832 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17833 objects and @file{ALI} files). When the files exist, the compiler does not
17834 look in @file{adainclude} and @file{adalib}, and thus the
17835 @file{ada_source_path} file
17836 must contain the location for the GNAT run-time sources (which can simply
17837 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17838 contain the location for the GNAT run-time objects (which can simply
17839 be @file{adalib}).
17840
17841 You can also specify a new default path to the run-time library at compilation
17842 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17843 the run-time library you want your program to be compiled with. This switch is
17844 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17845 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17846
17847 It is possible to install a library before or after the standard GNAT
17848 library, by reordering the lines in the configuration files. In general, a
17849 library must be installed before the GNAT library if it redefines
17850 any part of it.
17851
17852 @node Using a library
17853 @subsection Using a library
17854
17855 @noindent Once again, the project facility greatly simplifies the use of
17856 libraries. In this context, using a library is just a matter of adding a
17857 @code{with} clause in the user project. For instance, to make use of the
17858 library @code{My_Lib} shown in examples in earlier sections, you can
17859 write:
17860
17861 @smallexample @c projectfile
17862 with "my_lib";
17863 project My_Proj is
17864 @dots{}
17865 end My_Proj;
17866 @end smallexample
17867
17868 Even if you have a third-party, non-Ada library, you can still use GNAT's
17869 Project Manager facility to provide a wrapper for it. For example, the
17870 following project, when @code{with}ed by your main project, will link with the
17871 third-party library @file{liba.a}:
17872
17873 @smallexample @c projectfile
17874 @group
17875 project Liba is
17876 for Externally_Built use "true";
17877 for Source_Files use ();
17878 for Library_Dir use "lib";
17879 for Library_Name use "a";
17880 for Library_Kind use "static";
17881 end Liba;
17882 @end group
17883 @end smallexample
17884 This is an alternative to the use of @code{pragma Linker_Options}. It is
17885 especially interesting in the context of systems with several interdependent
17886 static libraries where finding a proper linker order is not easy and best be
17887 left to the tools having visibility over project dependence information.
17888
17889 @noindent
17890 In order to use an Ada library manually, you need to make sure that this
17891 library is on both your source and object path
17892 (see @ref{Search Paths and the Run-Time Library (RTL)}
17893 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17894 in an archive or a shared library, you need to specify the desired
17895 library at link time.
17896
17897 For example, you can use the library @file{mylib} installed in
17898 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17899
17900 @smallexample
17901 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17902 -largs -lmy_lib
17903 @end smallexample
17904
17905 @noindent
17906 This can be expressed more simply:
17907 @smallexample
17908 $ gnatmake my_appl
17909 @end smallexample
17910 @noindent
17911 when the following conditions are met:
17912 @itemize @bullet
17913 @item
17914 @file{/dir/my_lib_src} has been added by the user to the environment
17915 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
17916 @file{ada_source_path}
17917 @item
17918 @file{/dir/my_lib_obj} has been added by the user to the environment
17919 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
17920 @file{ada_object_path}
17921 @item
17922 a pragma @code{Linker_Options} has been added to one of the sources.
17923 For example:
17924
17925 @smallexample @c ada
17926 pragma Linker_Options ("-lmy_lib");
17927 @end smallexample
17928 @end itemize
17929
17930 @node Stand-alone Ada Libraries
17931 @section Stand-alone Ada Libraries
17932 @cindex Stand-alone library, building, using
17933
17934 @menu
17935 * Introduction to Stand-alone Libraries::
17936 * Building a Stand-alone Library::
17937 * Creating a Stand-alone Library to be used in a non-Ada context::
17938 * Restrictions in Stand-alone Libraries::
17939 @end menu
17940
17941 @node Introduction to Stand-alone Libraries
17942 @subsection Introduction to Stand-alone Libraries
17943
17944 @noindent
17945 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17946 necessary code to
17947 elaborate the Ada units that are included in the library. In contrast with
17948 an ordinary library, which consists of all sources, objects and @file{ALI}
17949 files of the
17950 library, a SAL may specify a restricted subset of compilation units
17951 to serve as a library interface. In this case, the fully
17952 self-sufficient set of files will normally consist of an objects
17953 archive, the sources of interface units' specs, and the @file{ALI}
17954 files of interface units.
17955 If an interface spec contains a generic unit or an inlined subprogram,
17956 the body's
17957 source must also be provided; if the units that must be provided in the source
17958 form depend on other units, the source and @file{ALI} files of those must
17959 also be provided.
17960
17961 The main purpose of a SAL is to minimize the recompilation overhead of client
17962 applications when a new version of the library is installed. Specifically,
17963 if the interface sources have not changed, client applications do not need to
17964 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17965 version, controlled by @code{Library_Version} attribute, is not changed,
17966 then the clients do not need to be relinked.
17967
17968 SALs also allow the library providers to minimize the amount of library source
17969 text exposed to the clients. Such ``information hiding'' might be useful or
17970 necessary for various reasons.
17971
17972 Stand-alone libraries are also well suited to be used in an executable whose
17973 main routine is not written in Ada.
17974
17975 @node Building a Stand-alone Library
17976 @subsection Building a Stand-alone Library
17977
17978 @noindent
17979 GNAT's Project facility provides a simple way of building and installing
17980 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17981 To be a Stand-alone Library Project, in addition to the two attributes
17982 that make a project a Library Project (@code{Library_Name} and
17983 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17984 @code{Library_Interface} must be defined. For example:
17985
17986 @smallexample @c projectfile
17987 @group
17988 for Library_Dir use "lib_dir";
17989 for Library_Name use "dummy";
17990 for Library_Interface use ("int1", "int1.child");
17991 @end group
17992 @end smallexample
17993
17994 @noindent
17995 Attribute @code{Library_Interface} has a non-empty string list value,
17996 each string in the list designating a unit contained in an immediate source
17997 of the project file.
17998
17999 When a Stand-alone Library is built, first the binder is invoked to build
18000 a package whose name depends on the library name
18001 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
18002 This binder-generated package includes initialization and
18003 finalization procedures whose
18004 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
18005 in the example
18006 above). The object corresponding to this package is included in the library.
18007
18008 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
18009 calling of these procedures if a static SAL is built, or if a shared SAL
18010 is built
18011 with the project-level attribute @code{Library_Auto_Init} set to
18012 @code{"false"}.
18013
18014 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
18015 (those that are listed in attribute @code{Library_Interface}) are copied to
18016 the Library Directory. As a consequence, only the Interface Units may be
18017 imported from Ada units outside of the library. If other units are imported,
18018 the binding phase will fail.
18019
18020 @noindent
18021 It is also possible to build an encapsulated library where not only
18022 the code to elaborate and finalize the library is embedded but also
18023 ensuring that the library is linked only against static
18024 libraries. So an encapsulated library only depends on system
18025 libraries, all other code, including the GNAT runtime, is embedded. To
18026 build an encapsulated library the attribute
18027 @code{Library_Standalone} must be set to @code{encapsulated}:
18028
18029 @smallexample @c projectfile
18030 @group
18031 for Library_Dir use "lib_dir";
18032 for Library_Name use "dummy";
18033 for Library_Kind use "dynamic";
18034 for Library_Interface use ("int1", "int1.child");
18035 for Library_Standalone use "encapsulated";
18036 @end group
18037 @end smallexample
18038
18039 @noindent
18040 The default value for this attribute is @code{standard} in which case
18041 a stand-alone library is built.
18042
18043 The attribute @code{Library_Src_Dir} may be specified for a
18044 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
18045 single string value. Its value must be the path (absolute or relative to the
18046 project directory) of an existing directory. This directory cannot be the
18047 object directory or one of the source directories, but it can be the same as
18048 the library directory. The sources of the Interface
18049 Units of the library that are needed by an Ada client of the library will be
18050 copied to the designated directory, called the Interface Copy directory.
18051 These sources include the specs of the Interface Units, but they may also
18052 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
18053 are used, or when there is a generic unit in the spec. Before the sources
18054 are copied to the Interface Copy directory, an attempt is made to delete all
18055 files in the Interface Copy directory.
18056
18057 Building stand-alone libraries by hand is somewhat tedious, but for those
18058 occasions when it is necessary here are the steps that you need to perform:
18059 @itemize @bullet
18060 @item
18061 Compile all library sources.
18062
18063 @item
18064 Invoke the binder with the switch @option{-n} (No Ada main program),
18065 with all the @file{ALI} files of the interfaces, and
18066 with the switch @option{-L} to give specific names to the @code{init}
18067 and @code{final} procedures. For example:
18068 @smallexample
18069 gnatbind -n int1.ali int2.ali -Lsal1
18070 @end smallexample
18071
18072 @item
18073 Compile the binder generated file:
18074 @smallexample
18075 gcc -c b~int2.adb
18076 @end smallexample
18077
18078 @item
18079 Link the dynamic library with all the necessary object files,
18080 indicating to the linker the names of the @code{init} (and possibly
18081 @code{final}) procedures for automatic initialization (and finalization).
18082 The built library should be placed in a directory different from
18083 the object directory.
18084
18085 @item
18086 Copy the @code{ALI} files of the interface to the library directory,
18087 add in this copy an indication that it is an interface to a SAL
18088 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
18089 with letter ``P'') and make the modified copy of the @file{ALI} file
18090 read-only.
18091 @end itemize
18092
18093 @noindent
18094 Using SALs is not different from using other libraries
18095 (see @ref{Using a library}).
18096
18097 @node Creating a Stand-alone Library to be used in a non-Ada context
18098 @subsection Creating a Stand-alone Library to be used in a non-Ada context
18099
18100 @noindent
18101 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
18102 a non-Ada context.
18103
18104 The only extra step required is to ensure that library interface subprograms
18105 are compatible with the main program, by means of @code{pragma Export}
18106 or @code{pragma Convention}.
18107
18108 Here is an example of simple library interface for use with C main program:
18109
18110 @smallexample @c ada
18111 package My_Package is
18112
18113 procedure Do_Something;
18114 pragma Export (C, Do_Something, "do_something");
18115
18116 procedure Do_Something_Else;
18117 pragma Export (C, Do_Something_Else, "do_something_else");
18118
18119 end My_Package;
18120 @end smallexample
18121
18122 @noindent
18123 On the foreign language side, you must provide a ``foreign'' view of the
18124 library interface; remember that it should contain elaboration routines in
18125 addition to interface subprograms.
18126
18127 The example below shows the content of @code{mylib_interface.h} (note
18128 that there is no rule for the naming of this file, any name can be used)
18129 @smallexample
18130 /* the library elaboration procedure */
18131 extern void mylibinit (void);
18132
18133 /* the library finalization procedure */
18134 extern void mylibfinal (void);
18135
18136 /* the interface exported by the library */
18137 extern void do_something (void);
18138 extern void do_something_else (void);
18139 @end smallexample
18140
18141 @noindent
18142 Libraries built as explained above can be used from any program, provided
18143 that the elaboration procedures (named @code{mylibinit} in the previous
18144 example) are called before the library services are used. Any number of
18145 libraries can be used simultaneously, as long as the elaboration
18146 procedure of each library is called.
18147
18148 Below is an example of a C program that uses the @code{mylib} library.
18149
18150 @smallexample
18151 #include "mylib_interface.h"
18152
18153 int
18154 main (void)
18155 @{
18156 /* First, elaborate the library before using it */
18157 mylibinit ();
18158
18159 /* Main program, using the library exported entities */
18160 do_something ();
18161 do_something_else ();
18162
18163 /* Library finalization at the end of the program */
18164 mylibfinal ();
18165 return 0;
18166 @}
18167 @end smallexample
18168
18169 @noindent
18170 Note that invoking any library finalization procedure generated by
18171 @code{gnatbind} shuts down the Ada run-time environment.
18172 Consequently, the
18173 finalization of all Ada libraries must be performed at the end of the program.
18174 No call to these libraries or to the Ada run-time library should be made
18175 after the finalization phase.
18176
18177 @node Restrictions in Stand-alone Libraries
18178 @subsection Restrictions in Stand-alone Libraries
18179
18180 @noindent
18181 The pragmas listed below should be used with caution inside libraries,
18182 as they can create incompatibilities with other Ada libraries:
18183 @itemize @bullet
18184 @item pragma @code{Locking_Policy}
18185 @item pragma @code{Partition_Elaboration_Policy}
18186 @item pragma @code{Queuing_Policy}
18187 @item pragma @code{Task_Dispatching_Policy}
18188 @item pragma @code{Unreserve_All_Interrupts}
18189 @end itemize
18190
18191 @noindent
18192 When using a library that contains such pragmas, the user must make sure
18193 that all libraries use the same pragmas with the same values. Otherwise,
18194 @code{Program_Error} will
18195 be raised during the elaboration of the conflicting
18196 libraries. The usage of these pragmas and its consequences for the user
18197 should therefore be well documented.
18198
18199 Similarly, the traceback in the exception occurrence mechanism should be
18200 enabled or disabled in a consistent manner across all libraries.
18201 Otherwise, Program_Error will be raised during the elaboration of the
18202 conflicting libraries.
18203
18204 If the @code{Version} or @code{Body_Version}
18205 attributes are used inside a library, then you need to
18206 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
18207 libraries, so that version identifiers can be properly computed.
18208 In practice these attributes are rarely used, so this is unlikely
18209 to be a consideration.
18210
18211 @node Rebuilding the GNAT Run-Time Library
18212 @section Rebuilding the GNAT Run-Time Library
18213 @cindex GNAT Run-Time Library, rebuilding
18214 @cindex Building the GNAT Run-Time Library
18215 @cindex Rebuilding the GNAT Run-Time Library
18216 @cindex Run-Time Library, rebuilding
18217
18218 @noindent
18219 It may be useful to recompile the GNAT library in various contexts, the
18220 most important one being the use of partition-wide configuration pragmas
18221 such as @code{Normalize_Scalars}. A special Makefile called
18222 @code{Makefile.adalib} is provided to that effect and can be found in
18223 the directory containing the GNAT library. The location of this
18224 directory depends on the way the GNAT environment has been installed and can
18225 be determined by means of the command:
18226
18227 @smallexample
18228 $ gnatls -v
18229 @end smallexample
18230
18231 @noindent
18232 The last entry in the object search path usually contains the
18233 gnat library. This Makefile contains its own documentation and in
18234 particular the set of instructions needed to rebuild a new library and
18235 to use it.
18236
18237 @node Using the GNU make Utility
18238 @chapter Using the GNU @code{make} Utility
18239 @findex make
18240
18241 @noindent
18242 This chapter offers some examples of makefiles that solve specific
18243 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
18244 make, make, GNU @code{make}}), nor does it try to replace the
18245 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
18246
18247 All the examples in this section are specific to the GNU version of
18248 make. Although @command{make} is a standard utility, and the basic language
18249 is the same, these examples use some advanced features found only in
18250 @code{GNU make}.
18251
18252 @menu
18253 * Using gnatmake in a Makefile::
18254 * Automatically Creating a List of Directories::
18255 * Generating the Command Line Switches::
18256 * Overcoming Command Line Length Limits::
18257 @end menu
18258
18259 @node Using gnatmake in a Makefile
18260 @section Using gnatmake in a Makefile
18261 @findex makefile
18262 @cindex GNU make
18263
18264 @noindent
18265 Complex project organizations can be handled in a very powerful way by
18266 using GNU make combined with gnatmake. For instance, here is a Makefile
18267 which allows you to build each subsystem of a big project into a separate
18268 shared library. Such a makefile allows you to significantly reduce the link
18269 time of very big applications while maintaining full coherence at
18270 each step of the build process.
18271
18272 The list of dependencies are handled automatically by
18273 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
18274 the appropriate directories.
18275
18276 Note that you should also read the example on how to automatically
18277 create the list of directories
18278 (@pxref{Automatically Creating a List of Directories})
18279 which might help you in case your project has a lot of subdirectories.
18280
18281 @smallexample
18282 @iftex
18283 @leftskip=0cm
18284 @font@heightrm=cmr8
18285 @heightrm
18286 @end iftex
18287 ## This Makefile is intended to be used with the following directory
18288 ## configuration:
18289 ## - The sources are split into a series of csc (computer software components)
18290 ## Each of these csc is put in its own directory.
18291 ## Their name are referenced by the directory names.
18292 ## They will be compiled into shared library (although this would also work
18293 ## with static libraries
18294 ## - The main program (and possibly other packages that do not belong to any
18295 ## csc is put in the top level directory (where the Makefile is).
18296 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
18297 ## \_ second_csc (sources) __ lib (will contain the library)
18298 ## \_ @dots{}
18299 ## Although this Makefile is build for shared library, it is easy to modify
18300 ## to build partial link objects instead (modify the lines with -shared and
18301 ## gnatlink below)
18302 ##
18303 ## With this makefile, you can change any file in the system or add any new
18304 ## file, and everything will be recompiled correctly (only the relevant shared
18305 ## objects will be recompiled, and the main program will be re-linked).
18306
18307 # The list of computer software component for your project. This might be
18308 # generated automatically.
18309 CSC_LIST=aa bb cc
18310
18311 # Name of the main program (no extension)
18312 MAIN=main
18313
18314 # If we need to build objects with -fPIC, uncomment the following line
18315 #NEED_FPIC=-fPIC
18316
18317 # The following variable should give the directory containing libgnat.so
18318 # You can get this directory through 'gnatls -v'. This is usually the last
18319 # directory in the Object_Path.
18320 GLIB=@dots{}
18321
18322 # The directories for the libraries
18323 # (This macro expands the list of CSC to the list of shared libraries, you
18324 # could simply use the expanded form:
18325 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
18326 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
18327
18328 $@{MAIN@}: objects $@{LIB_DIR@}
18329 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
18330 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
18331
18332 objects::
18333 # recompile the sources
18334 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
18335
18336 # Note: In a future version of GNAT, the following commands will be simplified
18337 # by a new tool, gnatmlib
18338 $@{LIB_DIR@}:
18339 mkdir -p $@{dir $@@ @}
18340 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
18341 cd $@{dir $@@ @} && cp -f ../*.ali .
18342
18343 # The dependencies for the modules
18344 # Note that we have to force the expansion of *.o, since in some cases
18345 # make won't be able to do it itself.
18346 aa/lib/libaa.so: $@{wildcard aa/*.o@}
18347 bb/lib/libbb.so: $@{wildcard bb/*.o@}
18348 cc/lib/libcc.so: $@{wildcard cc/*.o@}
18349
18350 # Make sure all of the shared libraries are in the path before starting the
18351 # program
18352 run::
18353 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
18354
18355 clean::
18356 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
18357 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
18358 $@{RM@} $@{CSC_LIST:%=%/*.o@}
18359 $@{RM@} *.o *.ali $@{MAIN@}
18360 @end smallexample
18361
18362 @node Automatically Creating a List of Directories
18363 @section Automatically Creating a List of Directories
18364
18365 @noindent
18366 In most makefiles, you will have to specify a list of directories, and
18367 store it in a variable. For small projects, it is often easier to
18368 specify each of them by hand, since you then have full control over what
18369 is the proper order for these directories, which ones should be
18370 included.
18371
18372 However, in larger projects, which might involve hundreds of
18373 subdirectories, it might be more convenient to generate this list
18374 automatically.
18375
18376 The example below presents two methods. The first one, although less
18377 general, gives you more control over the list. It involves wildcard
18378 characters, that are automatically expanded by @command{make}. Its
18379 shortcoming is that you need to explicitly specify some of the
18380 organization of your project, such as for instance the directory tree
18381 depth, whether some directories are found in a separate tree, @enddots{}
18382
18383 The second method is the most general one. It requires an external
18384 program, called @command{find}, which is standard on all Unix systems. All
18385 the directories found under a given root directory will be added to the
18386 list.
18387
18388 @smallexample
18389 @iftex
18390 @leftskip=0cm
18391 @font@heightrm=cmr8
18392 @heightrm
18393 @end iftex
18394 # The examples below are based on the following directory hierarchy:
18395 # All the directories can contain any number of files
18396 # ROOT_DIRECTORY -> a -> aa -> aaa
18397 # -> ab
18398 # -> ac
18399 # -> b -> ba -> baa
18400 # -> bb
18401 # -> bc
18402 # This Makefile creates a variable called DIRS, that can be reused any time
18403 # you need this list (see the other examples in this section)
18404
18405 # The root of your project's directory hierarchy
18406 ROOT_DIRECTORY=.
18407
18408 ####
18409 # First method: specify explicitly the list of directories
18410 # This allows you to specify any subset of all the directories you need.
18411 ####
18412
18413 DIRS := a/aa/ a/ab/ b/ba/
18414
18415 ####
18416 # Second method: use wildcards
18417 # Note that the argument(s) to wildcard below should end with a '/'.
18418 # Since wildcards also return file names, we have to filter them out
18419 # to avoid duplicate directory names.
18420 # We thus use make's @code{dir} and @code{sort} functions.
18421 # It sets DIRs to the following value (note that the directories aaa and baa
18422 # are not given, unless you change the arguments to wildcard).
18423 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
18424 ####
18425
18426 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
18427 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
18428
18429 ####
18430 # Third method: use an external program
18431 # This command is much faster if run on local disks, avoiding NFS slowdowns.
18432 # This is the most complete command: it sets DIRs to the following value:
18433 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
18434 ####
18435
18436 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
18437
18438 @end smallexample
18439
18440 @node Generating the Command Line Switches
18441 @section Generating the Command Line Switches
18442
18443 @noindent
18444 Once you have created the list of directories as explained in the
18445 previous section (@pxref{Automatically Creating a List of Directories}),
18446 you can easily generate the command line arguments to pass to gnatmake.
18447
18448 For the sake of completeness, this example assumes that the source path
18449 is not the same as the object path, and that you have two separate lists
18450 of directories.
18451
18452 @smallexample
18453 # see "Automatically creating a list of directories" to create
18454 # these variables
18455 SOURCE_DIRS=
18456 OBJECT_DIRS=
18457
18458 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
18459 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
18460
18461 all:
18462 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
18463 @end smallexample
18464
18465 @node Overcoming Command Line Length Limits
18466 @section Overcoming Command Line Length Limits
18467
18468 @noindent
18469 One problem that might be encountered on big projects is that many
18470 operating systems limit the length of the command line. It is thus hard to give
18471 gnatmake the list of source and object directories.
18472
18473 This example shows how you can set up environment variables, which will
18474 make @command{gnatmake} behave exactly as if the directories had been
18475 specified on the command line, but have a much higher length limit (or
18476 even none on most systems).
18477
18478 It assumes that you have created a list of directories in your Makefile,
18479 using one of the methods presented in
18480 @ref{Automatically Creating a List of Directories}.
18481 For the sake of completeness, we assume that the object
18482 path (where the ALI files are found) is different from the sources patch.
18483
18484 Note a small trick in the Makefile below: for efficiency reasons, we
18485 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
18486 expanded immediately by @code{make}. This way we overcome the standard
18487 make behavior which is to expand the variables only when they are
18488 actually used.
18489
18490 On Windows, if you are using the standard Windows command shell, you must
18491 replace colons with semicolons in the assignments to these variables.
18492
18493 @smallexample
18494 @iftex
18495 @leftskip=0cm
18496 @font@heightrm=cmr8
18497 @heightrm
18498 @end iftex
18499 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
18500 # This is the same thing as putting the -I arguments on the command line.
18501 # (the equivalent of using -aI on the command line would be to define
18502 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
18503 # You can of course have different values for these variables.
18504 #
18505 # Note also that we need to keep the previous values of these variables, since
18506 # they might have been set before running 'make' to specify where the GNAT
18507 # library is installed.
18508
18509 # see "Automatically creating a list of directories" to create these
18510 # variables
18511 SOURCE_DIRS=
18512 OBJECT_DIRS=
18513
18514 empty:=
18515 space:=$@{empty@} $@{empty@}
18516 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
18517 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
18518 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
18519 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
18520 export ADA_INCLUDE_PATH
18521 export ADA_OBJECTS_PATH
18522
18523 all:
18524 gnatmake main_unit
18525 @end smallexample
18526 @end ifclear
18527
18528 @node Memory Management Issues
18529 @chapter Memory Management Issues
18530
18531 @noindent
18532 This chapter describes some useful memory pools provided in the GNAT library
18533 and in particular the GNAT Debug Pool facility, which can be used to detect
18534 incorrect uses of access values (including ``dangling references'').
18535 @ifclear vms
18536 @ifclear FSFEDITION
18537 It also describes the @command{gnatmem} tool, which can be used to track down
18538 ``memory leaks''.
18539 @end ifclear
18540 @end ifclear
18541
18542 @menu
18543 * Some Useful Memory Pools::
18544 * The GNAT Debug Pool Facility::
18545 @ifclear vms
18546 @ifclear FSFEDITION
18547 * The gnatmem Tool::
18548 @end ifclear
18549 @end ifclear
18550 @end menu
18551
18552 @node Some Useful Memory Pools
18553 @section Some Useful Memory Pools
18554 @findex Memory Pool
18555 @cindex storage, pool
18556
18557 @noindent
18558 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18559 storage pool. Allocations use the standard system call @code{malloc} while
18560 deallocations use the standard system call @code{free}. No reclamation is
18561 performed when the pool goes out of scope. For performance reasons, the
18562 standard default Ada allocators/deallocators do not use any explicit storage
18563 pools but if they did, they could use this storage pool without any change in
18564 behavior. That is why this storage pool is used when the user
18565 manages to make the default implicit allocator explicit as in this example:
18566 @smallexample @c ada
18567 type T1 is access Something;
18568 -- no Storage pool is defined for T2
18569 type T2 is access Something_Else;
18570 for T2'Storage_Pool use T1'Storage_Pool;
18571 -- the above is equivalent to
18572 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18573 @end smallexample
18574
18575 @noindent
18576 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18577 pool. The allocation strategy is similar to @code{Pool_Local}'s
18578 except that the all
18579 storage allocated with this pool is reclaimed when the pool object goes out of
18580 scope. This pool provides a explicit mechanism similar to the implicit one
18581 provided by several Ada 83 compilers for allocations performed through a local
18582 access type and whose purpose was to reclaim memory when exiting the
18583 scope of a given local access. As an example, the following program does not
18584 leak memory even though it does not perform explicit deallocation:
18585
18586 @smallexample @c ada
18587 with System.Pool_Local;
18588 procedure Pooloc1 is
18589 procedure Internal is
18590 type A is access Integer;
18591 X : System.Pool_Local.Unbounded_Reclaim_Pool;
18592 for A'Storage_Pool use X;
18593 v : A;
18594 begin
18595 for I in 1 .. 50 loop
18596 v := new Integer;
18597 end loop;
18598 end Internal;
18599 begin
18600 for I in 1 .. 100 loop
18601 Internal;
18602 end loop;
18603 end Pooloc1;
18604 @end smallexample
18605
18606 @noindent
18607 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
18608 @code{Storage_Size} is specified for an access type.
18609 The whole storage for the pool is
18610 allocated at once, usually on the stack at the point where the access type is
18611 elaborated. It is automatically reclaimed when exiting the scope where the
18612 access type is defined. This package is not intended to be used directly by the
18613 user and it is implicitly used for each such declaration:
18614
18615 @smallexample @c ada
18616 type T1 is access Something;
18617 for T1'Storage_Size use 10_000;
18618 @end smallexample
18619
18620 @node The GNAT Debug Pool Facility
18621 @section The GNAT Debug Pool Facility
18622 @findex Debug Pool
18623 @cindex storage, pool, memory corruption
18624
18625 @noindent
18626 The use of unchecked deallocation and unchecked conversion can easily
18627 lead to incorrect memory references. The problems generated by such
18628 references are usually difficult to tackle because the symptoms can be
18629 very remote from the origin of the problem. In such cases, it is
18630 very helpful to detect the problem as early as possible. This is the
18631 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
18632
18633 In order to use the GNAT specific debugging pool, the user must
18634 associate a debug pool object with each of the access types that may be
18635 related to suspected memory problems. See Ada Reference Manual 13.11.
18636 @smallexample @c ada
18637 type Ptr is access Some_Type;
18638 Pool : GNAT.Debug_Pools.Debug_Pool;
18639 for Ptr'Storage_Pool use Pool;
18640 @end smallexample
18641
18642 @noindent
18643 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18644 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18645 allow the user to redefine allocation and deallocation strategies. They
18646 also provide a checkpoint for each dereference, through the use of
18647 the primitive operation @code{Dereference} which is implicitly called at
18648 each dereference of an access value.
18649
18650 Once an access type has been associated with a debug pool, operations on
18651 values of the type may raise four distinct exceptions,
18652 which correspond to four potential kinds of memory corruption:
18653 @itemize @bullet
18654 @item
18655 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18656 @item
18657 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18658 @item
18659 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18660 @item
18661 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18662 @end itemize
18663
18664 @noindent
18665 For types associated with a Debug_Pool, dynamic allocation is performed using
18666 the standard GNAT allocation routine. References to all allocated chunks of
18667 memory are kept in an internal dictionary. Several deallocation strategies are
18668 provided, whereupon the user can choose to release the memory to the system,
18669 keep it allocated for further invalid access checks, or fill it with an easily
18670 recognizable pattern for debug sessions. The memory pattern is the old IBM
18671 hexadecimal convention: @code{16#DEADBEEF#}.
18672
18673 See the documentation in the file g-debpoo.ads for more information on the
18674 various strategies.
18675
18676 Upon each dereference, a check is made that the access value denotes a
18677 properly allocated memory location. Here is a complete example of use of
18678 @code{Debug_Pools}, that includes typical instances of memory corruption:
18679 @smallexample @c ada
18680 @iftex
18681 @leftskip=0cm
18682 @end iftex
18683 with Gnat.Io; use Gnat.Io;
18684 with Unchecked_Deallocation;
18685 with Unchecked_Conversion;
18686 with GNAT.Debug_Pools;
18687 with System.Storage_Elements;
18688 with Ada.Exceptions; use Ada.Exceptions;
18689 procedure Debug_Pool_Test is
18690
18691 type T is access Integer;
18692 type U is access all T;
18693
18694 P : GNAT.Debug_Pools.Debug_Pool;
18695 for T'Storage_Pool use P;
18696
18697 procedure Free is new Unchecked_Deallocation (Integer, T);
18698 function UC is new Unchecked_Conversion (U, T);
18699 A, B : aliased T;
18700
18701 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
18702
18703 begin
18704 Info (P);
18705 A := new Integer;
18706 B := new Integer;
18707 B := A;
18708 Info (P);
18709 Free (A);
18710 begin
18711 Put_Line (Integer'Image(B.all));
18712 exception
18713 when E : others => Put_Line ("raised: " & Exception_Name (E));
18714 end;
18715 begin
18716 Free (B);
18717 exception
18718 when E : others => Put_Line ("raised: " & Exception_Name (E));
18719 end;
18720 B := UC(A'Access);
18721 begin
18722 Put_Line (Integer'Image(B.all));
18723 exception
18724 when E : others => Put_Line ("raised: " & Exception_Name (E));
18725 end;
18726 begin
18727 Free (B);
18728 exception
18729 when E : others => Put_Line ("raised: " & Exception_Name (E));
18730 end;
18731 Info (P);
18732 end Debug_Pool_Test;
18733 @end smallexample
18734
18735 @noindent
18736 The debug pool mechanism provides the following precise diagnostics on the
18737 execution of this erroneous program:
18738 @smallexample
18739 Debug Pool info:
18740 Total allocated bytes : 0
18741 Total deallocated bytes : 0
18742 Current Water Mark: 0
18743 High Water Mark: 0
18744
18745 Debug Pool info:
18746 Total allocated bytes : 8
18747 Total deallocated bytes : 0
18748 Current Water Mark: 8
18749 High Water Mark: 8
18750
18751 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18752 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18753 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18754 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18755 Debug Pool info:
18756 Total allocated bytes : 8
18757 Total deallocated bytes : 4
18758 Current Water Mark: 4
18759 High Water Mark: 8
18760 @end smallexample
18761
18762 @ifclear vms
18763 @ifclear FSFEDITION
18764 @node The gnatmem Tool
18765 @section The @command{gnatmem} Tool
18766 @findex gnatmem
18767
18768 @noindent
18769 The @code{gnatmem} utility monitors dynamic allocation and
18770 deallocation activity in a program, and displays information about
18771 incorrect deallocations and possible sources of memory leaks.
18772 It is designed to work in association with a static runtime library
18773 only and in this context provides three types of information:
18774 @itemize @bullet
18775 @item
18776 General information concerning memory management, such as the total
18777 number of allocations and deallocations, the amount of allocated
18778 memory and the high water mark, i.e.@: the largest amount of allocated
18779 memory in the course of program execution.
18780
18781 @item
18782 Backtraces for all incorrect deallocations, that is to say deallocations
18783 which do not correspond to a valid allocation.
18784
18785 @item
18786 Information on each allocation that is potentially the origin of a memory
18787 leak.
18788 @end itemize
18789
18790 @menu
18791 * Running gnatmem::
18792 * Switches for gnatmem::
18793 * Example of gnatmem Usage::
18794 @end menu
18795
18796 @node Running gnatmem
18797 @subsection Running @code{gnatmem}
18798
18799 @noindent
18800 @code{gnatmem} makes use of the output created by the special version of
18801 allocation and deallocation routines that record call information. This allows
18802 it to obtain accurate dynamic memory usage history at a minimal cost to the
18803 execution speed. Note however, that @code{gnatmem} is not supported on all
18804 platforms (currently, it is supported on AIX, HP-UX, GNU/Linux, Solaris and
18805 Windows NT/2000/XP (x86).
18806
18807 @noindent
18808 The @code{gnatmem} command has the form
18809
18810 @smallexample
18811 @c $ gnatmem @ovar{switches} user_program
18812 @c Expanding @ovar macro inline (explanation in macro def comments)
18813 $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
18814 @end smallexample
18815
18816 @noindent
18817 The program must have been linked with the instrumented version of the
18818 allocation and deallocation routines. This is done by linking with the
18819 @file{libgmem.a} library. For correct symbolic backtrace information,
18820 the user program should be compiled with debugging options
18821 (see @ref{Switches for gcc}). For example to build @file{my_program}:
18822
18823 @smallexample
18824 $ gnatmake -g my_program -largs -lgmem
18825 @end smallexample
18826
18827 @noindent
18828 As library @file{libgmem.a} contains an alternate body for package
18829 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
18830 when an executable is linked with library @file{libgmem.a}. It is then not
18831 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
18832
18833 @noindent
18834 When @file{my_program} is executed, the file @file{gmem.out} is produced.
18835 This file contains information about all allocations and deallocations
18836 performed by the program. It is produced by the instrumented allocations and
18837 deallocations routines and will be used by @code{gnatmem}.
18838
18839 In order to produce symbolic backtrace information for allocations and
18840 deallocations performed by the GNAT run-time library, you need to use a
18841 version of that library that has been compiled with the @option{-g} switch
18842 (see @ref{Rebuilding the GNAT Run-Time Library}).
18843
18844 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18845 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18846 @option{-i} switch, gnatmem will assume that this file can be found in the
18847 current directory. For example, after you have executed @file{my_program},
18848 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18849
18850 @smallexample
18851 $ gnatmem my_program
18852 @end smallexample
18853
18854 @noindent
18855 This will produce the output with the following format:
18856
18857 *************** debut cc
18858 @smallexample
18859 $ gnatmem my_program
18860
18861 Global information
18862 ------------------
18863 Total number of allocations : 45
18864 Total number of deallocations : 6
18865 Final Water Mark (non freed mem) : 11.29 Kilobytes
18866 High Water Mark : 11.40 Kilobytes
18867
18868 .
18869 .
18870 .
18871 Allocation Root # 2
18872 -------------------
18873 Number of non freed allocations : 11
18874 Final Water Mark (non freed mem) : 1.16 Kilobytes
18875 High Water Mark : 1.27 Kilobytes
18876 Backtrace :
18877 my_program.adb:23 my_program.alloc
18878 .
18879 .
18880 .
18881 @end smallexample
18882
18883 The first block of output gives general information. In this case, the
18884 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18885 Unchecked_Deallocation routine occurred.
18886
18887 @noindent
18888 Subsequent paragraphs display information on all allocation roots.
18889 An allocation root is a specific point in the execution of the program
18890 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18891 construct. This root is represented by an execution backtrace (or subprogram
18892 call stack). By default the backtrace depth for allocations roots is 1, so
18893 that a root corresponds exactly to a source location. The backtrace can
18894 be made deeper, to make the root more specific.
18895
18896 @node Switches for gnatmem
18897 @subsection Switches for @code{gnatmem}
18898
18899 @noindent
18900 @code{gnatmem} recognizes the following switches:
18901
18902 @table @option
18903
18904 @item -q
18905 @cindex @option{-q} (@code{gnatmem})
18906 Quiet. Gives the minimum output needed to identify the origin of the
18907 memory leaks. Omits statistical information.
18908
18909 @item @var{N}
18910 @cindex @var{N} (@code{gnatmem})
18911 N is an integer literal (usually between 1 and 10) which controls the
18912 depth of the backtraces defining allocation root. The default value for
18913 N is 1. The deeper the backtrace, the more precise the localization of
18914 the root. Note that the total number of roots can depend on this
18915 parameter. This parameter must be specified @emph{before} the name of the
18916 executable to be analyzed, to avoid ambiguity.
18917
18918 @item -b n
18919 @cindex @option{-b} (@code{gnatmem})
18920 This switch has the same effect as just depth parameter.
18921
18922 @item -i @var{file}
18923 @cindex @option{-i} (@code{gnatmem})
18924 Do the @code{gnatmem} processing starting from @file{file}, rather than
18925 @file{gmem.out} in the current directory.
18926
18927 @item -m n
18928 @cindex @option{-m} (@code{gnatmem})
18929 This switch causes @code{gnatmem} to mask the allocation roots that have less
18930 than n leaks. The default value is 1. Specifying the value of 0 will allow
18931 examination of even the roots that did not result in leaks.
18932
18933 @item -s order
18934 @cindex @option{-s} (@code{gnatmem})
18935 This switch causes @code{gnatmem} to sort the allocation roots according to the
18936 specified order of sort criteria, each identified by a single letter. The
18937 currently supported criteria are @code{n, h, w} standing respectively for
18938 number of unfreed allocations, high watermark, and final watermark
18939 corresponding to a specific root. The default order is @code{nwh}.
18940
18941 @item -t
18942 @cindex @option{-t} (@code{gnatmem})
18943 This switch causes memory allocated size to be always output in bytes.
18944 Default @code{gnatmem} behavior is to show memory sizes less then 1 kilobyte
18945 in bytes, from 1 kilobyte till 1 megabyte in kilobytes and the rest in
18946 megabytes.
18947
18948 @end table
18949
18950 @node Example of gnatmem Usage
18951 @subsection Example of @code{gnatmem} Usage
18952
18953 @noindent
18954 The following example shows the use of @code{gnatmem}
18955 on a simple memory-leaking program.
18956 Suppose that we have the following Ada program:
18957
18958 @smallexample @c ada
18959 @group
18960 @cartouche
18961 with Unchecked_Deallocation;
18962 procedure Test_Gm is
18963
18964 type T is array (1..1000) of Integer;
18965 type Ptr is access T;
18966 procedure Free is new Unchecked_Deallocation (T, Ptr);
18967 A : Ptr;
18968
18969 procedure My_Alloc is
18970 begin
18971 A := new T;
18972 end My_Alloc;
18973
18974 procedure My_DeAlloc is
18975 B : Ptr := A;
18976 begin
18977 Free (B);
18978 end My_DeAlloc;
18979
18980 begin
18981 My_Alloc;
18982 for I in 1 .. 5 loop
18983 for J in I .. 5 loop
18984 My_Alloc;
18985 end loop;
18986 My_Dealloc;
18987 end loop;
18988 end;
18989 @end cartouche
18990 @end group
18991 @end smallexample
18992
18993 @noindent
18994 The program needs to be compiled with debugging option and linked with
18995 @code{gmem} library:
18996
18997 @smallexample
18998 $ gnatmake -g test_gm -largs -lgmem
18999 @end smallexample
19000
19001 @noindent
19002 Then we execute the program as usual:
19003
19004 @smallexample
19005 $ test_gm
19006 @end smallexample
19007
19008 @noindent
19009 Then @code{gnatmem} is invoked simply with
19010 @smallexample
19011 $ gnatmem test_gm
19012 @end smallexample
19013
19014 @noindent
19015 which produces the following output (result may vary on different platforms):
19016
19017 @smallexample
19018 Global information
19019 ------------------
19020 Total number of allocations : 18
19021 Total number of deallocations : 5
19022 Final Water Mark (non freed mem) : 53.00 Kilobytes
19023 High Water Mark : 56.90 Kilobytes
19024
19025 Allocation Root # 1
19026 -------------------
19027 Number of non freed allocations : 11
19028 Final Water Mark (non freed mem) : 42.97 Kilobytes
19029 High Water Mark : 46.88 Kilobytes
19030 Backtrace :
19031 test_gm.adb:11 test_gm.my_alloc
19032
19033 Allocation Root # 2
19034 -------------------
19035 Number of non freed allocations : 1
19036 Final Water Mark (non freed mem) : 10.02 Kilobytes
19037 High Water Mark : 10.02 Kilobytes
19038 Backtrace :
19039 s-secsta.adb:81 system.secondary_stack.ss_init
19040
19041 Allocation Root # 3
19042 -------------------
19043 Number of non freed allocations : 1
19044 Final Water Mark (non freed mem) : 12 Bytes
19045 High Water Mark : 12 Bytes
19046 Backtrace :
19047 s-secsta.adb:181 system.secondary_stack.ss_init
19048 @end smallexample
19049
19050 @noindent
19051 Note that the GNAT run time contains itself a certain number of
19052 allocations that have no corresponding deallocation,
19053 as shown here for root #2 and root
19054 #3. This is a normal behavior when the number of non-freed allocations
19055 is one, it allocates dynamic data structures that the run time needs for
19056 the complete lifetime of the program. Note also that there is only one
19057 allocation root in the user program with a single line back trace:
19058 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
19059 program shows that 'My_Alloc' is called at 2 different points in the
19060 source (line 21 and line 24). If those two allocation roots need to be
19061 distinguished, the backtrace depth parameter can be used:
19062
19063 @smallexample
19064 $ gnatmem 3 test_gm
19065 @end smallexample
19066
19067 @noindent
19068 which will give the following output:
19069
19070 @smallexample
19071 Global information
19072 ------------------
19073 Total number of allocations : 18
19074 Total number of deallocations : 5
19075 Final Water Mark (non freed mem) : 53.00 Kilobytes
19076 High Water Mark : 56.90 Kilobytes
19077
19078 Allocation Root # 1
19079 -------------------
19080 Number of non freed allocations : 10
19081 Final Water Mark (non freed mem) : 39.06 Kilobytes
19082 High Water Mark : 42.97 Kilobytes
19083 Backtrace :
19084 test_gm.adb:11 test_gm.my_alloc
19085 test_gm.adb:24 test_gm
19086 b_test_gm.c:52 main
19087
19088 Allocation Root # 2
19089 -------------------
19090 Number of non freed allocations : 1
19091 Final Water Mark (non freed mem) : 10.02 Kilobytes
19092 High Water Mark : 10.02 Kilobytes
19093 Backtrace :
19094 s-secsta.adb:81 system.secondary_stack.ss_init
19095 s-secsta.adb:283 <system__secondary_stack___elabb>
19096 b_test_gm.c:33 adainit
19097
19098 Allocation Root # 3
19099 -------------------
19100 Number of non freed allocations : 1
19101 Final Water Mark (non freed mem) : 3.91 Kilobytes
19102 High Water Mark : 3.91 Kilobytes
19103 Backtrace :
19104 test_gm.adb:11 test_gm.my_alloc
19105 test_gm.adb:21 test_gm
19106 b_test_gm.c:52 main
19107
19108 Allocation Root # 4
19109 -------------------
19110 Number of non freed allocations : 1
19111 Final Water Mark (non freed mem) : 12 Bytes
19112 High Water Mark : 12 Bytes
19113 Backtrace :
19114 s-secsta.adb:181 system.secondary_stack.ss_init
19115 s-secsta.adb:283 <system__secondary_stack___elabb>
19116 b_test_gm.c:33 adainit
19117 @end smallexample
19118
19119 @noindent
19120 The allocation root #1 of the first example has been split in 2 roots #1
19121 and #3 thanks to the more precise associated backtrace.
19122 @end ifclear
19123 @end ifclear
19124
19125 @node Stack Related Facilities
19126 @chapter Stack Related Facilities
19127
19128 @noindent
19129 This chapter describes some useful tools associated with stack
19130 checking and analysis. In
19131 particular, it deals with dynamic and static stack usage measurements.
19132
19133 @menu
19134 * Stack Overflow Checking::
19135 * Static Stack Usage Analysis::
19136 * Dynamic Stack Usage Analysis::
19137 @end menu
19138
19139 @node Stack Overflow Checking
19140 @section Stack Overflow Checking
19141 @cindex Stack Overflow Checking
19142 @cindex -fstack-check
19143
19144 @noindent
19145 For most operating systems, @command{gcc} does not perform stack overflow
19146 checking by default. This means that if the main environment task or
19147 some other task exceeds the available stack space, then unpredictable
19148 behavior will occur. Most native systems offer some level of protection by
19149 adding a guard page at the end of each task stack. This mechanism is usually
19150 not enough for dealing properly with stack overflow situations because
19151 a large local variable could ``jump'' above the guard page.
19152 Furthermore, when the
19153 guard page is hit, there may not be any space left on the stack for executing
19154 the exception propagation code. Enabling stack checking avoids
19155 such situations.
19156
19157 To activate stack checking, compile all units with the gcc option
19158 @option{-fstack-check}. For example:
19159
19160 @smallexample
19161 gcc -c -fstack-check package1.adb
19162 @end smallexample
19163
19164 @noindent
19165 Units compiled with this option will generate extra instructions to check
19166 that any use of the stack (for procedure calls or for declaring local
19167 variables in declare blocks) does not exceed the available stack space.
19168 If the space is exceeded, then a @code{Storage_Error} exception is raised.
19169
19170 For declared tasks, the stack size is controlled by the size
19171 given in an applicable @code{Storage_Size} pragma or by the value specified
19172 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
19173 the default size as defined in the GNAT runtime otherwise.
19174
19175 For the environment task, the stack size depends on
19176 system defaults and is unknown to the compiler. Stack checking
19177 may still work correctly if a fixed
19178 size stack is allocated, but this cannot be guaranteed.
19179 @ifclear vms
19180 To ensure that a clean exception is signalled for stack
19181 overflow, set the environment variable
19182 @env{GNAT_STACK_LIMIT} to indicate the maximum
19183 stack area that can be used, as in:
19184 @cindex GNAT_STACK_LIMIT
19185
19186 @smallexample
19187 SET GNAT_STACK_LIMIT 1600
19188 @end smallexample
19189
19190 @noindent
19191 The limit is given in kilobytes, so the above declaration would
19192 set the stack limit of the environment task to 1.6 megabytes.
19193 Note that the only purpose of this usage is to limit the amount
19194 of stack used by the environment task. If it is necessary to
19195 increase the amount of stack for the environment task, then this
19196 is an operating systems issue, and must be addressed with the
19197 appropriate operating systems commands.
19198 @end ifclear
19199 @ifset vms
19200 To have a fixed size stack in the environment task, the stack must be put
19201 in the P0 address space and its size specified. Use these switches to
19202 create a p0 image:
19203
19204 @smallexample
19205 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
19206 @end smallexample
19207
19208 @noindent
19209 The quotes are required to keep case. The number after @samp{STACK=} is the
19210 size of the environmental task stack in pagelets (512 bytes). In this example
19211 the stack size is about 2 megabytes.
19212
19213 @noindent
19214 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
19215 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
19216 more details about the @option{/p0image} qualifier and the @option{stack}
19217 option.
19218
19219 @noindent
19220 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
19221 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
19222 stack in kilobytes. For example:
19223
19224 @smallexample
19225 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
19226 @end smallexample
19227 @end ifset
19228
19229 @node Static Stack Usage Analysis
19230 @section Static Stack Usage Analysis
19231 @cindex Static Stack Usage Analysis
19232 @cindex -fstack-usage
19233
19234 @noindent
19235 A unit compiled with @option{-fstack-usage} will generate an extra file
19236 that specifies
19237 the maximum amount of stack used, on a per-function basis.
19238 The file has the same
19239 basename as the target object file with a @file{.su} extension.
19240 Each line of this file is made up of three fields:
19241
19242 @itemize
19243 @item
19244 The name of the function.
19245 @item
19246 A number of bytes.
19247 @item
19248 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
19249 @end itemize
19250
19251 The second field corresponds to the size of the known part of the function
19252 frame.
19253
19254 The qualifier @code{static} means that the function frame size
19255 is purely static.
19256 It usually means that all local variables have a static size.
19257 In this case, the second field is a reliable measure of the function stack
19258 utilization.
19259
19260 The qualifier @code{dynamic} means that the function frame size is not static.
19261 It happens mainly when some local variables have a dynamic size. When this
19262 qualifier appears alone, the second field is not a reliable measure
19263 of the function stack analysis. When it is qualified with @code{bounded}, it
19264 means that the second field is a reliable maximum of the function stack
19265 utilization.
19266
19267 A unit compiled with @option{-Wstack-usage} will issue a warning for each
19268 subprogram whose stack usage might be larger than the specified amount of
19269 bytes. The wording is in keeping with the qualifier documented above.
19270
19271 @node Dynamic Stack Usage Analysis
19272 @section Dynamic Stack Usage Analysis
19273
19274 @noindent
19275 It is possible to measure the maximum amount of stack used by a task, by
19276 adding a switch to @command{gnatbind}, as:
19277
19278 @smallexample
19279 $ gnatbind -u0 file
19280 @end smallexample
19281
19282 @noindent
19283 With this option, at each task termination, its stack usage is output on
19284 @file{stderr}.
19285 It is not always convenient to output the stack usage when the program
19286 is still running. Hence, it is possible to delay this output until program
19287 termination. for a given number of tasks specified as the argument of the
19288 @option{-u} option. For instance:
19289
19290 @smallexample
19291 $ gnatbind -u100 file
19292 @end smallexample
19293
19294 @noindent
19295 will buffer the stack usage information of the first 100 tasks to terminate and
19296 output this info at program termination. Results are displayed in four
19297 columns:
19298
19299 @noindent
19300 Index | Task Name | Stack Size | Stack Usage
19301
19302 @noindent
19303 where:
19304
19305 @table @emph
19306 @item Index
19307 is a number associated with each task.
19308
19309 @item Task Name
19310 is the name of the task analyzed.
19311
19312 @item Stack Size
19313 is the maximum size for the stack.
19314
19315 @item Stack Usage
19316 is the measure done by the stack analyzer. In order to prevent overflow, the stack
19317 is not entirely analyzed, and it's not possible to know exactly how
19318 much has actually been used.
19319
19320 @end table
19321
19322 @noindent
19323 The environment task stack, e.g., the stack that contains the main unit, is
19324 only processed when the environment variable GNAT_STACK_LIMIT is set.
19325
19326 @noindent
19327 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
19328 stack usage reports at run-time. See its body for the details.
19329
19330 @ifclear FSFEDITION
19331 @c *********************************
19332 @c * GNATCHECK *
19333 @c *********************************
19334 @node Verifying Properties with gnatcheck
19335 @chapter Verifying Properties with @command{gnatcheck}
19336 @findex gnatcheck
19337 @cindex @command{gnatcheck}
19338
19339 @noindent
19340 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
19341 of Ada source files according to a given set of semantic rules.
19342 @cindex ASIS
19343
19344 In order to check compliance with a given rule, @command{gnatcheck} has to
19345 semantically analyze the Ada sources.
19346 Therefore, checks can only be performed on
19347 legal Ada units. Moreover, when a unit depends semantically upon units located
19348 outside the current directory, the source search path has to be provided when
19349 calling @command{gnatcheck}, either through a specified project file or
19350 through @command{gnatcheck} switches.
19351
19352 For full details, refer to @cite{GNATcheck Reference Manual} document.
19353 @end ifclear
19354
19355 @ifclear FSFEDITION
19356 @c *********************************
19357 @node Creating Sample Bodies with gnatstub
19358 @chapter Creating Sample Bodies with @command{gnatstub}
19359 @findex gnatstub
19360
19361 @noindent
19362 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
19363 for library unit declarations.
19364
19365 To create a body stub, @command{gnatstub} invokes the Ada
19366 compiler and generates and uses the ASIS tree for the input source;
19367 thus the input must be legal Ada code, and the tool should have all the
19368 information needed to compile the input source. To provide this information,
19369 you may specify as a tool parameter the project file the input source belongs to
19370 (or you may call @command{gnatstub}
19371 through the @command{gnat} driver (see @ref{The GNAT Driver and
19372 Project Files}). Another possibility is to specify the source search
19373 path and needed configuration files in @option{-cargs} section of @command{gnatstub}
19374 call, see the description of the @command{gnatstub} switches below.
19375
19376 By default, all the program unit body stubs generated by @code{gnatstub}
19377 raise the predefined @code{Program_Error} exception, which will catch
19378 accidental calls of generated stubs. This behavior can be changed with
19379 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
19380
19381 @menu
19382 * Running gnatstub::
19383 * Switches for gnatstub::
19384 @end menu
19385
19386 @node Running gnatstub
19387 @section Running @command{gnatstub}
19388
19389 @noindent
19390 @command{gnatstub} has a command-line interface of the form:
19391
19392 @smallexample
19393 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
19394 @c Expanding @ovar macro inline (explanation in macro def comments)
19395 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19396 @end smallexample
19397
19398 @noindent
19399 where
19400 @table @var
19401 @item filename
19402 is the name of the source file that contains a library unit declaration
19403 for which a body must be created. The file name may contain the path
19404 information.
19405 The file name does not have to follow the GNAT file name conventions. If the
19406 name
19407 does not follow GNAT file naming conventions, the name of the body file must
19408 be provided
19409 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
19410 If the file name follows the GNAT file naming
19411 conventions and the name of the body file is not provided,
19412 @command{gnatstub}
19413 creates the name
19414 of the body file from the argument file name by replacing the @file{.ads}
19415 suffix
19416 with the @file{.adb} suffix.
19417
19418 @item directory
19419 indicates the directory in which the body stub is to be placed (the default
19420 is the
19421 current directory)
19422
19423 @item @samp{@var{gcc_switches}} is a list of switches for
19424 @command{gcc}. They will be passed on to all compiler invocations made by
19425 @command{gnatstub} to generate the ASIS trees. Here you can provide
19426 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19427 use the @option{-gnatec} switch to set the configuration file,
19428 use the @option{-gnat05} switch if sources should be compiled in
19429 Ada 2005 mode etc.
19430
19431 @item switches
19432 is an optional sequence of switches as described in the next section
19433 @end table
19434
19435 @node Switches for gnatstub
19436 @section Switches for @command{gnatstub}
19437
19438 @table @option
19439 @c !sort!
19440
19441 @item --version
19442 @cindex @option{--version} @command{gnatstub}
19443 Display Copyright and version, then exit disregarding all other options.
19444
19445 @item --help
19446 @cindex @option{--help} @command{gnatstub}
19447 Display usage, then exit disregarding all other options.
19448
19449 @item -P @var{file}
19450 @cindex @option{-P} @command{gnatstub}
19451 Indicates the name of the project file that describes the set of sources
19452 to be processed.
19453
19454 @item -X@var{name}=@var{value}
19455 @cindex @option{-X} @command{gnatstub}
19456 Indicates that external variable @var{name} in the argument project
19457 has the value @var{value}. Has no effect if no project is specified as
19458 tool argument.
19459
19460 @item ^-f^/FULL^
19461 @cindex @option{^-f^/FULL^} (@command{gnatstub})
19462 If the destination directory already contains a file with the name of the
19463 body file
19464 for the argument spec file, replace it with the generated body stub.
19465
19466 @item ^-hs^/HEADER=SPEC^
19467 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
19468 Put the comment header (i.e., all the comments preceding the
19469 compilation unit) from the source of the library unit declaration
19470 into the body stub.
19471
19472 @item ^-hg^/HEADER=GENERAL^
19473 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
19474 Put a sample comment header into the body stub.
19475
19476 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
19477 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
19478 Use the content of the file as the comment header for a generated body stub.
19479
19480 @ifclear vms
19481 @item -IDIR
19482 @cindex @option{-IDIR} (@command{gnatstub})
19483 @itemx -I-
19484 @cindex @option{-I-} (@command{gnatstub})
19485 @end ifclear
19486 @ifset vms
19487 @item /NOCURRENT_DIRECTORY
19488 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
19489 @end ifset
19490 ^These switches have ^This switch has^ the same meaning as in calls to
19491 @command{gcc}.
19492 ^They define ^It defines ^ the source search path in the call to
19493 @command{gcc} issued
19494 by @command{gnatstub} to compile an argument source file.
19495
19496 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
19497 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
19498 This switch has the same meaning as in calls to @command{gcc}.
19499 It defines the additional configuration file to be passed to the call to
19500 @command{gcc} issued
19501 by @command{gnatstub} to compile an argument source file.
19502
19503 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
19504 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
19505 (@var{n} is a non-negative integer). Set the maximum line length that is
19506 allowed in a source file. The default is 79. The maximum value that can be
19507 specified is 32767. Note that in the special case of configuration
19508 pragma files, the maximum is always 32767 regardless of whether or
19509 not this switch appears.
19510
19511 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
19512 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
19513 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
19514 the generated body sample to @var{n}.
19515 The default indentation is 3.
19516
19517 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
19518 @cindex @option{^-gnatyo^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
19519 Order local bodies alphabetically. (By default local bodies are ordered
19520 in the same way as the corresponding local specs in the argument spec file.)
19521
19522 @item ^-i^/INDENTATION=^@var{n}
19523 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
19524 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
19525
19526 @item ^-k^/TREE_FILE=SAVE^
19527 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
19528 Do not remove the tree file (i.e., the snapshot of the compiler internal
19529 structures used by @command{gnatstub}) after creating the body stub.
19530
19531 @item ^-l^/LINE_LENGTH=^@var{n}
19532 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
19533 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
19534
19535 @item ^--no-exception^/NO_EXCEPTION^
19536 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
19537 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
19538 This is not always possible for function stubs.
19539
19540 @item ^--no-local-header^/NO_LOCAL_HEADER^
19541 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
19542 Do not place local comment header with unit name before body stub for a
19543 unit.
19544
19545 @item ^-o ^/BODY=^@var{body-name}
19546 @cindex @option{^-o^/BODY^} (@command{gnatstub})
19547 Body file name. This should be set if the argument file name does not
19548 follow
19549 the GNAT file naming
19550 conventions. If this switch is omitted the default name for the body will be
19551 obtained
19552 from the argument file name according to the GNAT file naming conventions.
19553
19554 @item ^-W^/RESULT_ENCODING=^@var{e}
19555 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatstub})
19556 Specify the wide character encoding method for the output body file.
19557 @var{e} is one of the following:
19558
19559 @itemize @bullet
19560
19561 @item ^h^HEX^
19562 Hex encoding
19563
19564 @item ^u^UPPER^
19565 Upper half encoding
19566
19567 @item ^s^SHIFT_JIS^
19568 Shift/JIS encoding
19569
19570 @item ^e^EUC^
19571 EUC encoding
19572
19573 @item ^8^UTF8^
19574 UTF-8 encoding
19575
19576 @item ^b^BRACKETS^
19577 Brackets encoding (default value)
19578 @end itemize
19579
19580 @item ^-q^/QUIET^
19581 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
19582 Quiet mode: do not generate a confirmation when a body is
19583 successfully created, and do not generate a message when a body is not
19584 required for an
19585 argument unit.
19586
19587 @item ^-r^/TREE_FILE=REUSE^
19588 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
19589 Reuse the tree file (if it exists) instead of creating it. Instead of
19590 creating the tree file for the library unit declaration, @command{gnatstub}
19591 tries to find it in the current directory and use it for creating
19592 a body. If the tree file is not found, no body is created. This option
19593 also implies @option{^-k^/SAVE^}, whether or not
19594 the latter is set explicitly.
19595
19596 @item ^-t^/TREE_FILE=OVERWRITE^
19597 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
19598 Overwrite the existing tree file. If the current directory already
19599 contains the file which, according to the GNAT file naming rules should
19600 be considered as a tree file for the argument source file,
19601 @command{gnatstub}
19602 will refuse to create the tree file needed to create a sample body
19603 unless this option is set.
19604
19605 @item ^-v^/VERBOSE^
19606 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
19607 Verbose mode: generate version information.
19608
19609 @end table
19610 @end ifclear
19611
19612 @ifclear FSFEDITION
19613 @c *********************************
19614 @node Creating Unit Tests with gnattest
19615 @chapter Creating Unit Tests with @command{gnattest}
19616 @findex gnattest
19617
19618 @noindent
19619 @command{gnattest} is an ASIS-based utility that creates unit-test skeletons
19620 as well as a test driver infrastructure (harness). @command{gnattest} creates
19621 a skeleton for each visible subprogram in the packages under consideration when
19622 they do not exist already.
19623
19624 In order to process source files from a project, @command{gnattest} has to
19625 semantically analyze the sources. Therefore, test skeletons can only be
19626 generated for legal Ada units. If a unit is dependent on other units,
19627 those units should be among the source files of the project or of other projects
19628 imported by this one.
19629
19630 Generated skeletons and harnesses are based on the AUnit testing framework.
19631 AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit
19632 for Java or CppUnit for C++. While it is advised that gnattest users read
19633 the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest.
19634 For correct operation of @command{gnattest}, AUnit should be installed and
19635 aunit.gpr must be on the project path. This happens automatically when Aunit
19636 is installed at its default location.
19637 @menu
19638 * Running gnattest::
19639 * Switches for gnattest::
19640 * Project Attributes for gnattest::
19641 * Simple Example::
19642 * Setting Up and Tearing Down the Testing Environment::
19643 * Regenerating Tests::
19644 * Default Test Behavior::
19645 * Testing Primitive Operations of Tagged Types::
19646 * Testing Inheritance::
19647 * Tagged Types Substitutability Testing::
19648 * Testing with Contracts::
19649 * Additional Tests::
19650 @ifclear vms
19651 * Support for other platforms/run-times::
19652 @end ifclear
19653 * Current Limitations::
19654 @end menu
19655
19656 @node Running gnattest
19657 @section Running @command{gnattest}
19658
19659 @noindent
19660 @command{gnattest} has a command-line interface of the form
19661
19662 @smallexample
19663 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
19664 @c Expanding @ovar macro inline (explanation in macro def comments)
19665 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19666 @end smallexample
19667
19668 @noindent
19669 where
19670 @table @var
19671
19672 @item -Pprojname
19673 specifies the project defining the location of source files. When no
19674 file names are provided on the command line, all sources in the project
19675 are used as input. This switch is required.
19676
19677 @item filename
19678 is the name of the source file containing the library unit package declaration
19679 for which a test package will be created. The file name may be given with a
19680 path.
19681
19682 @item @samp{@var{gcc_switches}}
19683 is a list of switches for
19684 @command{gcc}. These switches will be passed on to all compiler invocations
19685 made by @command{gnattest} to generate a set of ASIS trees. Here you can provide
19686 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19687 use the @option{-gnatec} switch to set the configuration file,
19688 use the @option{-gnat05} switch if sources should be compiled in
19689 Ada 2005 mode, etc.
19690
19691 @item switches
19692 is an optional sequence of switches as described in the next section.
19693
19694 @end table
19695
19696 @command{gnattest} results can be found in two different places.
19697
19698 @itemize @bullet
19699 @item automatic harness:
19700 the harness code, which is located by default in "gnattest/harness" directory
19701 that is created in the object directory of corresponding project file. All of
19702 this code is generated completely automatically and can be destroyed and
19703 regenerated at will. It is not recommended to modify this code manually, since
19704 it could easily be overridden by mistake. The entry point in the harness code is
19705 the project file named @command{test_driver.gpr}. Tests can be compiled and run
19706 using a command such as:
19707
19708 @smallexample
19709 gnatmake -P<harness-dir>/test_driver
19710 test_runner
19711 @end smallexample
19712
19713 Note that you might need to specify the necessary values of scenario variables
19714 when you are not using the AUnit defaults.
19715
19716 @item actual unit test skeletons:
19717 a test skeleton for each visible subprogram is created in a separate file, if it
19718 doesn't exist already. By default, those separate test files are located in a
19719 "gnattest/tests" directory that is created in the object directory of
19720 corresponding project file. For example, if a source file my_unit.ads in
19721 directory src contains a visible subprogram Proc, then the corresponding unit
19722 test will be found in file src/tests/my_unit-test_data-tests-proc_<code>.adb.
19723 <code> is a signature encoding used to differentiate test names in case of
19724 overloading.
19725
19726 Note that if the project already has both my_unit.ads and my_unit-test_data.ads,
19727 this will cause a name conflict with the generated test package.
19728 @end itemize
19729
19730 @node Switches for gnattest
19731 @section Switches for @command{gnattest}
19732
19733 @table @option
19734 @c !sort!
19735
19736 @item --harness-only
19737 @cindex @option{--harness-only} (@command{gnattest})
19738 When this option is given, @command{gnattest} creates a harness for all
19739 sources, treating them as test packages.
19740
19741 @item --additional-tests=@var{projname}
19742 @cindex @option{--additional-tests} (@command{gnattest})
19743 Sources described in @var{projname} are considered potential additional
19744 manual tests to be added to the test suite.
19745
19746 @item -r
19747 @cindex @option{-r} (@command{gnattest})
19748 Recursively consider all sources from all projects.
19749
19750 @item -X@var{name=value}
19751 @cindex @option{-X} (@command{gnattest})
19752 Indicate that external variable @var{name} has the value @var{value}.
19753
19754 @item -q
19755 @cindex @option{-q} (@command{gnattest})
19756 Suppresses noncritical output messages.
19757
19758 @item -v
19759 @cindex @option{-v} (@command{gnattest})
19760 Verbose mode: generates version information.
19761
19762 @item --validate-type-extensions
19763 @cindex @option{--validate-type-extensions} (@command{gnattest})
19764 Enables substitution check: run all tests from all parents in order
19765 to check substitutability.
19766
19767 @item --skeleton-default=@var{val}
19768 @cindex @option{--skeleton-default} (@command{gnattest})
19769 Specifies the default behavior of generated skeletons. @var{val} can be either
19770 "fail" or "pass", "fail" being the default.
19771
19772 @item --passed-tests=@var{val}
19773 @cindex @option{--skeleton-default} (@command{gnattest})
19774 Specifies whether or not passed tests should be shown. @var{val} can be either
19775 "show" or "hide", "show" being the default.
19776
19777
19778 @item --tests-root=@var{dirname}
19779 @cindex @option{--tests-root} (@command{gnattest})
19780 The directory hierarchy of tested sources is recreated in the @var{dirname}
19781 directory, and test packages are placed in corresponding directories.
19782 If the @var{dirname} is a relative path, it is considered relative to the object
19783 directory of the project file. When all sources from all projects are taken
19784 recursively from all projects, directory hierarchies of tested sources are
19785 recreated for each project in their object directories and test packages are
19786 placed accordingly.
19787
19788 @item --subdir=@var{dirname}
19789 @cindex @option{--subdir} (@command{gnattest})
19790 Test packages are placed in subdirectories.
19791
19792 @item --tests-dir=@var{dirname}
19793 @cindex @option{--tests-dir} (@command{gnattest})
19794 All test packages are placed in the @var{dirname} directory.
19795 If the @var{dirname} is a relative path, it is considered relative to the object
19796 directory of the project file. When all sources from all projects are taken
19797 recursively from all projects, @var{dirname} directories are created for each
19798 project in their object directories and test packages are placed accordingly.
19799
19800 @item --harness-dir=@var{dirname}
19801 @cindex @option{--harness-dir} (@command{gnattest})
19802 specifies the directory that will hold the harness packages and project file
19803 for the test driver. If the @var{dirname} is a relative path, it is considered
19804 relative to the object directory of the project file.
19805
19806 @item --separates
19807 @cindex @option{--separates} (@command{gnattest})
19808 Bodies of all test routines are generated as separates. Note that this mode is
19809 kept for compatibility reasons only and it is not advised to use it due to
19810 possible problems with hash in names of test skeletons when using an
19811 inconsistent casing. Separate test skeletons can be incorporated to monolith
19812 test package with improved hash being used by using @option{--transition}
19813 switch.
19814
19815
19816 @item --transition
19817 @cindex @option{--transition} (@command{gnattest})
19818 This allows transition from separate test routines to monolith test packages.
19819 All matching test routines are overwritten with contents of corresponding
19820 separates. Note that if separate test routines had any manually added with
19821 clauses they will be moved to the test package body as is and have to be moved
19822 by hand.
19823
19824 @end table
19825
19826 @option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are
19827 mutually exclusive.
19828
19829 @node Project Attributes for gnattest
19830 @section Project Attributes for @command{gnattest}
19831
19832 @noindent
19833
19834 Most of the command-line options can also be passed to the tool by adding
19835 special attributes to the project file. Those attributes should be put in
19836 package gnattest. Here is the list of attributes:
19837
19838 @itemize @bullet
19839
19840 @item Tests_Root
19841 is used to select the same output mode as with the --tests-root option.
19842 This attribute cannot be used together with Subdir or Tests_Dir.
19843
19844 @item Subdir
19845 is used to select the same output mode as with the --subdir option.
19846 This attribute cannot be used together with Tests_Root or Tests_Dir.
19847
19848 @item Tests_Dir
19849 is used to select the same output mode as with the --tests-dir option.
19850 This attribute cannot be used together with Subdir or Tests_Root.
19851
19852 @item Harness_Dir
19853 is used to specify the directory in which to place harness packages and project
19854 file for the test driver, otherwise specified by --harness-dir.
19855
19856 @item Additional_Tests
19857 is used to specify the project file, otherwise given by
19858 --additional-tests switch.
19859
19860 @item Skeletons_Default
19861 is used to specify the default behaviour of test skeletons, otherwise
19862 specified by --skeleton-default option. The value of this attribute
19863 should be either "pass" or "fail".
19864
19865 @end itemize
19866
19867 Each of those attributes can be overridden from the command line if needed.
19868 Other @command{gnattest} switches can also be passed via the project
19869 file as an attribute list called GNATtest_Switches.
19870
19871 @node Simple Example
19872 @section Simple Example
19873
19874 @noindent
19875
19876 Let's take a very simple example using the first @command{gnattest} example
19877 located in:
19878
19879 @smallexample
19880 <install_prefix>/share/examples/gnattest/simple
19881 @end smallexample
19882
19883 This project contains a simple package containing one subprogram. By running gnattest:
19884
19885 @smallexample
19886 $ gnattest --harness-dir=driver -Psimple.gpr
19887 @end smallexample
19888
19889 a test driver is created in directory "driver". It can be compiled and run:
19890
19891 @smallexample
19892 $ cd obj/driver
19893 $ gnatmake -Ptest_driver
19894 $ test_runner
19895 @end smallexample
19896
19897 One failed test with diagnosis "test not implemented" is reported.
19898 Since no special output option was specified, the test package Simple.Tests
19899 is located in:
19900
19901 @smallexample
19902 <install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
19903 @end smallexample
19904
19905 For each package containing visible subprograms, a child test package is
19906 generated. It contains one test routine per tested subprogram. Each
19907 declaration of a test subprogram has a comment specifying which tested
19908 subprogram it corresponds to. Bodies of test routines are placed in test package
19909 bodies and are surrounded by special comment sections. Those comment sections
19910 should not be removed or modified in order for gnattest to be able to regenerate
19911 test packages and keep already written tests in place.
19912 The test routine Test_Inc_5eaee3 located at simple-test_data-tests.adb contains
19913 a single statement: a call to procedure Assert. It has two arguments:
19914 the Boolean expression we want to check and the diagnosis message to display if
19915 the condition is false.
19916
19917 That is where actual testing code should be written after a proper setup.
19918 An actual check can be performed by replacing the Assert call with:
19919
19920 @smallexample @c ada
19921 Assert (Inc (1) = 2, "wrong incrementation");
19922 @end smallexample
19923
19924 After recompiling and running the test driver, one successfully passed test
19925 is reported.
19926
19927 @node Setting Up and Tearing Down the Testing Environment
19928 @section Setting Up and Tearing Down the Testing Environment
19929
19930 @noindent
19931
19932 Besides test routines themselves, each test package has a parent package
19933 Test_Data that has two procedures: Set_Up and Tear_Down. This package is never
19934 overwritten by the tool. Set_Up is called before each test routine of the
19935 package and Tear_Down is called after each test routine. Those two procedures
19936 can be used to perform necessary initialization and finalization,
19937 memory allocation, etc. Test type declared in Test_Data package is parent type
19938 for the test type of test package and can have user-defined components whose
19939 values can be set by Set_Up routine and used in test routines afterwards.
19940
19941 @node Regenerating Tests
19942 @section Regenerating Tests
19943
19944 @noindent
19945
19946 Bodies of test routines and test_data packages are never overridden after they
19947 have been created once. As long as the name of the subprogram, full expanded Ada
19948 names, and the order of its parameters is the same, and comment sections are
19949 intact the old test routine will fit in its place and no test skeleton will be
19950 generated for the subprogram.
19951
19952 This can be demonstrated with the previous example. By uncommenting declaration
19953 and body of function Dec in simple.ads and simple.adb, running
19954 @command{gnattest} on the project, and then running the test driver:
19955
19956 @smallexample
19957 gnattest --harness-dir=driver -Psimple.gpr
19958 cd obj/driver
19959 gnatmake -Ptest_driver
19960 test_runner
19961 @end smallexample
19962
19963 the old test is not replaced with a stub, nor is it lost, but a new test
19964 skeleton is created for function Dec.
19965
19966 The only way of regenerating tests skeletons is to remove the previously created
19967 tests together with corresponding comment sections.
19968
19969 @node Default Test Behavior
19970 @section Default Test Behavior
19971
19972 @noindent
19973
19974 The generated test driver can treat unimplemented tests in two ways:
19975 either count them all as failed (this is useful to see which tests are still
19976 left to implement) or as passed (to sort out unimplemented ones from those
19977 actually failing).
19978
19979 The test driver accepts a switch to specify this behavior:
19980 --skeleton-default=val, where val is either "pass" or "fail" (exactly as for
19981 @command{gnattest}).
19982
19983 The default behavior of the test driver is set with the same switch
19984 as passed to gnattest when generating the test driver.
19985
19986 Passing it to the driver generated on the first example:
19987
19988 @smallexample
19989 test_runner --skeleton-default=pass
19990 @end smallexample
19991
19992 makes both tests pass, even the unimplemented one.
19993
19994 @node Testing Primitive Operations of Tagged Types
19995 @section Testing Primitive Operations of Tagged Types
19996
19997 @noindent
19998
19999 Creation of test skeletons for primitive operations of tagged types entails
20000 a number of features. Test routines for all primitives of a given tagged type
20001 are placed in a separate child package named according to the tagged type. For
20002 example, if you have tagged type T in package P, all tests for primitives
20003 of T will be in P.T_Test_Data.T_Tests.
20004
20005 Consider running gnattest on the second example (note: actual tests for this
20006 example already exist, so there's no need to worry if the tool reports that
20007 no new stubs were generated):
20008
20009 @smallexample
20010 cd <install_prefix>/share/examples/gnattest/tagged_rec
20011 gnattest --harness-dir=driver -Ptagged_rec.gpr
20012 @end smallexample
20013
20014 Taking a closer look at the test type declared in the test package
20015 Speed1.Controller_Test_Data is necessary. It is declared in:
20016
20017 @smallexample
20018 <install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
20019 @end smallexample
20020
20021 Test types are direct or indirect descendants of
20022 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
20023 subprograms, the user doesn't need to be concerned with them. However,
20024 when generating test packages for primitive operations, there are some things
20025 the user needs to know.
20026
20027 Type Test_Controller has components that allow assignment of various
20028 derivations of type Controller. And if you look at the specification of
20029 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
20030 actually derives from Test_Controller rather than AUnit type Test_Fixture.
20031 Thus, test types mirror the hierarchy of tested types.
20032
20033 The Set_Up procedure of Test_Data package corresponding to a test package
20034 of primitive operations of type T assigns to Fixture a reference to an
20035 object of that exact type T. Notice, however, that if the tagged type has
20036 discriminants, the Set_Up only has a commented template for setting
20037 up the fixture, since filling the discriminant with actual value is up
20038 to the user.
20039
20040 The knowledge of the structure of test types allows additional testing
20041 without additional effort. Those possibilities are described below.
20042
20043 @node Testing Inheritance
20044 @section Testing Inheritance
20045
20046 @noindent
20047
20048 Since the test type hierarchy mimics the hierarchy of tested types, the
20049 inheritance of tests takes place. An example of such inheritance can be
20050 seen by running the test driver generated for the second example. As previously
20051 mentioned, actual tests are already written for this example.
20052
20053 @smallexample
20054 cd obj/driver
20055 gnatmake -Ptest_driver
20056 test_runner
20057 @end smallexample
20058
20059 There are 6 passed tests while there are only 5 testable subprograms. The test
20060 routine for function Speed has been inherited and run against objects of the
20061 derived type.
20062
20063 @node Tagged Types Substitutability Testing
20064 @section Tagged Types Substitutability Testing
20065
20066 @noindent
20067
20068 Tagged Types Substitutability Testing is a way of verifying the global type
20069 consistency by testing. Global type consistency is a principle stating that if
20070 S is a subtype of T (in Ada, S is a derived type of tagged type T),
20071 then objects of type T may be replaced with objects of type S (that is,
20072 objects of type S may be substituted for objects of type T), without
20073 altering any of the desirable properties of the program. When the properties
20074 of the program are expressed in the form of subprogram preconditions and
20075 postconditions (let's call them pre and post), the principle is formulated as
20076 relations between the pre and post of primitive operations and the pre and post
20077 of their derived operations. The pre of a derived operation should not be
20078 stronger than the original pre, and the post of the derived operation should
20079 not be weaker than the original post. Those relations ensure that verifying if
20080 a dispatching call is safe can be done just by using the pre and post of the
20081 root operation.
20082
20083 Verifying global type consistency by testing consists of running all the unit
20084 tests associated with the primitives of a given tagged type with objects of its
20085 derived types.
20086
20087 In the example used in the previous section, there was clearly a violation of
20088 type consistency. The overriding primitive Adjust_Speed in package Speed2
20089 removes the functionality of the overridden primitive and thus doesn't respect
20090 the consistency principle.
20091 Gnattest has a special option to run overridden parent tests against objects
20092 of the type which have overriding primitives:
20093
20094 @smallexample
20095 gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr
20096 cd obj/driver
20097 gnatmake -Ptest_driver
20098 test_runner
20099 @end smallexample
20100
20101 While all the tests pass by themselves, the parent test for Adjust_Speed fails
20102 against objects of the derived type.
20103
20104 Non-overridden tests are already inherited for derived test types, so the
20105 --validate-type-extensions enables the application of overriden tests to objects
20106 of derived types.
20107
20108 @node Testing with Contracts
20109 @section Testing with Contracts
20110
20111 @noindent
20112
20113 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case,
20114 as well as corresponding aspects.
20115 Test routines are generated, one per each Test_Case associated with a tested
20116 subprogram. Those test routines have special wrappers for tested functions
20117 that have composition of pre- and postcondition of the subprogram with
20118 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
20119 either count for Nominal mode or do not count for Robustness mode).
20120
20121 The third example demonstrates how this works:
20122
20123 @smallexample
20124 cd <install_prefix>/share/examples/gnattest/contracts
20125 gnattest --harness-dir=driver -Pcontracts.gpr
20126 @end smallexample
20127
20128 Putting actual checks within the range of the contract does not cause any
20129 error reports. For example, for the test routine which corresponds to
20130 test case 1:
20131
20132 @smallexample @c ada
20133 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
20134 @end smallexample
20135
20136 and for the test routine corresponding to test case 2:
20137
20138 @smallexample @c ada
20139 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
20140 @end smallexample
20141
20142 are acceptable:
20143
20144 @smallexample
20145 cd obj/driver
20146 gnatmake -Ptest_driver
20147 test_runner
20148 @end smallexample
20149
20150 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
20151 a precondition violation for test case one. Also, by using any otherwise
20152 correct but positive pair of numbers in the second test routine, you can also
20153 get a precondition violation. Postconditions are checked and reported
20154 the same way.
20155
20156 @node Additional Tests
20157 @section Additional Tests
20158
20159 @noindent
20160 @command{gnattest} can add user-written tests to the main suite of the test
20161 driver. @command{gnattest} traverses the given packages and searches for test
20162 routines. All procedures with a single in out parameter of a type which is
20163 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
20164 specifications are added to the suites and are then executed by the test driver.
20165 (Set_Up and Tear_Down are filtered out.)
20166
20167 An example illustrates two ways of creating test harnesses for user-written
20168 tests. Directory additional_tests contains an AUnit-based test driver written
20169 by hand.
20170
20171 @smallexample
20172 <install_prefix>/share/examples/gnattest/additional_tests/
20173 @end smallexample
20174
20175 To create a test driver for already-written tests, use the --harness-only
20176 option:
20177
20178 @smallexample
20179 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
20180 --harness-only
20181 gnatmake -Pharness_only/test_driver.gpr
20182 harness_only/test_runner
20183 @end smallexample
20184
20185 Additional tests can also be executed together with generated tests:
20186
20187 @smallexample
20188 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
20189 --harness-dir=mixing
20190 gnatmake -Pmixing/test_driver.gpr
20191 mixing/test_runner
20192 @end smallexample
20193
20194 @ifclear vms
20195 @node Support for other platforms/run-times
20196 @section Support for other platforms/run-times
20197
20198 @noindent
20199 @command{gnattest} can be used to generate the test harness for platforms
20200 and run-time libraries others than the default native target with the
20201 default full run-time. For example, when using a limited run-time library
20202 such as Zero FootPrint (ZFP), a simplified harness is generated.
20203
20204 Two variables are used to tell the underlying AUnit framework how to generate
20205 the test harness: @code{PLATFORM}, which identifies the target, and
20206 @code{RUNTIME}, used to determine the run-time library for which the harness
20207 is generated. Corresponding prefix should also be used when calling
20208 @command{gnattest} for non-native targets. For example, the following options
20209 are used to generate the AUnit test harness for a PowerPC ELF target using
20210 the ZFP run-time library:
20211
20212 @smallexample
20213 powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
20214 @end smallexample
20215 @end ifclear
20216
20217 @node Current Limitations
20218 @section Current Limitations
20219
20220 @noindent
20221
20222 The tool currently does not support following features:
20223
20224 @itemize @bullet
20225 @item generic tests for generic packages and package instantiations
20226 @item tests for protected subprograms and entries
20227
20228 @end itemize
20229 @end ifclear
20230
20231
20232 @c *********************************
20233 @node Performing Dimensionality Analysis in GNAT
20234 @chapter Performing Dimensionality Analysis in GNAT
20235 @cindex Dimensionality analysis
20236
20237 @noindent
20238 The GNAT compiler now supports dimensionality checking. The user can
20239 specify physical units for objects, and the compiler will verify that uses
20240 of these objects are compatible with their dimensions, in a fashion that is
20241 familiar to engineering practice. The dimensions of algebraic expressions
20242 (including powers with static exponents) are computed from their constituents.
20243
20244 This feature depends on Ada 2012 aspect specifications, and is available from
20245 version 7.0.1 of GNAT onwards.
20246 The GNAT-specific aspect @code{Dimension_System}
20247 @cindex @code{Dimension_System} aspect
20248 allows you to define a system of units; the aspect @code{Dimension}
20249 @cindex @code{Dimension} aspect
20250 then allows the user to declare dimensioned quantities within a given system.
20251 (These aspects are described in the @i{Implementation Defined Aspects}
20252 chapter of the @i{GNAT Reference Manual}).
20253
20254 The major advantage of this model is that it does not require the declaration of
20255 multiple operators for all possible combinations of types: it is only necessary
20256 to use the proper subtypes in object declarations.
20257
20258 The simplest way to impose dimensionality checking on a computation is to make
20259 use of the package @code{System.Dim.Mks},
20260 @cindex @code{System.Dim.Mks} package (GNAT library)
20261 which is part of the GNAT library. This
20262 package defines a floating-point type @code{MKS_Type},
20263 @cindex @code{MKS_Type} type
20264 for which a sequence of
20265 dimension names are specified, together with their conventional abbreviations.
20266 The following should be read together with the full specification of the
20267 package, in file @file{s-dimmks.ads}.
20268 @cindex @file{s-dimmks.ads} file
20269
20270 @smallexample @c ada
20271 @group
20272 type Mks_Type is new Long_Long_Float
20273 with
20274 Dimension_System => (
20275 (Unit_Name => Meter, Unit_Symbol => 'm', Dim_Symbol => 'L'),
20276 (Unit_Name => Kilogram, Unit_Symbol => "kg", Dim_Symbol => 'M'),
20277 (Unit_Name => Second, Unit_Symbol => 's', Dim_Symbol => 'T'),
20278 (Unit_Name => Ampere, Unit_Symbol => 'A', Dim_Symbol => 'I'),
20279 (Unit_Name => Kelvin, Unit_Symbol => 'K', Dim_Symbol => "Theta"),
20280 (Unit_Name => Mole, Unit_Symbol => "mol", Dim_Symbol => 'N'),
20281 (Unit_Name => Candela, Unit_Symbol => "cd", Dim_Symbol => 'J'));
20282 @end group
20283 @end smallexample
20284
20285 @noindent
20286 The package then defines a series of subtypes that correspond to these
20287 conventional units. For example:
20288
20289 @smallexample @c ada
20290 @group
20291 subtype Length is Mks_Type
20292 with
20293 Dimension => (Symbol => 'm', Meter => 1, others => 0);
20294 @end group
20295 @end smallexample
20296
20297 @noindent
20298 and similarly for @code{Mass}, @code{Time}, @code{Electric_Current},
20299 @code{Thermodynamic_Temperature}, @code{Amount_Of_Substance}, and
20300 @code{Luminous_Intensity} (the standard set of units of the SI system).
20301
20302 The package also defines conventional names for values of each unit, for
20303 example:
20304
20305 @smallexample @c ada
20306 @group
20307 m : constant Length := 1.0;
20308 kg : constant Mass := 1.0;
20309 s : constant Time := 1.0;
20310 A : constant Electric_Current := 1.0;
20311 @end group
20312 @end smallexample
20313
20314 @noindent
20315 as well as useful multiples of these units:
20316
20317 @smallexample @c ada
20318 @group
20319 cm : constant Length := 1.0E-02;
20320 g : constant Mass := 1.0E-03;
20321 min : constant Time := 60.0;
20322 day : constant Time := 60.0 * 24.0 * min;
20323 ...
20324 @end group
20325 @end smallexample
20326
20327 @noindent
20328 Using this package, you can then define a derived unit by
20329 providing the aspect that
20330 specifies its dimensions within the MKS system, as well as the string to
20331 be used for output of a value of that unit:
20332
20333 @smallexample @c ada
20334 @group
20335 subtype Acceleration is Mks_Type
20336 with Dimension => ("m/sec^^^2",
20337 Meter => 1,
20338 Second => -2,
20339 others => 0);
20340 @end group
20341 @end smallexample
20342
20343 @noindent
20344 Here is a complete example of use:
20345
20346 @smallexample @c ada
20347 @group
20348 with System.Dim.MKS; use System.Dim.Mks;
20349 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
20350 with Text_IO; use Text_IO;
20351 procedure Free_Fall is
20352 subtype Acceleration is Mks_Type
20353 with Dimension => ("m/sec^^^2", 1, 0, -2, others => 0);
20354 G : constant acceleration := 9.81 * m / (s ** 2);
20355 T : Time := 10.0*s;
20356 Distance : Length;
20357 @end group
20358 @group
20359 begin
20360 Put ("Gravitational constant: ");
20361 Put (G, Aft => 2, Exp => 0); Put_Line ("");
20362 Distance := 0.5 * G * T ** 2;
20363 Put ("distance travelled in 10 seconds of free fall ");
20364 Put (Distance, Aft => 2, Exp => 0);
20365 Put_Line ("");
20366 end Free_Fall;
20367 @end group
20368 @end smallexample
20369
20370 @noindent
20371 Execution of this program yields:
20372 @smallexample
20373 @group
20374 Gravitational constant: 9.81 m/sec^^^2
20375 distance travelled in 10 seconds of free fall 490.50 m
20376 @end group
20377 @end smallexample
20378
20379 @noindent
20380 However, incorrect assignments such as:
20381
20382 @smallexample @c ada
20383 @group
20384 Distance := 5.0;
20385 Distance := 5.0 * kg:
20386 @end group
20387 @end smallexample
20388
20389 @noindent
20390 are rejected with the following diagnoses:
20391
20392 @smallexample
20393 @group
20394 Distance := 5.0;
20395 >>> dimensions mismatch in assignment
20396 >>> left-hand side has dimension [L]
20397 >>> right-hand side is dimensionless
20398 @end group
20399
20400 @group
20401 Distance := 5.0 * kg:
20402 >>> dimensions mismatch in assignment
20403 >>> left-hand side has dimension [L]
20404 >>> right-hand side has dimension [M]
20405 @end group
20406 @end smallexample
20407
20408 @noindent
20409 The dimensions of an expression are properly displayed, even if there is
20410 no explicit subtype for it. If we add to the program:
20411
20412 @smallexample @c ada
20413 @group
20414 Put ("Final velocity: ");
20415 Put (G * T, Aft =>2, Exp =>0);
20416 Put_Line ("");
20417 @end group
20418 @end smallexample
20419
20420 @noindent
20421 then the output includes:
20422 @smallexample
20423 Final velocity: 98.10 m.s**(-1)
20424 @end smallexample
20425
20426
20427 @c *********************************
20428 @node Generating Ada Bindings for C and C++ headers
20429 @chapter Generating Ada Bindings for C and C++ headers
20430 @findex binding
20431
20432 @noindent
20433 GNAT now comes with a binding generator for C and C++ headers which is
20434 intended to do 95% of the tedious work of generating Ada specs from C
20435 or C++ header files.
20436
20437 Note that this capability is not intended to generate 100% correct Ada specs,
20438 and will is some cases require manual adjustments, although it can often
20439 be used out of the box in practice.
20440
20441 Some of the known limitations include:
20442
20443 @itemize @bullet
20444 @item only very simple character constant macros are translated into Ada
20445 constants. Function macros (macros with arguments) are partially translated
20446 as comments, to be completed manually if needed.
20447 @item some extensions (e.g. vector types) are not supported
20448 @item pointers to pointers or complex structures are mapped to System.Address
20449 @item identifiers with identical name (except casing) will generate compilation
20450 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
20451 @end itemize
20452
20453 The code generated is using the Ada 2005 syntax, which makes it
20454 easier to interface with other languages than previous versions of Ada.
20455
20456 @menu
20457 * Running the binding generator::
20458 * Generating bindings for C++ headers::
20459 * Switches::
20460 @end menu
20461
20462 @node Running the binding generator
20463 @section Running the binding generator
20464
20465 @noindent
20466 The binding generator is part of the @command{gcc} compiler and can be
20467 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
20468 spec files for the header files specified on the command line, and all
20469 header files needed by these files transitively. For example:
20470
20471 @smallexample
20472 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
20473 $ gcc -c -gnat05 *.ads
20474 @end smallexample
20475
20476 will generate, under GNU/Linux, the following files: @file{time_h.ads},
20477 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
20478 correspond to the files @file{/usr/include/time.h},
20479 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
20480 mode these Ada specs.
20481
20482 The @code{-C} switch tells @command{gcc} to extract comments from headers,
20483 and will attempt to generate corresponding Ada comments.
20484
20485 If you want to generate a single Ada file and not the transitive closure, you
20486 can use instead the @option{-fdump-ada-spec-slim} switch.
20487
20488 You can optionally specify a parent unit, of which all generated units will
20489 be children, using @code{-fada-spec-parent=}@var{unit}.
20490
20491 Note that we recommend when possible to use the @command{g++} driver to
20492 generate bindings, even for most C headers, since this will in general
20493 generate better Ada specs. For generating bindings for C++ headers, it is
20494 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
20495 is equivalent in this case. If @command{g++} cannot work on your C headers
20496 because of incompatibilities between C and C++, then you can fallback to
20497 @command{gcc} instead.
20498
20499 For an example of better bindings generated from the C++ front-end,
20500 the name of the parameters (when available) are actually ignored by the C
20501 front-end. Consider the following C header:
20502
20503 @smallexample
20504 extern void foo (int variable);
20505 @end smallexample
20506
20507 with the C front-end, @code{variable} is ignored, and the above is handled as:
20508
20509 @smallexample
20510 extern void foo (int);
20511 @end smallexample
20512
20513 generating a generic:
20514
20515 @smallexample
20516 procedure foo (param1 : int);
20517 @end smallexample
20518
20519 with the C++ front-end, the name is available, and we generate:
20520
20521 @smallexample
20522 procedure foo (variable : int);
20523 @end smallexample
20524
20525 In some cases, the generated bindings will be more complete or more meaningful
20526 when defining some macros, which you can do via the @option{-D} switch. This
20527 is for example the case with @file{Xlib.h} under GNU/Linux:
20528
20529 @smallexample
20530 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
20531 @end smallexample
20532
20533 The above will generate more complete bindings than a straight call without
20534 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
20535
20536 In other cases, it is not possible to parse a header file in a stand-alone
20537 manner, because other include files need to be included first. In this
20538 case, the solution is to create a small header file including the needed
20539 @code{#include} and possible @code{#define} directives. For example, to
20540 generate Ada bindings for @file{readline/readline.h}, you need to first
20541 include @file{stdio.h}, so you can create a file with the following two
20542 lines in e.g. @file{readline1.h}:
20543
20544 @smallexample
20545 #include <stdio.h>
20546 #include <readline/readline.h>
20547 @end smallexample
20548
20549 and then generate Ada bindings from this file:
20550
20551 @smallexample
20552 $ g++ -c -fdump-ada-spec readline1.h
20553 @end smallexample
20554
20555 @node Generating bindings for C++ headers
20556 @section Generating bindings for C++ headers
20557
20558 @noindent
20559 Generating bindings for C++ headers is done using the same options, always
20560 with the @command{g++} compiler.
20561
20562 In this mode, C++ classes will be mapped to Ada tagged types, constructors
20563 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
20564 multiple inheritance of abstract classes will be mapped to Ada interfaces
20565 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
20566 information on interfacing to C++).
20567
20568 For example, given the following C++ header file:
20569
20570 @smallexample
20571 @group
20572 @cartouche
20573 class Carnivore @{
20574 public:
20575 virtual int Number_Of_Teeth () = 0;
20576 @};
20577
20578 class Domestic @{
20579 public:
20580 virtual void Set_Owner (char* Name) = 0;
20581 @};
20582
20583 class Animal @{
20584 public:
20585 int Age_Count;
20586 virtual void Set_Age (int New_Age);
20587 @};
20588
20589 class Dog : Animal, Carnivore, Domestic @{
20590 public:
20591 int Tooth_Count;
20592 char *Owner;
20593
20594 virtual int Number_Of_Teeth ();
20595 virtual void Set_Owner (char* Name);
20596
20597 Dog();
20598 @};
20599 @end cartouche
20600 @end group
20601 @end smallexample
20602
20603 The corresponding Ada code is generated:
20604
20605 @smallexample @c ada
20606 @group
20607 @cartouche
20608 package Class_Carnivore is
20609 type Carnivore is limited interface;
20610 pragma Import (CPP, Carnivore);
20611
20612 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
20613 end;
20614 use Class_Carnivore;
20615
20616 package Class_Domestic is
20617 type Domestic is limited interface;
20618 pragma Import (CPP, Domestic);
20619
20620 procedure Set_Owner
20621 (this : access Domestic;
20622 Name : Interfaces.C.Strings.chars_ptr) is abstract;
20623 end;
20624 use Class_Domestic;
20625
20626 package Class_Animal is
20627 type Animal is tagged limited record
20628 Age_Count : aliased int;
20629 end record;
20630 pragma Import (CPP, Animal);
20631
20632 procedure Set_Age (this : access Animal; New_Age : int);
20633 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
20634 end;
20635 use Class_Animal;
20636
20637 package Class_Dog is
20638 type Dog is new Animal and Carnivore and Domestic with record
20639 Tooth_Count : aliased int;
20640 Owner : Interfaces.C.Strings.chars_ptr;
20641 end record;
20642 pragma Import (CPP, Dog);
20643
20644 function Number_Of_Teeth (this : access Dog) return int;
20645 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
20646
20647 procedure Set_Owner
20648 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
20649 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
20650
20651 function New_Dog return Dog;
20652 pragma CPP_Constructor (New_Dog);
20653 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
20654 end;
20655 use Class_Dog;
20656 @end cartouche
20657 @end group
20658 @end smallexample
20659
20660 @node Switches
20661 @section Switches
20662
20663 @table @option
20664 @item -fdump-ada-spec
20665 @cindex @option{-fdump-ada-spec} (@command{gcc})
20666 Generate Ada spec files for the given header files transitively (including
20667 all header files that these headers depend upon).
20668
20669 @item -fdump-ada-spec-slim
20670 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
20671 Generate Ada spec files for the header files specified on the command line
20672 only.
20673
20674 @item -fada-spec-parent=@var{unit}
20675 @cindex -fada-spec-parent (@command{gcc})
20676 Specifies that all files generated by @option{-fdump-ada-spec*} are
20677 to be child units of the specified parent unit.
20678
20679 @item -C
20680 @cindex @option{-C} (@command{gcc})
20681 Extract comments from headers and generate Ada comments in the Ada spec files.
20682 @end table
20683
20684 @node Other Utility Programs
20685 @chapter Other Utility Programs
20686
20687 @noindent
20688 This chapter discusses some other utility programs available in the Ada
20689 environment.
20690
20691 @menu
20692 * Using Other Utility Programs with GNAT::
20693 * The External Symbol Naming Scheme of GNAT::
20694 * Converting Ada Files to html with gnathtml::
20695 * Installing gnathtml::
20696 @ifset vms
20697 * LSE::
20698 * Profiling::
20699 @end ifset
20700 @end menu
20701
20702 @node Using Other Utility Programs with GNAT
20703 @section Using Other Utility Programs with GNAT
20704
20705 @noindent
20706 The object files generated by GNAT are in standard system format and in
20707 particular the debugging information uses this format. This means
20708 programs generated by GNAT can be used with existing utilities that
20709 depend on these formats.
20710
20711 @ifclear vms
20712 In general, any utility program that works with C will also often work with
20713 Ada programs generated by GNAT. This includes software utilities such as
20714 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
20715 as Purify.
20716 @end ifclear
20717
20718 @node The External Symbol Naming Scheme of GNAT
20719 @section The External Symbol Naming Scheme of GNAT
20720
20721 @noindent
20722 In order to interpret the output from GNAT, when using tools that are
20723 originally intended for use with other languages, it is useful to
20724 understand the conventions used to generate link names from the Ada
20725 entity names.
20726
20727 All link names are in all lowercase letters. With the exception of library
20728 procedure names, the mechanism used is simply to use the full expanded
20729 Ada name with dots replaced by double underscores. For example, suppose
20730 we have the following package spec:
20731
20732 @smallexample @c ada
20733 @group
20734 @cartouche
20735 package QRS is
20736 MN : Integer;
20737 end QRS;
20738 @end cartouche
20739 @end group
20740 @end smallexample
20741
20742 @noindent
20743 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
20744 the corresponding link name is @code{qrs__mn}.
20745 @findex Export
20746 Of course if a @code{pragma Export} is used this may be overridden:
20747
20748 @smallexample @c ada
20749 @group
20750 @cartouche
20751 package Exports is
20752 Var1 : Integer;
20753 pragma Export (Var1, C, External_Name => "var1_name");
20754 Var2 : Integer;
20755 pragma Export (Var2, C, Link_Name => "var2_link_name");
20756 end Exports;
20757 @end cartouche
20758 @end group
20759 @end smallexample
20760
20761 @noindent
20762 In this case, the link name for @var{Var1} is whatever link name the
20763 C compiler would assign for the C function @var{var1_name}. This typically
20764 would be either @var{var1_name} or @var{_var1_name}, depending on operating
20765 system conventions, but other possibilities exist. The link name for
20766 @var{Var2} is @var{var2_link_name}, and this is not operating system
20767 dependent.
20768
20769 @findex _main
20770 One exception occurs for library level procedures. A potential ambiguity
20771 arises between the required name @code{_main} for the C main program,
20772 and the name we would otherwise assign to an Ada library level procedure
20773 called @code{Main} (which might well not be the main program).
20774
20775 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
20776 names. So if we have a library level procedure such as
20777
20778 @smallexample @c ada
20779 @group
20780 @cartouche
20781 procedure Hello (S : String);
20782 @end cartouche
20783 @end group
20784 @end smallexample
20785
20786 @noindent
20787 the external name of this procedure will be @var{_ada_hello}.
20788
20789
20790 @node Converting Ada Files to html with gnathtml
20791 @section Converting Ada Files to HTML with @code{gnathtml}
20792
20793 @noindent
20794 This @code{Perl} script allows Ada source files to be browsed using
20795 standard Web browsers. For installation procedure, see the section
20796 @xref{Installing gnathtml}.
20797
20798 Ada reserved keywords are highlighted in a bold font and Ada comments in
20799 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
20800 switch to suppress the generation of cross-referencing information, user
20801 defined variables and types will appear in a different color; you will
20802 be able to click on any identifier and go to its declaration.
20803
20804 The command line is as follow:
20805 @smallexample
20806 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
20807 @c Expanding @ovar macro inline (explanation in macro def comments)
20808 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
20809 @end smallexample
20810
20811 @noindent
20812 You can pass it as many Ada files as you want. @code{gnathtml} will generate
20813 an html file for every ada file, and a global file called @file{index.htm}.
20814 This file is an index of every identifier defined in the files.
20815
20816 The available ^switches^options^ are the following ones:
20817
20818 @table @option
20819 @item -83
20820 @cindex @option{-83} (@code{gnathtml})
20821 Only the Ada 83 subset of keywords will be highlighted.
20822
20823 @item -cc @var{color}
20824 @cindex @option{-cc} (@code{gnathtml})
20825 This option allows you to change the color used for comments. The default
20826 value is green. The color argument can be any name accepted by html.
20827
20828 @item -d
20829 @cindex @option{-d} (@code{gnathtml})
20830 If the Ada files depend on some other files (for instance through
20831 @code{with} clauses, the latter files will also be converted to html.
20832 Only the files in the user project will be converted to html, not the files
20833 in the run-time library itself.
20834
20835 @item -D
20836 @cindex @option{-D} (@code{gnathtml})
20837 This command is the same as @option{-d} above, but @command{gnathtml} will
20838 also look for files in the run-time library, and generate html files for them.
20839
20840 @item -ext @var{extension}
20841 @cindex @option{-ext} (@code{gnathtml})
20842 This option allows you to change the extension of the generated HTML files.
20843 If you do not specify an extension, it will default to @file{htm}.
20844
20845 @item -f
20846 @cindex @option{-f} (@code{gnathtml})
20847 By default, gnathtml will generate html links only for global entities
20848 ('with'ed units, global variables and types,@dots{}). If you specify
20849 @option{-f} on the command line, then links will be generated for local
20850 entities too.
20851
20852 @item -l @var{number}
20853 @cindex @option{-l} (@code{gnathtml})
20854 If this ^switch^option^ is provided and @var{number} is not 0, then
20855 @code{gnathtml} will number the html files every @var{number} line.
20856
20857 @item -I @var{dir}
20858 @cindex @option{-I} (@code{gnathtml})
20859 Specify a directory to search for library files (@file{.ALI} files) and
20860 source files. You can provide several -I switches on the command line,
20861 and the directories will be parsed in the order of the command line.
20862
20863 @item -o @var{dir}
20864 @cindex @option{-o} (@code{gnathtml})
20865 Specify the output directory for html files. By default, gnathtml will
20866 saved the generated html files in a subdirectory named @file{html/}.
20867
20868 @item -p @var{file}
20869 @cindex @option{-p} (@code{gnathtml})
20870 If you are using Emacs and the most recent Emacs Ada mode, which provides
20871 a full Integrated Development Environment for compiling, checking,
20872 running and debugging applications, you may use @file{.gpr} files
20873 to give the directories where Emacs can find sources and object files.
20874
20875 Using this ^switch^option^, you can tell gnathtml to use these files.
20876 This allows you to get an html version of your application, even if it
20877 is spread over multiple directories.
20878
20879 @item -sc @var{color}
20880 @cindex @option{-sc} (@code{gnathtml})
20881 This ^switch^option^ allows you to change the color used for symbol
20882 definitions.
20883 The default value is red. The color argument can be any name accepted by html.
20884
20885 @item -t @var{file}
20886 @cindex @option{-t} (@code{gnathtml})
20887 This ^switch^option^ provides the name of a file. This file contains a list of
20888 file names to be converted, and the effect is exactly as though they had
20889 appeared explicitly on the command line. This
20890 is the recommended way to work around the command line length limit on some
20891 systems.
20892
20893 @end table
20894
20895 @node Installing gnathtml
20896 @section Installing @code{gnathtml}
20897
20898 @noindent
20899 @code{Perl} needs to be installed on your machine to run this script.
20900 @code{Perl} is freely available for almost every architecture and
20901 Operating System via the Internet.
20902
20903 On Unix systems, you may want to modify the first line of the script
20904 @code{gnathtml}, to explicitly tell the Operating system where Perl
20905 is. The syntax of this line is:
20906 @smallexample
20907 #!full_path_name_to_perl
20908 @end smallexample
20909
20910 @noindent
20911 Alternatively, you may run the script using the following command line:
20912
20913 @smallexample
20914 @c $ perl gnathtml.pl @ovar{switches} @var{files}
20915 @c Expanding @ovar macro inline (explanation in macro def comments)
20916 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
20917 @end smallexample
20918
20919 @ifset vms
20920 @node LSE
20921 @section LSE
20922 @findex LSE
20923
20924 @noindent
20925 The GNAT distribution provides an Ada 95 template for the HP Language
20926 Sensitive Editor (LSE), a component of DECset. In order to
20927 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
20928
20929 @node Profiling
20930 @section Profiling
20931 @findex PCA
20932
20933 @noindent
20934 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
20935 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
20936 the collection phase with the /DEBUG qualifier.
20937
20938 @smallexample
20939 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
20940 $ DEFINE LIB$DEBUG PCA$COLLECTOR
20941 $ RUN/DEBUG <PROGRAM_NAME>
20942 @end smallexample
20943 @noindent
20944 @end ifset
20945
20946 @ifclear vms
20947 @c ******************************
20948 @node Code Coverage and Profiling
20949 @chapter Code Coverage and Profiling
20950 @cindex Code Coverage
20951 @cindex Profiling
20952
20953 @noindent
20954 This chapter describes how to use @code{gcov} - coverage testing tool - and
20955 @code{gprof} - profiler tool - on your Ada programs.
20956
20957 @menu
20958 * Code Coverage of Ada Programs with gcov::
20959 * Profiling an Ada Program with gprof::
20960 @end menu
20961
20962 @node Code Coverage of Ada Programs with gcov
20963 @section Code Coverage of Ada Programs with gcov
20964 @cindex gcov
20965 @cindex -fprofile-arcs
20966 @cindex -ftest-coverage
20967 @cindex -coverage
20968 @cindex Code Coverage
20969
20970 @noindent
20971 @code{gcov} is a test coverage program: it analyzes the execution of a given
20972 program on selected tests, to help you determine the portions of the program
20973 that are still untested.
20974
20975 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
20976 User's Guide. You can refer to this documentation for a more complete
20977 description.
20978
20979 This chapter provides a quick startup guide, and
20980 details some Gnat-specific features.
20981
20982 @menu
20983 * Quick startup guide::
20984 * Gnat specifics::
20985 @end menu
20986
20987 @node Quick startup guide
20988 @subsection Quick startup guide
20989
20990 In order to perform coverage analysis of a program using @code{gcov}, 3
20991 steps are needed:
20992
20993 @itemize @bullet
20994 @item
20995 Code instrumentation during the compilation process
20996 @item
20997 Execution of the instrumented program
20998 @item
20999 Execution of the @code{gcov} tool to generate the result.
21000 @end itemize
21001
21002 The code instrumentation needed by gcov is created at the object level:
21003 The source code is not modified in any way, because the instrumentation code is
21004 inserted by gcc during the compilation process. To compile your code with code
21005 coverage activated, you need to recompile your whole project using the
21006 switches
21007 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
21008 @code{-fprofile-arcs}.
21009
21010 @smallexample
21011 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
21012 -largs -fprofile-arcs
21013 @end smallexample
21014
21015 This compilation process will create @file{.gcno} files together with
21016 the usual object files.
21017
21018 Once the program is compiled with coverage instrumentation, you can
21019 run it as many times as needed - on portions of a test suite for
21020 example. The first execution will produce @file{.gcda} files at the
21021 same location as the @file{.gcno} files. The following executions
21022 will update those files, so that a cumulative result of the covered
21023 portions of the program is generated.
21024
21025 Finally, you need to call the @code{gcov} tool. The different options of
21026 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
21027
21028 This will create annotated source files with a @file{.gcov} extension:
21029 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
21030
21031 @node Gnat specifics
21032 @subsection Gnat specifics
21033
21034 Because Ada semantics, portions of the source code may be shared among
21035 several object files. This is the case for example when generics are
21036 involved, when inlining is active or when declarations generate initialisation
21037 calls. In order to take
21038 into account this shared code, you need to call @code{gcov} on all
21039 source files of the tested program at once.
21040
21041 The list of source files might exceed the system's maximum command line
21042 length. In order to bypass this limitation, a new mechanism has been
21043 implemented in @code{gcov}: you can now list all your project's files into a
21044 text file, and provide this file to gcov as a parameter, preceded by a @@
21045 (e.g. @samp{gcov @@mysrclist.txt}).
21046
21047 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
21048 not supported as there can be unresolved symbols during the final link.
21049
21050 @node Profiling an Ada Program with gprof
21051 @section Profiling an Ada Program with gprof
21052 @cindex gprof
21053 @cindex -pg
21054 @cindex Profiling
21055
21056 @noindent
21057 This section is not meant to be an exhaustive documentation of @code{gprof}.
21058 Full documentation for it can be found in the GNU Profiler User's Guide
21059 documentation that is part of this GNAT distribution.
21060
21061 Profiling a program helps determine the parts of a program that are executed
21062 most often, and are therefore the most time-consuming.
21063
21064 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
21065 better handle Ada programs and multitasking.
21066 It is currently supported on the following platforms
21067 @itemize @bullet
21068 @item
21069 linux x86/x86_64
21070 @item
21071 solaris sparc/sparc64/x86
21072 @item
21073 windows x86
21074 @end itemize
21075
21076 @noindent
21077 In order to profile a program using @code{gprof}, 3 steps are needed:
21078
21079 @itemize @bullet
21080 @item
21081 Code instrumentation, requiring a full recompilation of the project with the
21082 proper switches.
21083 @item
21084 Execution of the program under the analysis conditions, i.e. with the desired
21085 input.
21086 @item
21087 Analysis of the results using the @code{gprof} tool.
21088 @end itemize
21089
21090 @noindent
21091 The following sections detail the different steps, and indicate how
21092 to interpret the results:
21093 @menu
21094 * Compilation for profiling::
21095 * Program execution::
21096 * Running gprof::
21097 * Interpretation of profiling results::
21098 @end menu
21099
21100 @node Compilation for profiling
21101 @subsection Compilation for profiling
21102 @cindex -pg
21103 @cindex Profiling
21104
21105 In order to profile a program the first step is to tell the compiler
21106 to generate the necessary profiling information. The compiler switch to be used
21107 is @code{-pg}, which must be added to other compilation switches. This
21108 switch needs to be specified both during compilation and link stages, and can
21109 be specified once when using gnatmake:
21110
21111 @smallexample
21112 gnatmake -f -pg -P my_project
21113 @end smallexample
21114
21115 @noindent
21116 Note that only the objects that were compiled with the @samp{-pg} switch will
21117 be profiled; if you need to profile your whole project, use the @samp{-f}
21118 gnatmake switch to force full recompilation.
21119
21120 @node Program execution
21121 @subsection Program execution
21122
21123 @noindent
21124 Once the program has been compiled for profiling, you can run it as usual.
21125
21126 The only constraint imposed by profiling is that the program must terminate
21127 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
21128 properly analyzed.
21129
21130 Once the program completes execution, a data file called @file{gmon.out} is
21131 generated in the directory where the program was launched from. If this file
21132 already exists, it will be overwritten.
21133
21134 @node Running gprof
21135 @subsection Running gprof
21136
21137 @noindent
21138 The @code{gprof} tool is called as follow:
21139
21140 @smallexample
21141 gprof my_prog gmon.out
21142 @end smallexample
21143
21144 @noindent
21145 or simpler:
21146
21147 @smallexample
21148 gprof my_prog
21149 @end smallexample
21150
21151 @noindent
21152 The complete form of the gprof command line is the following:
21153
21154 @smallexample
21155 gprof [^switches^options^] [executable [data-file]]
21156 @end smallexample
21157
21158 @noindent
21159 @code{gprof} supports numerous ^switch^options^. The order of these
21160 ^switch^options^ does not matter. The full list of options can be found in
21161 the GNU Profiler User's Guide documentation that comes with this documentation.
21162
21163 The following is the subset of those switches that is most relevant:
21164
21165 @table @option
21166
21167 @item --demangle[=@var{style}]
21168 @itemx --no-demangle
21169 @cindex @option{--demangle} (@code{gprof})
21170 These options control whether symbol names should be demangled when
21171 printing output. The default is to demangle C++ symbols. The
21172 @code{--no-demangle} option may be used to turn off demangling. Different
21173 compilers have different mangling styles. The optional demangling style
21174 argument can be used to choose an appropriate demangling style for your
21175 compiler, in particular Ada symbols generated by GNAT can be demangled using
21176 @code{--demangle=gnat}.
21177
21178 @item -e @var{function_name}
21179 @cindex @option{-e} (@code{gprof})
21180 The @samp{-e @var{function}} option tells @code{gprof} not to print
21181 information about the function @var{function_name} (and its
21182 children@dots{}) in the call graph. The function will still be listed
21183 as a child of any functions that call it, but its index number will be
21184 shown as @samp{[not printed]}. More than one @samp{-e} option may be
21185 given; only one @var{function_name} may be indicated with each @samp{-e}
21186 option.
21187
21188 @item -E @var{function_name}
21189 @cindex @option{-E} (@code{gprof})
21190 The @code{-E @var{function}} option works like the @code{-e} option, but
21191 execution time spent in the function (and children who were not called from
21192 anywhere else), will not be used to compute the percentages-of-time for
21193 the call graph. More than one @samp{-E} option may be given; only one
21194 @var{function_name} may be indicated with each @samp{-E} option.
21195
21196 @item -f @var{function_name}
21197 @cindex @option{-f} (@code{gprof})
21198 The @samp{-f @var{function}} option causes @code{gprof} to limit the
21199 call graph to the function @var{function_name} and its children (and
21200 their children@dots{}). More than one @samp{-f} option may be given;
21201 only one @var{function_name} may be indicated with each @samp{-f}
21202 option.
21203
21204 @item -F @var{function_name}
21205 @cindex @option{-F} (@code{gprof})
21206 The @samp{-F @var{function}} option works like the @code{-f} option, but
21207 only time spent in the function and its children (and their
21208 children@dots{}) will be used to determine total-time and
21209 percentages-of-time for the call graph. More than one @samp{-F} option
21210 may be given; only one @var{function_name} may be indicated with each
21211 @samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.
21212
21213 @end table
21214
21215 @node Interpretation of profiling results
21216 @subsection Interpretation of profiling results
21217
21218 @noindent
21219
21220 The results of the profiling analysis are represented by two arrays: the
21221 'flat profile' and the 'call graph'. Full documentation of those outputs
21222 can be found in the GNU Profiler User's Guide.
21223
21224 The flat profile shows the time spent in each function of the program, and how
21225 many time it has been called. This allows you to locate easily the most
21226 time-consuming functions.
21227
21228 The call graph shows, for each subprogram, the subprograms that call it,
21229 and the subprograms that it calls. It also provides an estimate of the time
21230 spent in each of those callers/called subprograms.
21231 @end ifclear
21232
21233 @c ******************************
21234 @node Running and Debugging Ada Programs
21235 @chapter Running and Debugging Ada Programs
21236 @cindex Debugging
21237
21238 @noindent
21239 This chapter discusses how to debug Ada programs.
21240 @ifset vms
21241 It applies to GNAT on the Alpha OpenVMS platform;
21242 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
21243 since HP has implemented Ada support in the OpenVMS debugger on I64.
21244 @end ifset
21245
21246 An incorrect Ada program may be handled in three ways by the GNAT compiler:
21247
21248 @enumerate
21249 @item
21250 The illegality may be a violation of the static semantics of Ada. In
21251 that case GNAT diagnoses the constructs in the program that are illegal.
21252 It is then a straightforward matter for the user to modify those parts of
21253 the program.
21254
21255 @item
21256 The illegality may be a violation of the dynamic semantics of Ada. In
21257 that case the program compiles and executes, but may generate incorrect
21258 results, or may terminate abnormally with some exception.
21259
21260 @item
21261 When presented with a program that contains convoluted errors, GNAT
21262 itself may terminate abnormally without providing full diagnostics on
21263 the incorrect user program.
21264 @end enumerate
21265
21266 @menu
21267 * The GNAT Debugger GDB::
21268 * Running GDB::
21269 * Introduction to GDB Commands::
21270 * Using Ada Expressions::
21271 * Calling User-Defined Subprograms::
21272 * Using the Next Command in a Function::
21273 * Ada Exceptions::
21274 * Ada Tasks::
21275 * Debugging Generic Units::
21276 * Remote Debugging with gdbserver::
21277 * GNAT Abnormal Termination or Failure to Terminate::
21278 * Naming Conventions for GNAT Source Files::
21279 * Getting Internal Debugging Information::
21280 * Stack Traceback::
21281 @end menu
21282
21283 @cindex Debugger
21284 @findex gdb
21285
21286 @node The GNAT Debugger GDB
21287 @section The GNAT Debugger GDB
21288
21289 @noindent
21290 @code{GDB} is a general purpose, platform-independent debugger that
21291 can be used to debug mixed-language programs compiled with @command{gcc},
21292 and in particular is capable of debugging Ada programs compiled with
21293 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
21294 complex Ada data structures.
21295
21296 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
21297 @ifset vms
21298 located in the GNU:[DOCS] directory,
21299 @end ifset
21300 for full details on the usage of @code{GDB}, including a section on
21301 its usage on programs. This manual should be consulted for full
21302 details. The section that follows is a brief introduction to the
21303 philosophy and use of @code{GDB}.
21304
21305 When GNAT programs are compiled, the compiler optionally writes debugging
21306 information into the generated object file, including information on
21307 line numbers, and on declared types and variables. This information is
21308 separate from the generated code. It makes the object files considerably
21309 larger, but it does not add to the size of the actual executable that
21310 will be loaded into memory, and has no impact on run-time performance. The
21311 generation of debug information is triggered by the use of the
21312 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
21313 used to carry out the compilations. It is important to emphasize that
21314 the use of these options does not change the generated code.
21315
21316 The debugging information is written in standard system formats that
21317 are used by many tools, including debuggers and profilers. The format
21318 of the information is typically designed to describe C types and
21319 semantics, but GNAT implements a translation scheme which allows full
21320 details about Ada types and variables to be encoded into these
21321 standard C formats. Details of this encoding scheme may be found in
21322 the file exp_dbug.ads in the GNAT source distribution. However, the
21323 details of this encoding are, in general, of no interest to a user,
21324 since @code{GDB} automatically performs the necessary decoding.
21325
21326 When a program is bound and linked, the debugging information is
21327 collected from the object files, and stored in the executable image of
21328 the program. Again, this process significantly increases the size of
21329 the generated executable file, but it does not increase the size of
21330 the executable program itself. Furthermore, if this program is run in
21331 the normal manner, it runs exactly as if the debug information were
21332 not present, and takes no more actual memory.
21333
21334 However, if the program is run under control of @code{GDB}, the
21335 debugger is activated. The image of the program is loaded, at which
21336 point it is ready to run. If a run command is given, then the program
21337 will run exactly as it would have if @code{GDB} were not present. This
21338 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
21339 entirely non-intrusive until a breakpoint is encountered. If no
21340 breakpoint is ever hit, the program will run exactly as it would if no
21341 debugger were present. When a breakpoint is hit, @code{GDB} accesses
21342 the debugging information and can respond to user commands to inspect
21343 variables, and more generally to report on the state of execution.
21344
21345 @c **************
21346 @node Running GDB
21347 @section Running GDB
21348
21349 @noindent
21350 This section describes how to initiate the debugger.
21351 @c The above sentence is really just filler, but it was otherwise
21352 @c clumsy to get the first paragraph nonindented given the conditional
21353 @c nature of the description
21354
21355 @ifclear vms
21356 The debugger can be launched from a @code{GPS} menu or
21357 directly from the command line. The description below covers the latter use.
21358 All the commands shown can be used in the @code{GPS} debug console window,
21359 but there are usually more GUI-based ways to achieve the same effect.
21360 @end ifclear
21361
21362 The command to run @code{GDB} is
21363
21364 @smallexample
21365 $ ^gdb program^GDB PROGRAM^
21366 @end smallexample
21367
21368 @noindent
21369 where @code{^program^PROGRAM^} is the name of the executable file. This
21370 activates the debugger and results in a prompt for debugger commands.
21371 The simplest command is simply @code{run}, which causes the program to run
21372 exactly as if the debugger were not present. The following section
21373 describes some of the additional commands that can be given to @code{GDB}.
21374
21375 @c *******************************
21376 @node Introduction to GDB Commands
21377 @section Introduction to GDB Commands
21378
21379 @noindent
21380 @code{GDB} contains a large repertoire of commands. @xref{Top,,
21381 Debugging with GDB, gdb, Debugging with GDB},
21382 @ifset vms
21383 located in the GNU:[DOCS] directory,
21384 @end ifset
21385 for extensive documentation on the use
21386 of these commands, together with examples of their use. Furthermore,
21387 the command @command{help} invoked from within GDB activates a simple help
21388 facility which summarizes the available commands and their options.
21389 In this section we summarize a few of the most commonly
21390 used commands to give an idea of what @code{GDB} is about. You should create
21391 a simple program with debugging information and experiment with the use of
21392 these @code{GDB} commands on the program as you read through the
21393 following section.
21394
21395 @table @code
21396 @item set args @var{arguments}
21397 The @var{arguments} list above is a list of arguments to be passed to
21398 the program on a subsequent run command, just as though the arguments
21399 had been entered on a normal invocation of the program. The @code{set args}
21400 command is not needed if the program does not require arguments.
21401
21402 @item run
21403 The @code{run} command causes execution of the program to start from
21404 the beginning. If the program is already running, that is to say if
21405 you are currently positioned at a breakpoint, then a prompt will ask
21406 for confirmation that you want to abandon the current execution and
21407 restart.
21408
21409 @item breakpoint @var{location}
21410 The breakpoint command sets a breakpoint, that is to say a point at which
21411 execution will halt and @code{GDB} will await further
21412 commands. @var{location} is
21413 either a line number within a file, given in the format @code{file:linenumber},
21414 or it is the name of a subprogram. If you request that a breakpoint be set on
21415 a subprogram that is overloaded, a prompt will ask you to specify on which of
21416 those subprograms you want to breakpoint. You can also
21417 specify that all of them should be breakpointed. If the program is run
21418 and execution encounters the breakpoint, then the program
21419 stops and @code{GDB} signals that the breakpoint was encountered by
21420 printing the line of code before which the program is halted.
21421
21422 @item catch exception @var{name}
21423 This command causes the program execution to stop whenever exception
21424 @var{name} is raised. If @var{name} is omitted, then the execution is
21425 suspended when any exception is raised.
21426
21427 @item print @var{expression}
21428 This will print the value of the given expression. Most simple
21429 Ada expression formats are properly handled by @code{GDB}, so the expression
21430 can contain function calls, variables, operators, and attribute references.
21431
21432 @item continue
21433 Continues execution following a breakpoint, until the next breakpoint or the
21434 termination of the program.
21435
21436 @item step
21437 Executes a single line after a breakpoint. If the next statement
21438 is a subprogram call, execution continues into (the first statement of)
21439 the called subprogram.
21440
21441 @item next
21442 Executes a single line. If this line is a subprogram call, executes and
21443 returns from the call.
21444
21445 @item list
21446 Lists a few lines around the current source location. In practice, it
21447 is usually more convenient to have a separate edit window open with the
21448 relevant source file displayed. Successive applications of this command
21449 print subsequent lines. The command can be given an argument which is a
21450 line number, in which case it displays a few lines around the specified one.
21451
21452 @item backtrace
21453 Displays a backtrace of the call chain. This command is typically
21454 used after a breakpoint has occurred, to examine the sequence of calls that
21455 leads to the current breakpoint. The display includes one line for each
21456 activation record (frame) corresponding to an active subprogram.
21457
21458 @item up
21459 At a breakpoint, @code{GDB} can display the values of variables local
21460 to the current frame. The command @code{up} can be used to
21461 examine the contents of other active frames, by moving the focus up
21462 the stack, that is to say from callee to caller, one frame at a time.
21463
21464 @item down
21465 Moves the focus of @code{GDB} down from the frame currently being
21466 examined to the frame of its callee (the reverse of the previous command),
21467
21468 @item frame @var{n}
21469 Inspect the frame with the given number. The value 0 denotes the frame
21470 of the current breakpoint, that is to say the top of the call stack.
21471
21472 @item kill
21473 Kills the child process in which the program is running under GDB.
21474 This may be useful for several purposes:
21475 @itemize @bullet
21476 @item
21477 It allows you to recompile and relink your program, since on many systems
21478 you cannot regenerate an executable file while it is running in a process.
21479 @item
21480 You can run your program outside the debugger, on systems that do not
21481 permit executing a program outside GDB while breakpoints are set
21482 within GDB.
21483 @item
21484 It allows you to debug a core dump rather than a running process.
21485 @end itemize
21486 @end table
21487
21488 @noindent
21489 The above list is a very short introduction to the commands that
21490 @code{GDB} provides. Important additional capabilities, including conditional
21491 breakpoints, the ability to execute command sequences on a breakpoint,
21492 the ability to debug at the machine instruction level and many other
21493 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
21494 Debugging with GDB}. Note that most commands can be abbreviated
21495 (for example, c for continue, bt for backtrace).
21496
21497 @node Using Ada Expressions
21498 @section Using Ada Expressions
21499 @cindex Ada expressions
21500
21501 @noindent
21502 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
21503 extensions. The philosophy behind the design of this subset is
21504
21505 @itemize @bullet
21506 @item
21507 That @code{GDB} should provide basic literals and access to operations for
21508 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
21509 leaving more sophisticated computations to subprograms written into the
21510 program (which therefore may be called from @code{GDB}).
21511
21512 @item
21513 That type safety and strict adherence to Ada language restrictions
21514 are not particularly important to the @code{GDB} user.
21515
21516 @item
21517 That brevity is important to the @code{GDB} user.
21518 @end itemize
21519
21520 @noindent
21521 Thus, for brevity, the debugger acts as if there were
21522 implicit @code{with} and @code{use} clauses in effect for all user-written
21523 packages, thus making it unnecessary to fully qualify most names with
21524 their packages, regardless of context. Where this causes ambiguity,
21525 @code{GDB} asks the user's intent.
21526
21527 For details on the supported Ada syntax, see @ref{Top,, Debugging with
21528 GDB, gdb, Debugging with GDB}.
21529
21530 @node Calling User-Defined Subprograms
21531 @section Calling User-Defined Subprograms
21532
21533 @noindent
21534 An important capability of @code{GDB} is the ability to call user-defined
21535 subprograms while debugging. This is achieved simply by entering
21536 a subprogram call statement in the form:
21537
21538 @smallexample
21539 call subprogram-name (parameters)
21540 @end smallexample
21541
21542 @noindent
21543 The keyword @code{call} can be omitted in the normal case where the
21544 @code{subprogram-name} does not coincide with any of the predefined
21545 @code{GDB} commands.
21546
21547 The effect is to invoke the given subprogram, passing it the
21548 list of parameters that is supplied. The parameters can be expressions and
21549 can include variables from the program being debugged. The
21550 subprogram must be defined
21551 at the library level within your program, and @code{GDB} will call the
21552 subprogram within the environment of your program execution (which
21553 means that the subprogram is free to access or even modify variables
21554 within your program).
21555
21556 The most important use of this facility is in allowing the inclusion of
21557 debugging routines that are tailored to particular data structures
21558 in your program. Such debugging routines can be written to provide a suitably
21559 high-level description of an abstract type, rather than a low-level dump
21560 of its physical layout. After all, the standard
21561 @code{GDB print} command only knows the physical layout of your
21562 types, not their abstract meaning. Debugging routines can provide information
21563 at the desired semantic level and are thus enormously useful.
21564
21565 For example, when debugging GNAT itself, it is crucial to have access to
21566 the contents of the tree nodes used to represent the program internally.
21567 But tree nodes are represented simply by an integer value (which in turn
21568 is an index into a table of nodes).
21569 Using the @code{print} command on a tree node would simply print this integer
21570 value, which is not very useful. But the PN routine (defined in file
21571 treepr.adb in the GNAT sources) takes a tree node as input, and displays
21572 a useful high level representation of the tree node, which includes the
21573 syntactic category of the node, its position in the source, the integers
21574 that denote descendant nodes and parent node, as well as varied
21575 semantic information. To study this example in more detail, you might want to
21576 look at the body of the PN procedure in the stated file.
21577
21578 @node Using the Next Command in a Function
21579 @section Using the Next Command in a Function
21580
21581 @noindent
21582 When you use the @code{next} command in a function, the current source
21583 location will advance to the next statement as usual. A special case
21584 arises in the case of a @code{return} statement.
21585
21586 Part of the code for a return statement is the ``epilog'' of the function.
21587 This is the code that returns to the caller. There is only one copy of
21588 this epilog code, and it is typically associated with the last return
21589 statement in the function if there is more than one return. In some
21590 implementations, this epilog is associated with the first statement
21591 of the function.
21592
21593 The result is that if you use the @code{next} command from a return
21594 statement that is not the last return statement of the function you
21595 may see a strange apparent jump to the last return statement or to
21596 the start of the function. You should simply ignore this odd jump.
21597 The value returned is always that from the first return statement
21598 that was stepped through.
21599
21600 @node Ada Exceptions
21601 @section Stopping when Ada Exceptions are Raised
21602 @cindex Exceptions
21603
21604 @noindent
21605 You can set catchpoints that stop the program execution when your program
21606 raises selected exceptions.
21607
21608 @table @code
21609 @item catch exception
21610 Set a catchpoint that stops execution whenever (any task in the) program
21611 raises any exception.
21612
21613 @item catch exception @var{name}
21614 Set a catchpoint that stops execution whenever (any task in the) program
21615 raises the exception @var{name}.
21616
21617 @item catch exception unhandled
21618 Set a catchpoint that stops executing whenever (any task in the) program
21619 raises an exception for which there is no handler.
21620
21621 @item info exceptions
21622 @itemx info exceptions @var{regexp}
21623 The @code{info exceptions} command permits the user to examine all defined
21624 exceptions within Ada programs. With a regular expression, @var{regexp}, as
21625 argument, prints out only those exceptions whose name matches @var{regexp}.
21626 @end table
21627
21628 @node Ada Tasks
21629 @section Ada Tasks
21630 @cindex Tasks
21631
21632 @noindent
21633 @code{GDB} allows the following task-related commands:
21634
21635 @table @code
21636 @item info tasks
21637 This command shows a list of current Ada tasks, as in the following example:
21638
21639 @smallexample
21640 @iftex
21641 @leftskip=0cm
21642 @end iftex
21643 (gdb) info tasks
21644 ID TID P-ID Thread Pri State Name
21645 1 8088000 0 807e000 15 Child Activation Wait main_task
21646 2 80a4000 1 80ae000 15 Accept/Select Wait b
21647 3 809a800 1 80a4800 15 Child Activation Wait a
21648 * 4 80ae800 3 80b8000 15 Running c
21649 @end smallexample
21650
21651 @noindent
21652 In this listing, the asterisk before the first task indicates it to be the
21653 currently running task. The first column lists the task ID that is used
21654 to refer to tasks in the following commands.
21655
21656 @item break @var{linespec} task @var{taskid}
21657 @itemx break @var{linespec} task @var{taskid} if @dots{}
21658 @cindex Breakpoints and tasks
21659 These commands are like the @code{break @dots{} thread @dots{}}.
21660 @var{linespec} specifies source lines.
21661
21662 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
21663 to specify that you only want @code{GDB} to stop the program when a
21664 particular Ada task reaches this breakpoint. @var{taskid} is one of the
21665 numeric task identifiers assigned by @code{GDB}, shown in the first
21666 column of the @samp{info tasks} display.
21667
21668 If you do not specify @samp{task @var{taskid}} when you set a
21669 breakpoint, the breakpoint applies to @emph{all} tasks of your
21670 program.
21671
21672 You can use the @code{task} qualifier on conditional breakpoints as
21673 well; in this case, place @samp{task @var{taskid}} before the
21674 breakpoint condition (before the @code{if}).
21675
21676 @item task @var{taskno}
21677 @cindex Task switching
21678
21679 This command allows switching to the task referred by @var{taskno}. In
21680 particular, this allows browsing of the backtrace of the specified
21681 task. It is advisable to switch back to the original task before
21682 continuing execution otherwise the scheduling of the program may be
21683 perturbed.
21684 @end table
21685
21686 @noindent
21687 For more detailed information on the tasking support,
21688 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
21689
21690 @node Debugging Generic Units
21691 @section Debugging Generic Units
21692 @cindex Debugging Generic Units
21693 @cindex Generics
21694
21695 @noindent
21696 GNAT always uses code expansion for generic instantiation. This means that
21697 each time an instantiation occurs, a complete copy of the original code is
21698 made, with appropriate substitutions of formals by actuals.
21699
21700 It is not possible to refer to the original generic entities in
21701 @code{GDB}, but it is always possible to debug a particular instance of
21702 a generic, by using the appropriate expanded names. For example, if we have
21703
21704 @smallexample @c ada
21705 @group
21706 @cartouche
21707 procedure g is
21708
21709 generic package k is
21710 procedure kp (v1 : in out integer);
21711 end k;
21712
21713 package body k is
21714 procedure kp (v1 : in out integer) is
21715 begin
21716 v1 := v1 + 1;
21717 end kp;
21718 end k;
21719
21720 package k1 is new k;
21721 package k2 is new k;
21722
21723 var : integer := 1;
21724
21725 begin
21726 k1.kp (var);
21727 k2.kp (var);
21728 k1.kp (var);
21729 k2.kp (var);
21730 end;
21731 @end cartouche
21732 @end group
21733 @end smallexample
21734
21735 @noindent
21736 Then to break on a call to procedure kp in the k2 instance, simply
21737 use the command:
21738
21739 @smallexample
21740 (gdb) break g.k2.kp
21741 @end smallexample
21742
21743 @noindent
21744 When the breakpoint occurs, you can step through the code of the
21745 instance in the normal manner and examine the values of local variables, as for
21746 other units.
21747
21748 @node Remote Debugging with gdbserver
21749 @section Remote Debugging with gdbserver
21750 @cindex Remote Debugging with gdbserver
21751
21752 @noindent
21753 On platforms where gdbserver is supported, it is possible to use this tool
21754 to debug your application remotely. This can be useful in situations
21755 where the program needs to be run on a target host that is different
21756 from the host used for development, particularly when the target has
21757 a limited amount of resources (either CPU and/or memory).
21758
21759 To do so, start your program using gdbserver on the target machine.
21760 gdbserver then automatically suspends the execution of your program
21761 at its entry point, waiting for a debugger to connect to it. The
21762 following commands starts an application and tells gdbserver to
21763 wait for a connection with the debugger on localhost port 4444.
21764
21765 @smallexample
21766 $ gdbserver localhost:4444 program
21767 Process program created; pid = 5685
21768 Listening on port 4444
21769 @end smallexample
21770
21771 Once gdbserver has started listening, we can tell the debugger to establish
21772 a connection with this gdbserver, and then start the same debugging session
21773 as if the program was being debugged on the same host, directly under
21774 the control of GDB.
21775
21776 @smallexample
21777 $ gdb program
21778 (gdb) target remote targethost:4444
21779 Remote debugging using targethost:4444
21780 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
21781 (gdb) b foo.adb:3
21782 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
21783 (gdb) continue
21784 Continuing.
21785
21786 Breakpoint 1, foo () at foo.adb:4
21787 4 end foo;
21788 @end smallexample
21789
21790 It is also possible to use gdbserver to attach to an already running
21791 program, in which case the execution of that program is simply suspended
21792 until the connection between the debugger and gdbserver is established.
21793
21794 For more information on how to use gdbserver, @ref{Top, Server, Using
21795 the gdbserver Program, gdb, Debugging with GDB}. @value{EDITION} provides support
21796 for gdbserver on x86-linux, x86-windows and x86_64-linux.
21797
21798 @node GNAT Abnormal Termination or Failure to Terminate
21799 @section GNAT Abnormal Termination or Failure to Terminate
21800 @cindex GNAT Abnormal Termination or Failure to Terminate
21801
21802 @noindent
21803 When presented with programs that contain serious errors in syntax
21804 or semantics,
21805 GNAT may on rare occasions experience problems in operation, such
21806 as aborting with a
21807 segmentation fault or illegal memory access, raising an internal
21808 exception, terminating abnormally, or failing to terminate at all.
21809 In such cases, you can activate
21810 various features of GNAT that can help you pinpoint the construct in your
21811 program that is the likely source of the problem.
21812
21813 The following strategies are presented in increasing order of
21814 difficulty, corresponding to your experience in using GNAT and your
21815 familiarity with compiler internals.
21816
21817 @enumerate
21818 @item
21819 Run @command{gcc} with the @option{-gnatf}. This first
21820 switch causes all errors on a given line to be reported. In its absence,
21821 only the first error on a line is displayed.
21822
21823 The @option{-gnatdO} switch causes errors to be displayed as soon as they
21824 are encountered, rather than after compilation is terminated. If GNAT
21825 terminates prematurely or goes into an infinite loop, the last error
21826 message displayed may help to pinpoint the culprit.
21827
21828 @item
21829 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
21830 mode, @command{gcc} produces ongoing information about the progress of the
21831 compilation and provides the name of each procedure as code is
21832 generated. This switch allows you to find which Ada procedure was being
21833 compiled when it encountered a code generation problem.
21834
21835 @item
21836 @cindex @option{-gnatdc} switch
21837 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
21838 switch that does for the front-end what @option{^-v^VERBOSE^} does
21839 for the back end. The system prints the name of each unit,
21840 either a compilation unit or nested unit, as it is being analyzed.
21841 @item
21842 Finally, you can start
21843 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
21844 front-end of GNAT, and can be run independently (normally it is just
21845 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
21846 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
21847 @code{where} command is the first line of attack; the variable
21848 @code{lineno} (seen by @code{print lineno}), used by the second phase of
21849 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
21850 which the execution stopped, and @code{input_file name} indicates the name of
21851 the source file.
21852 @end enumerate
21853
21854 @node Naming Conventions for GNAT Source Files
21855 @section Naming Conventions for GNAT Source Files
21856
21857 @noindent
21858 In order to examine the workings of the GNAT system, the following
21859 brief description of its organization may be helpful:
21860
21861 @itemize @bullet
21862 @item
21863 Files with prefix @file{^sc^SC^} contain the lexical scanner.
21864
21865 @item
21866 All files prefixed with @file{^par^PAR^} are components of the parser. The
21867 numbers correspond to chapters of the Ada Reference Manual. For example,
21868 parsing of select statements can be found in @file{par-ch9.adb}.
21869
21870 @item
21871 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
21872 numbers correspond to chapters of the Ada standard. For example, all
21873 issues involving context clauses can be found in @file{sem_ch10.adb}. In
21874 addition, some features of the language require sufficient special processing
21875 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
21876 dynamic dispatching, etc.
21877
21878 @item
21879 All files prefixed with @file{^exp^EXP^} perform normalization and
21880 expansion of the intermediate representation (abstract syntax tree, or AST).
21881 these files use the same numbering scheme as the parser and semantics files.
21882 For example, the construction of record initialization procedures is done in
21883 @file{exp_ch3.adb}.
21884
21885 @item
21886 The files prefixed with @file{^bind^BIND^} implement the binder, which
21887 verifies the consistency of the compilation, determines an order of
21888 elaboration, and generates the bind file.
21889
21890 @item
21891 The files @file{atree.ads} and @file{atree.adb} detail the low-level
21892 data structures used by the front-end.
21893
21894 @item
21895 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
21896 the abstract syntax tree as produced by the parser.
21897
21898 @item
21899 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
21900 all entities, computed during semantic analysis.
21901
21902 @item
21903 Library management issues are dealt with in files with prefix
21904 @file{^lib^LIB^}.
21905
21906 @item
21907 @findex Ada
21908 @cindex Annex A
21909 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
21910 defined in Annex A.
21911
21912 @item
21913 @findex Interfaces
21914 @cindex Annex B
21915 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
21916 defined in Annex B.
21917
21918 @item
21919 @findex System
21920 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
21921 both language-defined children and GNAT run-time routines.
21922
21923 @item
21924 @findex GNAT
21925 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
21926 general-purpose packages, fully documented in their specs. All
21927 the other @file{.c} files are modifications of common @command{gcc} files.
21928 @end itemize
21929
21930 @node Getting Internal Debugging Information
21931 @section Getting Internal Debugging Information
21932
21933 @noindent
21934 Most compilers have internal debugging switches and modes. GNAT
21935 does also, except GNAT internal debugging switches and modes are not
21936 secret. A summary and full description of all the compiler and binder
21937 debug flags are in the file @file{debug.adb}. You must obtain the
21938 sources of the compiler to see the full detailed effects of these flags.
21939
21940 The switches that print the source of the program (reconstructed from
21941 the internal tree) are of general interest for user programs, as are the
21942 options to print
21943 the full internal tree, and the entity table (the symbol table
21944 information). The reconstructed source provides a readable version of the
21945 program after the front-end has completed analysis and expansion,
21946 and is useful when studying the performance of specific constructs.
21947 For example, constraint checks are indicated, complex aggregates
21948 are replaced with loops and assignments, and tasking primitives
21949 are replaced with run-time calls.
21950
21951 @node Stack Traceback
21952 @section Stack Traceback
21953 @cindex traceback
21954 @cindex stack traceback
21955 @cindex stack unwinding
21956
21957 @noindent
21958 Traceback is a mechanism to display the sequence of subprogram calls that
21959 leads to a specified execution point in a program. Often (but not always)
21960 the execution point is an instruction at which an exception has been raised.
21961 This mechanism is also known as @i{stack unwinding} because it obtains
21962 its information by scanning the run-time stack and recovering the activation
21963 records of all active subprograms. Stack unwinding is one of the most
21964 important tools for program debugging.
21965
21966 The first entry stored in traceback corresponds to the deepest calling level,
21967 that is to say the subprogram currently executing the instruction
21968 from which we want to obtain the traceback.
21969
21970 Note that there is no runtime performance penalty when stack traceback
21971 is enabled, and no exception is raised during program execution.
21972
21973 @menu
21974 * Non-Symbolic Traceback::
21975 * Symbolic Traceback::
21976 @end menu
21977
21978 @node Non-Symbolic Traceback
21979 @subsection Non-Symbolic Traceback
21980 @cindex traceback, non-symbolic
21981
21982 @noindent
21983 Note: this feature is not supported on all platforms. See
21984 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
21985 platforms.
21986
21987 @menu
21988 * Tracebacks From an Unhandled Exception::
21989 * Tracebacks From Exception Occurrences (non-symbolic)::
21990 * Tracebacks From Anywhere in a Program (non-symbolic)::
21991 @end menu
21992
21993 @node Tracebacks From an Unhandled Exception
21994 @subsubsection Tracebacks From an Unhandled Exception
21995
21996 @noindent
21997 A runtime non-symbolic traceback is a list of addresses of call instructions.
21998 To enable this feature you must use the @option{-E}
21999 @code{gnatbind}'s option. With this option a stack traceback is stored as part
22000 of exception information. You can retrieve this information using the
22001 @code{addr2line} tool.
22002
22003 Here is a simple example:
22004
22005 @smallexample @c ada
22006 @cartouche
22007 procedure STB is
22008
22009 procedure P1 is
22010 begin
22011 raise Constraint_Error;
22012 end P1;
22013
22014 procedure P2 is
22015 begin
22016 P1;
22017 end P2;
22018
22019 begin
22020 P2;
22021 end STB;
22022 @end cartouche
22023 @end smallexample
22024
22025 @smallexample
22026 $ gnatmake stb -bargs -E
22027 $ stb
22028
22029 Execution terminated by unhandled exception
22030 Exception name: CONSTRAINT_ERROR
22031 Message: stb.adb:5
22032 Call stack traceback locations:
22033 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
22034 @end smallexample
22035
22036 @noindent
22037 As we see the traceback lists a sequence of addresses for the unhandled
22038 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
22039 guess that this exception come from procedure P1. To translate these
22040 addresses into the source lines where the calls appear, the
22041 @code{addr2line} tool, described below, is invaluable. The use of this tool
22042 requires the program to be compiled with debug information.
22043
22044 @smallexample
22045 $ gnatmake -g stb -bargs -E
22046 $ stb
22047
22048 Execution terminated by unhandled exception
22049 Exception name: CONSTRAINT_ERROR
22050 Message: stb.adb:5
22051 Call stack traceback locations:
22052 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
22053
22054 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
22055 0x4011f1 0x77e892a4
22056
22057 00401373 at d:/stb/stb.adb:5
22058 0040138B at d:/stb/stb.adb:10
22059 0040139C at d:/stb/stb.adb:14
22060 00401335 at d:/stb/b~stb.adb:104
22061 004011C4 at /build/@dots{}/crt1.c:200
22062 004011F1 at /build/@dots{}/crt1.c:222
22063 77E892A4 in ?? at ??:0
22064 @end smallexample
22065
22066 @noindent
22067 The @code{addr2line} tool has several other useful options:
22068
22069 @table @code
22070 @item --functions
22071 to get the function name corresponding to any location
22072
22073 @item --demangle=gnat
22074 to use the gnat decoding mode for the function names. Note that
22075 for binutils version 2.9.x the option is simply @option{--demangle}.
22076 @end table
22077
22078 @smallexample
22079 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
22080 0x40139c 0x401335 0x4011c4 0x4011f1
22081
22082 00401373 in stb.p1 at d:/stb/stb.adb:5
22083 0040138B in stb.p2 at d:/stb/stb.adb:10
22084 0040139C in stb at d:/stb/stb.adb:14
22085 00401335 in main at d:/stb/b~stb.adb:104
22086 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
22087 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
22088 @end smallexample
22089
22090 @noindent
22091 From this traceback we can see that the exception was raised in
22092 @file{stb.adb} at line 5, which was reached from a procedure call in
22093 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
22094 which contains the call to the main program.
22095 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
22096 and the output will vary from platform to platform.
22097
22098 It is also possible to use @code{GDB} with these traceback addresses to debug
22099 the program. For example, we can break at a given code location, as reported
22100 in the stack traceback:
22101
22102 @smallexample
22103 $ gdb -nw stb
22104 @ifclear vms
22105 @noindent
22106 Furthermore, this feature is not implemented inside Windows DLL. Only
22107 the non-symbolic traceback is reported in this case.
22108 @end ifclear
22109
22110 (gdb) break *0x401373
22111 Breakpoint 1 at 0x401373: file stb.adb, line 5.
22112 @end smallexample
22113
22114 @noindent
22115 It is important to note that the stack traceback addresses
22116 do not change when debug information is included. This is particularly useful
22117 because it makes it possible to release software without debug information (to
22118 minimize object size), get a field report that includes a stack traceback
22119 whenever an internal bug occurs, and then be able to retrieve the sequence
22120 of calls with the same program compiled with debug information.
22121
22122 @node Tracebacks From Exception Occurrences (non-symbolic)
22123 @subsubsection Tracebacks From Exception Occurrences
22124
22125 @noindent
22126 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
22127 The stack traceback is attached to the exception information string, and can
22128 be retrieved in an exception handler within the Ada program, by means of the
22129 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
22130
22131 @smallexample @c ada
22132 with Ada.Text_IO;
22133 with Ada.Exceptions;
22134
22135 procedure STB is
22136
22137 use Ada;
22138 use Ada.Exceptions;
22139
22140 procedure P1 is
22141 K : Positive := 1;
22142 begin
22143 K := K - 1;
22144 exception
22145 when E : others =>
22146 Text_IO.Put_Line (Exception_Information (E));
22147 end P1;
22148
22149 procedure P2 is
22150 begin
22151 P1;
22152 end P2;
22153
22154 begin
22155 P2;
22156 end STB;
22157 @end smallexample
22158
22159 @noindent
22160 This program will output:
22161
22162 @smallexample
22163 $ stb
22164
22165 Exception name: CONSTRAINT_ERROR
22166 Message: stb.adb:12
22167 Call stack traceback locations:
22168 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
22169 @end smallexample
22170
22171 @node Tracebacks From Anywhere in a Program (non-symbolic)
22172 @subsubsection Tracebacks From Anywhere in a Program
22173
22174 @noindent
22175 It is also possible to retrieve a stack traceback from anywhere in a
22176 program. For this you need to
22177 use the @code{GNAT.Traceback} API. This package includes a procedure called
22178 @code{Call_Chain} that computes a complete stack traceback, as well as useful
22179 display procedures described below. It is not necessary to use the
22180 @option{-E gnatbind} option in this case, because the stack traceback mechanism
22181 is invoked explicitly.
22182
22183 @noindent
22184 In the following example we compute a traceback at a specific location in
22185 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
22186 convert addresses to strings:
22187
22188 @smallexample @c ada
22189 with Ada.Text_IO;
22190 with GNAT.Traceback;
22191 with GNAT.Debug_Utilities;
22192
22193 procedure STB is
22194
22195 use Ada;
22196 use GNAT;
22197 use GNAT.Traceback;
22198
22199 procedure P1 is
22200 TB : Tracebacks_Array (1 .. 10);
22201 -- We are asking for a maximum of 10 stack frames.
22202 Len : Natural;
22203 -- Len will receive the actual number of stack frames returned.
22204 begin
22205 Call_Chain (TB, Len);
22206
22207 Text_IO.Put ("In STB.P1 : ");
22208
22209 for K in 1 .. Len loop
22210 Text_IO.Put (Debug_Utilities.Image (TB (K)));
22211 Text_IO.Put (' ');
22212 end loop;
22213
22214 Text_IO.New_Line;
22215 end P1;
22216
22217 procedure P2 is
22218 begin
22219 P1;
22220 end P2;
22221
22222 begin
22223 P2;
22224 end STB;
22225 @end smallexample
22226
22227 @smallexample
22228 $ gnatmake -g stb
22229 $ stb
22230
22231 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
22232 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
22233 @end smallexample
22234
22235 @noindent
22236 You can then get further information by invoking the @code{addr2line}
22237 tool as described earlier (note that the hexadecimal addresses
22238 need to be specified in C format, with a leading ``0x'').
22239
22240 @node Symbolic Traceback
22241 @subsection Symbolic Traceback
22242 @cindex traceback, symbolic
22243
22244 @noindent
22245 A symbolic traceback is a stack traceback in which procedure names are
22246 associated with each code location.
22247
22248 @noindent
22249 Note that this feature is not supported on all platforms. See
22250 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
22251 list of currently supported platforms.
22252
22253 @noindent
22254 Note that the symbolic traceback requires that the program be compiled
22255 with debug information. If it is not compiled with debug information
22256 only the non-symbolic information will be valid.
22257
22258 @menu
22259 * Tracebacks From Exception Occurrences (symbolic)::
22260 * Tracebacks From Anywhere in a Program (symbolic)::
22261 @end menu
22262
22263 @node Tracebacks From Exception Occurrences (symbolic)
22264 @subsubsection Tracebacks From Exception Occurrences
22265
22266 @smallexample @c ada
22267 with Ada.Text_IO;
22268 with GNAT.Traceback.Symbolic;
22269
22270 procedure STB is
22271
22272 procedure P1 is
22273 begin
22274 raise Constraint_Error;
22275 end P1;
22276
22277 procedure P2 is
22278 begin
22279 P1;
22280 end P2;
22281
22282 procedure P3 is
22283 begin
22284 P2;
22285 end P3;
22286
22287 begin
22288 P3;
22289 exception
22290 when E : others =>
22291 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
22292 end STB;
22293 @end smallexample
22294
22295 @smallexample
22296 $ gnatmake -g .\stb -bargs -E
22297 $ stb
22298
22299 0040149F in stb.p1 at stb.adb:8
22300 004014B7 in stb.p2 at stb.adb:13
22301 004014CF in stb.p3 at stb.adb:18
22302 004015DD in ada.stb at stb.adb:22
22303 00401461 in main at b~stb.adb:168
22304 004011C4 in __mingw_CRTStartup at crt1.c:200
22305 004011F1 in mainCRTStartup at crt1.c:222
22306 77E892A4 in ?? at ??:0
22307 @end smallexample
22308
22309 @noindent
22310 In the above example the ``.\'' syntax in the @command{gnatmake} command
22311 is currently required by @command{addr2line} for files that are in
22312 the current working directory.
22313 Moreover, the exact sequence of linker options may vary from platform
22314 to platform.
22315 The above @option{-largs} section is for Windows platforms. By contrast,
22316 under Unix there is no need for the @option{-largs} section.
22317 Differences across platforms are due to details of linker implementation.
22318
22319 @node Tracebacks From Anywhere in a Program (symbolic)
22320 @subsubsection Tracebacks From Anywhere in a Program
22321
22322 @noindent
22323 It is possible to get a symbolic stack traceback
22324 from anywhere in a program, just as for non-symbolic tracebacks.
22325 The first step is to obtain a non-symbolic
22326 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
22327 information. Here is an example:
22328
22329 @smallexample @c ada
22330 with Ada.Text_IO;
22331 with GNAT.Traceback;
22332 with GNAT.Traceback.Symbolic;
22333
22334 procedure STB is
22335
22336 use Ada;
22337 use GNAT.Traceback;
22338 use GNAT.Traceback.Symbolic;
22339
22340 procedure P1 is
22341 TB : Tracebacks_Array (1 .. 10);
22342 -- We are asking for a maximum of 10 stack frames.
22343 Len : Natural;
22344 -- Len will receive the actual number of stack frames returned.
22345 begin
22346 Call_Chain (TB, Len);
22347 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
22348 end P1;
22349
22350 procedure P2 is
22351 begin
22352 P1;
22353 end P2;
22354
22355 begin
22356 P2;
22357 end STB;
22358 @end smallexample
22359
22360 @c ******************************
22361 @ifset vms
22362 @node Compatibility with HP Ada
22363 @chapter Compatibility with HP Ada
22364 @cindex Compatibility
22365
22366 @noindent
22367 @cindex DEC Ada
22368 @cindex HP Ada
22369 @cindex Compatibility between GNAT and HP Ada
22370 This chapter compares HP Ada (formerly known as ``DEC Ada'')
22371 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
22372 GNAT is highly compatible
22373 with HP Ada, and it should generally be straightforward to port code
22374 from the HP Ada environment to GNAT. However, there are a few language
22375 and implementation differences of which the user must be aware. These
22376 differences are discussed in this chapter. In
22377 addition, the operating environment and command structure for the
22378 compiler are different, and these differences are also discussed.
22379
22380 For further details on these and other compatibility issues,
22381 see Appendix E of the HP publication
22382 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
22383
22384 Except where otherwise indicated, the description of GNAT for OpenVMS
22385 applies to both the Alpha and I64 platforms.
22386
22387 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
22388 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22389
22390 The discussion in this chapter addresses specifically the implementation
22391 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
22392 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
22393 GNAT always follows the Alpha implementation.
22394
22395 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
22396 attributes are recognized, although only a subset of them can sensibly
22397 be implemented. The description of pragmas in
22398 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
22399 indicates whether or not they are applicable to non-VMS systems.
22400
22401 @menu
22402 * Ada Language Compatibility::
22403 * Differences in the Definition of Package System::
22404 * Language-Related Features::
22405 * The Package STANDARD::
22406 * The Package SYSTEM::
22407 * Tasking and Task-Related Features::
22408 * Pragmas and Pragma-Related Features::
22409 * Library of Predefined Units::
22410 * Bindings::
22411 * Main Program Definition::
22412 * Implementation-Defined Attributes::
22413 * Compiler and Run-Time Interfacing::
22414 * Program Compilation and Library Management::
22415 * Input-Output::
22416 * Implementation Limits::
22417 * Tools and Utilities::
22418 @end menu
22419
22420 @node Ada Language Compatibility
22421 @section Ada Language Compatibility
22422
22423 @noindent
22424 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
22425 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
22426 with Ada 83, and therefore Ada 83 programs will compile
22427 and run under GNAT with
22428 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
22429 provides details on specific incompatibilities.
22430
22431 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
22432 as well as the pragma @code{ADA_83}, to force the compiler to
22433 operate in Ada 83 mode. This mode does not guarantee complete
22434 conformance to Ada 83, but in practice is sufficient to
22435 eliminate most sources of incompatibilities.
22436 In particular, it eliminates the recognition of the
22437 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
22438 in Ada 83 programs is legal, and handles the cases of packages
22439 with optional bodies, and generics that instantiate unconstrained
22440 types without the use of @code{(<>)}.
22441
22442 @node Differences in the Definition of Package System
22443 @section Differences in the Definition of Package @code{System}
22444
22445 @noindent
22446 An Ada compiler is allowed to add
22447 implementation-dependent declarations to package @code{System}.
22448 In normal mode,
22449 GNAT does not take advantage of this permission, and the version of
22450 @code{System} provided by GNAT exactly matches that defined in the Ada
22451 Reference Manual.
22452
22453 However, HP Ada adds an extensive set of declarations to package
22454 @code{System},
22455 as fully documented in the HP Ada manuals. To minimize changes required
22456 for programs that make use of these extensions, GNAT provides the pragma
22457 @code{Extend_System} for extending the definition of package System. By using:
22458 @cindex pragma @code{Extend_System}
22459 @cindex @code{Extend_System} pragma
22460
22461 @smallexample @c ada
22462 @group
22463 @cartouche
22464 pragma Extend_System (Aux_DEC);
22465 @end cartouche
22466 @end group
22467 @end smallexample
22468
22469 @noindent
22470 the set of definitions in @code{System} is extended to include those in
22471 package @code{System.Aux_DEC}.
22472 @cindex @code{System.Aux_DEC} package
22473 @cindex @code{Aux_DEC} package (child of @code{System})
22474 These definitions are incorporated directly into package @code{System},
22475 as though they had been declared there. For a
22476 list of the declarations added, see the spec of this package,
22477 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
22478 @cindex @file{s-auxdec.ads} file
22479 The pragma @code{Extend_System} is a configuration pragma, which means that
22480 it can be placed in the file @file{gnat.adc}, so that it will automatically
22481 apply to all subsequent compilations. See @ref{Configuration Pragmas},
22482 for further details.
22483
22484 An alternative approach that avoids the use of the non-standard
22485 @code{Extend_System} pragma is to add a context clause to the unit that
22486 references these facilities:
22487
22488 @smallexample @c ada
22489 @cartouche
22490 with System.Aux_DEC;
22491 use System.Aux_DEC;
22492 @end cartouche
22493 @end smallexample
22494
22495 @noindent
22496 The effect is not quite semantically identical to incorporating
22497 the declarations directly into package @code{System},
22498 but most programs will not notice a difference
22499 unless they use prefix notation (e.g.@: @code{System.Integer_8})
22500 to reference the entities directly in package @code{System}.
22501 For units containing such references,
22502 the prefixes must either be removed, or the pragma @code{Extend_System}
22503 must be used.
22504
22505 @node Language-Related Features
22506 @section Language-Related Features
22507
22508 @noindent
22509 The following sections highlight differences in types,
22510 representations of types, operations, alignment, and
22511 related topics.
22512
22513 @menu
22514 * Integer Types and Representations::
22515 * Floating-Point Types and Representations::
22516 * Pragmas Float_Representation and Long_Float::
22517 * Fixed-Point Types and Representations::
22518 * Record and Array Component Alignment::
22519 * Address Clauses::
22520 * Other Representation Clauses::
22521 @end menu
22522
22523 @node Integer Types and Representations
22524 @subsection Integer Types and Representations
22525
22526 @noindent
22527 The set of predefined integer types is identical in HP Ada and GNAT.
22528 Furthermore the representation of these integer types is also identical,
22529 including the capability of size clauses forcing biased representation.
22530
22531 In addition,
22532 HP Ada for OpenVMS Alpha systems has defined the
22533 following additional integer types in package @code{System}:
22534
22535 @itemize @bullet
22536
22537 @item
22538 @code{INTEGER_8}
22539
22540 @item
22541 @code{INTEGER_16}
22542
22543 @item
22544 @code{INTEGER_32}
22545
22546 @item
22547 @code{INTEGER_64}
22548
22549 @item
22550 @code{LARGEST_INTEGER}
22551 @end itemize
22552
22553 @noindent
22554 In GNAT, the first four of these types may be obtained from the
22555 standard Ada package @code{Interfaces}.
22556 Alternatively, by use of the pragma @code{Extend_System}, identical
22557 declarations can be referenced directly in package @code{System}.
22558 On both GNAT and HP Ada, the maximum integer size is 64 bits.
22559
22560 @node Floating-Point Types and Representations
22561 @subsection Floating-Point Types and Representations
22562 @cindex Floating-Point types
22563
22564 @noindent
22565 The set of predefined floating-point types is identical in HP Ada and GNAT.
22566 Furthermore the representation of these floating-point
22567 types is also identical. One important difference is that the default
22568 representation for HP Ada is @code{VAX_Float}, but the default representation
22569 for GNAT is IEEE.
22570
22571 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
22572 pragma @code{Float_Representation} as described in the HP Ada
22573 documentation.
22574 For example, the declarations:
22575
22576 @smallexample @c ada
22577 @cartouche
22578 type F_Float is digits 6;
22579 pragma Float_Representation (VAX_Float, F_Float);
22580 @end cartouche
22581 @end smallexample
22582
22583 @noindent
22584 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
22585 format.
22586 This set of declarations actually appears in @code{System.Aux_DEC},
22587 which contains
22588 the full set of additional floating-point declarations provided in
22589 the HP Ada version of package @code{System}.
22590 This and similar declarations may be accessed in a user program
22591 by using pragma @code{Extend_System}. The use of this
22592 pragma, and the related pragma @code{Long_Float} is described in further
22593 detail in the following section.
22594
22595 @node Pragmas Float_Representation and Long_Float
22596 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
22597
22598 @noindent
22599 HP Ada provides the pragma @code{Float_Representation}, which
22600 acts as a program library switch to allow control over
22601 the internal representation chosen for the predefined
22602 floating-point types declared in the package @code{Standard}.
22603 The format of this pragma is as follows:
22604
22605 @smallexample @c ada
22606 @cartouche
22607 pragma Float_Representation(VAX_Float | IEEE_Float);
22608 @end cartouche
22609 @end smallexample
22610
22611 @noindent
22612 This pragma controls the representation of floating-point
22613 types as follows:
22614
22615 @itemize @bullet
22616 @item
22617 @code{VAX_Float} specifies that floating-point
22618 types are represented by default with the VAX system hardware types
22619 @code{F-floating}, @code{D-floating}, @code{G-floating}.
22620 Note that the @code{H-floating}
22621 type was available only on VAX systems, and is not available
22622 in either HP Ada or GNAT.
22623
22624 @item
22625 @code{IEEE_Float} specifies that floating-point
22626 types are represented by default with the IEEE single and
22627 double floating-point types.
22628 @end itemize
22629
22630 @noindent
22631 GNAT provides an identical implementation of the pragma
22632 @code{Float_Representation}, except that it functions as a
22633 configuration pragma. Note that the
22634 notion of configuration pragma corresponds closely to the
22635 HP Ada notion of a program library switch.
22636
22637 When no pragma is used in GNAT, the default is @code{IEEE_Float},
22638 which is different
22639 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
22640 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
22641 advisable to change the format of numbers passed to standard library
22642 routines, and if necessary explicit type conversions may be needed.
22643
22644 The use of @code{IEEE_Float} is recommended in GNAT since it is more
22645 efficient, and (given that it conforms to an international standard)
22646 potentially more portable.
22647 The situation in which @code{VAX_Float} may be useful is in interfacing
22648 to existing code and data that expect the use of @code{VAX_Float}.
22649 In such a situation use the predefined @code{VAX_Float}
22650 types in package @code{System}, as extended by
22651 @code{Extend_System}. For example, use @code{System.F_Float}
22652 to specify the 32-bit @code{F-Float} format.
22653
22654 @noindent
22655 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
22656 to allow control over the internal representation chosen
22657 for the predefined type @code{Long_Float} and for floating-point
22658 type declarations with digits specified in the range 7 .. 15.
22659 The format of this pragma is as follows:
22660
22661 @smallexample @c ada
22662 @cartouche
22663 pragma Long_Float (D_FLOAT | G_FLOAT);
22664 @end cartouche
22665 @end smallexample
22666
22667 @node Fixed-Point Types and Representations
22668 @subsection Fixed-Point Types and Representations
22669
22670 @noindent
22671 On HP Ada for OpenVMS Alpha systems, rounding is
22672 away from zero for both positive and negative numbers.
22673 Therefore, @code{+0.5} rounds to @code{1},
22674 and @code{-0.5} rounds to @code{-1}.
22675
22676 On GNAT the results of operations
22677 on fixed-point types are in accordance with the Ada
22678 rules. In particular, results of operations on decimal
22679 fixed-point types are truncated.
22680
22681 @node Record and Array Component Alignment
22682 @subsection Record and Array Component Alignment
22683
22684 @noindent
22685 On HP Ada for OpenVMS Alpha, all non-composite components
22686 are aligned on natural boundaries. For example, 1-byte
22687 components are aligned on byte boundaries, 2-byte
22688 components on 2-byte boundaries, 4-byte components on 4-byte
22689 byte boundaries, and so on. The OpenVMS Alpha hardware
22690 runs more efficiently with naturally aligned data.
22691
22692 On GNAT, alignment rules are compatible
22693 with HP Ada for OpenVMS Alpha.
22694
22695 @node Address Clauses
22696 @subsection Address Clauses
22697
22698 @noindent
22699 In HP Ada and GNAT, address clauses are supported for
22700 objects and imported subprograms.
22701 The predefined type @code{System.Address} is a private type
22702 in both compilers on Alpha OpenVMS, with the same representation
22703 (it is simply a machine pointer). Addition, subtraction, and comparison
22704 operations are available in the standard Ada package
22705 @code{System.Storage_Elements}, or in package @code{System}
22706 if it is extended to include @code{System.Aux_DEC} using a
22707 pragma @code{Extend_System} as previously described.
22708
22709 Note that code that @code{with}'s both this extended package @code{System}
22710 and the package @code{System.Storage_Elements} should not @code{use}
22711 both packages, or ambiguities will result. In general it is better
22712 not to mix these two sets of facilities. The Ada package was
22713 designed specifically to provide the kind of features that HP Ada
22714 adds directly to package @code{System}.
22715
22716 The type @code{System.Address} is a 64-bit integer type in GNAT for
22717 I64 OpenVMS. For more information,
22718 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22719
22720 GNAT is compatible with HP Ada in its handling of address
22721 clauses, except for some limitations in
22722 the form of address clauses for composite objects with
22723 initialization. Such address clauses are easily replaced
22724 by the use of an explicitly-defined constant as described
22725 in the Ada Reference Manual (13.1(22)). For example, the sequence
22726 of declarations:
22727
22728 @smallexample @c ada
22729 @cartouche
22730 X, Y : Integer := Init_Func;
22731 Q : String (X .. Y) := "abc";
22732 @dots{}
22733 for Q'Address use Compute_Address;
22734 @end cartouche
22735 @end smallexample
22736
22737 @noindent
22738 will be rejected by GNAT, since the address cannot be computed at the time
22739 that @code{Q} is declared. To achieve the intended effect, write instead:
22740
22741 @smallexample @c ada
22742 @group
22743 @cartouche
22744 X, Y : Integer := Init_Func;
22745 Q_Address : constant Address := Compute_Address;
22746 Q : String (X .. Y) := "abc";
22747 @dots{}
22748 for Q'Address use Q_Address;
22749 @end cartouche
22750 @end group
22751 @end smallexample
22752
22753 @noindent
22754 which will be accepted by GNAT (and other Ada compilers), and is also
22755 compatible with Ada 83. A fuller description of the restrictions
22756 on address specifications is found in @ref{Top, GNAT Reference Manual,
22757 About This Guide, gnat_rm, GNAT Reference Manual}.
22758
22759 @node Other Representation Clauses
22760 @subsection Other Representation Clauses
22761
22762 @noindent
22763 GNAT implements in a compatible manner all the representation
22764 clauses supported by HP Ada. In addition, GNAT
22765 implements the representation clause forms that were introduced in Ada 95,
22766 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
22767
22768 @node The Package STANDARD
22769 @section The Package @code{STANDARD}
22770
22771 @noindent
22772 The package @code{STANDARD}, as implemented by HP Ada, is fully
22773 described in the @cite{Ada Reference Manual} and in the
22774 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
22775 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
22776
22777 In addition, HP Ada supports the Latin-1 character set in
22778 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
22779 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
22780 the type @code{WIDE_CHARACTER}.
22781
22782 The floating-point types supported by GNAT are those
22783 supported by HP Ada, but the defaults are different, and are controlled by
22784 pragmas. See @ref{Floating-Point Types and Representations}, for details.
22785
22786 @node The Package SYSTEM
22787 @section The Package @code{SYSTEM}
22788
22789 @noindent
22790 HP Ada provides a specific version of the package
22791 @code{SYSTEM} for each platform on which the language is implemented.
22792 For the complete spec of the package @code{SYSTEM}, see
22793 Appendix F of the @cite{HP Ada Language Reference Manual}.
22794
22795 On HP Ada, the package @code{SYSTEM} includes the following conversion
22796 functions:
22797 @itemize @bullet
22798 @item @code{TO_ADDRESS(INTEGER)}
22799
22800 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
22801
22802 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
22803
22804 @item @code{TO_INTEGER(ADDRESS)}
22805
22806 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
22807
22808 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
22809 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
22810 @end itemize
22811
22812 @noindent
22813 By default, GNAT supplies a version of @code{SYSTEM} that matches
22814 the definition given in the @cite{Ada Reference Manual}.
22815 This
22816 is a subset of the HP system definitions, which is as
22817 close as possible to the original definitions. The only difference
22818 is that the definition of @code{SYSTEM_NAME} is different:
22819
22820 @smallexample @c ada
22821 @cartouche
22822 type Name is (SYSTEM_NAME_GNAT);
22823 System_Name : constant Name := SYSTEM_NAME_GNAT;
22824 @end cartouche
22825 @end smallexample
22826
22827 @noindent
22828 Also, GNAT adds the Ada declarations for
22829 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
22830
22831 However, the use of the following pragma causes GNAT
22832 to extend the definition of package @code{SYSTEM} so that it
22833 encompasses the full set of HP-specific extensions,
22834 including the functions listed above:
22835
22836 @smallexample @c ada
22837 @cartouche
22838 pragma Extend_System (Aux_DEC);
22839 @end cartouche
22840 @end smallexample
22841
22842 @noindent
22843 The pragma @code{Extend_System} is a configuration pragma that
22844 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
22845 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
22846
22847 HP Ada does not allow the recompilation of the package
22848 @code{SYSTEM}. Instead HP Ada provides several pragmas
22849 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
22850 to modify values in the package @code{SYSTEM}.
22851 On OpenVMS Alpha systems, the pragma
22852 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
22853 its single argument.
22854
22855 GNAT does permit the recompilation of package @code{SYSTEM} using
22856 the special switch @option{-gnatg}, and this switch can be used if
22857 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
22858 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
22859 or @code{MEMORY_SIZE} by any other means.
22860
22861 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
22862 enumeration literal @code{SYSTEM_NAME_GNAT}.
22863
22864 The definitions provided by the use of
22865
22866 @smallexample @c ada
22867 pragma Extend_System (AUX_Dec);
22868 @end smallexample
22869
22870 @noindent
22871 are virtually identical to those provided by the HP Ada 83 package
22872 @code{SYSTEM}. One important difference is that the name of the
22873 @code{TO_ADDRESS}
22874 function for type @code{UNSIGNED_LONGWORD} is changed to
22875 @code{TO_ADDRESS_LONG}.
22876 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
22877 discussion of why this change was necessary.
22878
22879 @noindent
22880 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
22881 is in fact
22882 an extension to Ada 83 not strictly compatible with the reference manual.
22883 GNAT, in order to be exactly compatible with the standard,
22884 does not provide this capability. In HP Ada 83, the
22885 point of this definition is to deal with a call like:
22886
22887 @smallexample @c ada
22888 TO_ADDRESS (16#12777#);
22889 @end smallexample
22890
22891 @noindent
22892 Normally, according to Ada 83 semantics, one would expect this to be
22893 ambiguous, since it matches both the @code{INTEGER} and
22894 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
22895 However, in HP Ada 83, there is no ambiguity, since the
22896 definition using @i{universal_integer} takes precedence.
22897
22898 In GNAT, since the version with @i{universal_integer} cannot be supplied,
22899 it is
22900 not possible to be 100% compatible. Since there are many programs using
22901 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
22902 GNAT was
22903 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
22904 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
22905
22906 @smallexample @c ada
22907 function To_Address (X : Integer) return Address;
22908 pragma Pure_Function (To_Address);
22909
22910 function To_Address_Long (X : Unsigned_Longword) return Address;
22911 pragma Pure_Function (To_Address_Long);
22912 @end smallexample
22913
22914 @noindent
22915 This means that programs using @code{TO_ADDRESS} for
22916 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
22917
22918 @node Tasking and Task-Related Features
22919 @section Tasking and Task-Related Features
22920
22921 @noindent
22922 This section compares the treatment of tasking in GNAT
22923 and in HP Ada for OpenVMS Alpha.
22924 The GNAT description applies to both Alpha and I64 OpenVMS.
22925 For detailed information on tasking in
22926 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
22927 relevant run-time reference manual.
22928
22929 @menu
22930 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
22931 * Assigning Task IDs::
22932 * Task IDs and Delays::
22933 * Task-Related Pragmas::
22934 * Scheduling and Task Priority::
22935 * The Task Stack::
22936 * External Interrupts::
22937 @end menu
22938
22939 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22940 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22941
22942 @noindent
22943 On OpenVMS Alpha systems, each Ada task (except a passive
22944 task) is implemented as a single stream of execution
22945 that is created and managed by the kernel. On these
22946 systems, HP Ada tasking support is based on DECthreads,
22947 an implementation of the POSIX standard for threads.
22948
22949 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
22950 code that calls DECthreads routines can be used together.
22951 The interaction between Ada tasks and DECthreads routines
22952 can have some benefits. For example when on OpenVMS Alpha,
22953 HP Ada can call C code that is already threaded.
22954
22955 GNAT uses the facilities of DECthreads,
22956 and Ada tasks are mapped to threads.
22957
22958 @node Assigning Task IDs
22959 @subsection Assigning Task IDs
22960
22961 @noindent
22962 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
22963 the environment task that executes the main program. On
22964 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
22965 that have been created but are not yet activated.
22966
22967 On OpenVMS Alpha systems, task IDs are assigned at
22968 activation. On GNAT systems, task IDs are also assigned at
22969 task creation but do not have the same form or values as
22970 task ID values in HP Ada. There is no null task, and the
22971 environment task does not have a specific task ID value.
22972
22973 @node Task IDs and Delays
22974 @subsection Task IDs and Delays
22975
22976 @noindent
22977 On OpenVMS Alpha systems, tasking delays are implemented
22978 using Timer System Services. The Task ID is used for the
22979 identification of the timer request (the @code{REQIDT} parameter).
22980 If Timers are used in the application take care not to use
22981 @code{0} for the identification, because cancelling such a timer
22982 will cancel all timers and may lead to unpredictable results.
22983
22984 @node Task-Related Pragmas
22985 @subsection Task-Related Pragmas
22986
22987 @noindent
22988 Ada supplies the pragma @code{TASK_STORAGE}, which allows
22989 specification of the size of the guard area for a task
22990 stack. (The guard area forms an area of memory that has no
22991 read or write access and thus helps in the detection of
22992 stack overflow.) On OpenVMS Alpha systems, if the pragma
22993 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
22994 area is created. In the absence of a pragma @code{TASK_STORAGE},
22995 a default guard area is created.
22996
22997 GNAT supplies the following task-related pragma:
22998
22999 @itemize
23000 @item @code{TASK_STORAGE}
23001
23002 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
23003 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
23004 @code{SUPPRESS}, and @code{VOLATILE}.
23005 @end itemize
23006
23007 @node Scheduling and Task Priority
23008 @subsection Scheduling and Task Priority
23009
23010 @noindent
23011 HP Ada implements the Ada language requirement that
23012 when two tasks are eligible for execution and they have
23013 different priorities, the lower priority task does not
23014 execute while the higher priority task is waiting. The HP
23015 Ada Run-Time Library keeps a task running until either the
23016 task is suspended or a higher priority task becomes ready.
23017
23018 On OpenVMS Alpha systems, the default strategy is round-
23019 robin with preemption. Tasks of equal priority take turns
23020 at the processor. A task is run for a certain period of
23021 time and then placed at the tail of the ready queue for
23022 its priority level.
23023
23024 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
23025 which can be used to enable or disable round-robin
23026 scheduling of tasks with the same priority.
23027 See the relevant HP Ada run-time reference manual for
23028 information on using the pragmas to control HP Ada task
23029 scheduling.
23030
23031 GNAT follows the scheduling rules of Annex D (Real-Time
23032 Annex) of the @cite{Ada Reference Manual}. In general, this
23033 scheduling strategy is fully compatible with HP Ada
23034 although it provides some additional constraints (as
23035 fully documented in Annex D).
23036 GNAT implements time slicing control in a manner compatible with
23037 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
23038 are identical to the HP Ada 83 pragma of the same name.
23039 Note that it is not possible to mix GNAT tasking and
23040 HP Ada 83 tasking in the same program, since the two run-time
23041 libraries are not compatible.
23042
23043 @node The Task Stack
23044 @subsection The Task Stack
23045
23046 @noindent
23047 In HP Ada, a task stack is allocated each time a
23048 non-passive task is activated. As soon as the task is
23049 terminated, the storage for the task stack is deallocated.
23050 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
23051 a default stack size is used. Also, regardless of the size
23052 specified, some additional space is allocated for task
23053 management purposes. On OpenVMS Alpha systems, at least
23054 one page is allocated.
23055
23056 GNAT handles task stacks in a similar manner. In accordance with
23057 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
23058 an alternative method for controlling the task stack size.
23059 The specification of the attribute @code{T'STORAGE_SIZE} is also
23060 supported in a manner compatible with HP Ada.
23061
23062 @node External Interrupts
23063 @subsection External Interrupts
23064
23065 @noindent
23066 On HP Ada, external interrupts can be associated with task entries.
23067 GNAT is compatible with HP Ada in its handling of external interrupts.
23068
23069 @node Pragmas and Pragma-Related Features
23070 @section Pragmas and Pragma-Related Features
23071
23072 @noindent
23073 Both HP Ada and GNAT supply all language-defined pragmas
23074 as specified by the Ada 83 standard. GNAT also supplies all
23075 language-defined pragmas introduced by Ada 95 and Ada 2005.
23076 In addition, GNAT implements the implementation-defined pragmas
23077 from HP Ada 83.
23078
23079 @itemize @bullet
23080 @item @code{AST_ENTRY}
23081
23082 @item @code{COMMON_OBJECT}
23083
23084 @item @code{COMPONENT_ALIGNMENT}
23085
23086 @item @code{EXPORT_EXCEPTION}
23087
23088 @item @code{EXPORT_FUNCTION}
23089
23090 @item @code{EXPORT_OBJECT}
23091
23092 @item @code{EXPORT_PROCEDURE}
23093
23094 @item @code{EXPORT_VALUED_PROCEDURE}
23095
23096 @item @code{FLOAT_REPRESENTATION}
23097
23098 @item @code{IDENT}
23099
23100 @item @code{IMPORT_EXCEPTION}
23101
23102 @item @code{IMPORT_FUNCTION}
23103
23104 @item @code{IMPORT_OBJECT}
23105
23106 @item @code{IMPORT_PROCEDURE}
23107
23108 @item @code{IMPORT_VALUED_PROCEDURE}
23109
23110 @item @code{INLINE_GENERIC}
23111
23112 @item @code{INTERFACE_NAME}
23113
23114 @item @code{LONG_FLOAT}
23115
23116 @item @code{MAIN_STORAGE}
23117
23118 @item @code{PASSIVE}
23119
23120 @item @code{PSECT_OBJECT}
23121
23122 @item @code{SHARE_GENERIC}
23123
23124 @item @code{SUPPRESS_ALL}
23125
23126 @item @code{TASK_STORAGE}
23127
23128 @item @code{TIME_SLICE}
23129
23130 @item @code{TITLE}
23131 @end itemize
23132
23133 @noindent
23134 These pragmas are all fully implemented, with the exception of @code{TITLE},
23135 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
23136 recognized, but which have no
23137 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
23138 use of Ada protected objects. In GNAT, all generics are inlined.
23139
23140 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
23141 a separate subprogram specification which must appear before the
23142 subprogram body.
23143
23144 GNAT also supplies a number of implementation-defined pragmas including the
23145 following:
23146
23147 @itemize @bullet
23148 @item @code{ABORT_DEFER}
23149
23150 @item @code{ADA_83}
23151
23152 @item @code{ADA_95}
23153
23154 @item @code{ADA_05}
23155
23156 @item @code{Ada_2005}
23157
23158 @item @code{Ada_12}
23159
23160 @item @code{Ada_2012}
23161
23162 @item @code{ALLOW_INTEGER_ADDRESS}
23163
23164 @item @code{ANNOTATE}
23165
23166 @item @code{ASSERT}
23167
23168 @item @code{C_PASS_BY_COPY}
23169
23170 @item @code{CPP_CLASS}
23171
23172 @item @code{CPP_CONSTRUCTOR}
23173
23174 @item @code{CPP_DESTRUCTOR}
23175
23176 @item @code{DEBUG}
23177
23178 @item @code{EXTEND_SYSTEM}
23179
23180 @item @code{LINKER_ALIAS}
23181
23182 @item @code{LINKER_SECTION}
23183
23184 @item @code{MACHINE_ATTRIBUTE}
23185
23186 @item @code{NO_RETURN}
23187
23188 @item @code{PURE_FUNCTION}
23189
23190 @item @code{SOURCE_FILE_NAME}
23191
23192 @item @code{SOURCE_REFERENCE}
23193
23194 @item @code{UNCHECKED_UNION}
23195
23196 @item @code{UNIMPLEMENTED_UNIT}
23197
23198 @item @code{UNIVERSAL_DATA}
23199
23200 @item @code{UNSUPPRESS}
23201
23202 @item @code{WARNINGS}
23203
23204 @item @code{WEAK_EXTERNAL}
23205 @end itemize
23206
23207 @noindent
23208 For full details on these and other GNAT implementation-defined pragmas,
23209 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
23210 Manual}.
23211
23212 @menu
23213 * Restrictions on the Pragma INLINE::
23214 * Restrictions on the Pragma INTERFACE::
23215 * Restrictions on the Pragma SYSTEM_NAME::
23216 @end menu
23217
23218 @node Restrictions on the Pragma INLINE
23219 @subsection Restrictions on Pragma @code{INLINE}
23220
23221 @noindent
23222 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
23223 @itemize @bullet
23224 @item Parameters cannot have a task type.
23225
23226 @item Function results cannot be task types, unconstrained
23227 array types, or unconstrained types with discriminants.
23228
23229 @item Bodies cannot declare the following:
23230 @itemize @bullet
23231 @item Subprogram body or stub (imported subprogram is allowed)
23232
23233 @item Tasks
23234
23235 @item Generic declarations
23236
23237 @item Instantiations
23238
23239 @item Exceptions
23240
23241 @item Access types (types derived from access types allowed)
23242
23243 @item Array or record types
23244
23245 @item Dependent tasks
23246
23247 @item Direct recursive calls of subprogram or containing
23248 subprogram, directly or via a renaming
23249
23250 @end itemize
23251 @end itemize
23252
23253 @noindent
23254 In GNAT, the only restriction on pragma @code{INLINE} is that the
23255 body must occur before the call if both are in the same
23256 unit, and the size must be appropriately small. There are
23257 no other specific restrictions which cause subprograms to
23258 be incapable of being inlined.
23259
23260 @node Restrictions on the Pragma INTERFACE
23261 @subsection Restrictions on Pragma @code{INTERFACE}
23262
23263 @noindent
23264 The following restrictions on pragma @code{INTERFACE}
23265 are enforced by both HP Ada and GNAT:
23266 @itemize @bullet
23267 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
23268 Default is the default on OpenVMS Alpha systems.
23269
23270 @item Parameter passing: Language specifies default
23271 mechanisms but can be overridden with an @code{EXPORT} pragma.
23272
23273 @itemize @bullet
23274 @item Ada: Use internal Ada rules.
23275
23276 @item Bliss, C: Parameters must be mode @code{in}; cannot be
23277 record or task type. Result cannot be a string, an
23278 array, or a record.
23279
23280 @item Fortran: Parameters cannot have a task type. Result cannot
23281 be a string, an array, or a record.
23282 @end itemize
23283 @end itemize
23284
23285 @noindent
23286 GNAT is entirely upwards compatible with HP Ada, and in addition allows
23287 record parameters for all languages.
23288
23289 @node Restrictions on the Pragma SYSTEM_NAME
23290 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
23291
23292 @noindent
23293 For HP Ada for OpenVMS Alpha, the enumeration literal
23294 for the type @code{NAME} is @code{OPENVMS_AXP}.
23295 In GNAT, the enumeration
23296 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
23297
23298 @node Library of Predefined Units
23299 @section Library of Predefined Units
23300
23301 @noindent
23302 A library of predefined units is provided as part of the
23303 HP Ada and GNAT implementations. HP Ada does not provide
23304 the package @code{MACHINE_CODE} but instead recommends importing
23305 assembler code.
23306
23307 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
23308 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
23309 version.
23310 The HP Ada Predefined Library units are modified to remove post-Ada 83
23311 incompatibilities and to make them interoperable with GNAT
23312 (@pxref{Changes to DECLIB}, for details).
23313 The units are located in the @file{DECLIB} directory.
23314
23315 The GNAT RTL is contained in
23316 the @file{ADALIB} directory, and
23317 the default search path is set up to find @code{DECLIB} units in preference
23318 to @code{ADALIB} units with the same name (@code{TEXT_IO},
23319 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
23320
23321 @menu
23322 * Changes to DECLIB::
23323 @end menu
23324
23325 @node Changes to DECLIB
23326 @subsection Changes to @code{DECLIB}
23327
23328 @noindent
23329 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
23330 compatibility are minor and include the following:
23331
23332 @itemize @bullet
23333 @item Adjusting the location of pragmas and record representation
23334 clauses to obey Ada 95 (and thus Ada 2005) rules
23335
23336 @item Adding the proper notation to generic formal parameters
23337 that take unconstrained types in instantiation
23338
23339 @item Adding pragma @code{ELABORATE_BODY} to package specs
23340 that have package bodies not otherwise allowed
23341
23342 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
23343 ``@code{PROTECTD}''.
23344 Currently these are found only in the @code{STARLET} package spec.
23345
23346 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
23347 where the address size is constrained to 32 bits.
23348 @end itemize
23349
23350 @noindent
23351 None of the above changes is visible to users.
23352
23353 @node Bindings
23354 @section Bindings
23355
23356 @noindent
23357 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
23358 @itemize @bullet
23359
23360 @item Command Language Interpreter (CLI interface)
23361
23362 @item DECtalk Run-Time Library (DTK interface)
23363
23364 @item Librarian utility routines (LBR interface)
23365
23366 @item General Purpose Run-Time Library (LIB interface)
23367
23368 @item Math Run-Time Library (MTH interface)
23369
23370 @item National Character Set Run-Time Library (NCS interface)
23371
23372 @item Compiled Code Support Run-Time Library (OTS interface)
23373
23374 @item Parallel Processing Run-Time Library (PPL interface)
23375
23376 @item Screen Management Run-Time Library (SMG interface)
23377
23378 @item Sort Run-Time Library (SOR interface)
23379
23380 @item String Run-Time Library (STR interface)
23381
23382 @item STARLET System Library
23383 @findex Starlet
23384
23385 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
23386
23387 @item X Windows Toolkit (XT interface)
23388
23389 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
23390 @end itemize
23391
23392 @noindent
23393 GNAT provides implementations of these HP bindings in the @code{DECLIB}
23394 directory, on both the Alpha and I64 OpenVMS platforms.
23395
23396 The X components of DECLIB compatibility package are located in a separate
23397 library, called XDECGNAT, which is not linked with by default; this library
23398 must be explicitly linked with any application that makes use of any X facilities,
23399 with a command similar to
23400
23401 @code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
23402
23403 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
23404 in the
23405 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
23406 A pragma @code{Linker_Options} has been added to packages @code{Xm},
23407 @code{Xt}, and @code{X_Lib}
23408 causing the default X/Motif sharable image libraries to be linked in. This
23409 is done via options files named @file{xm.opt}, @file{xt.opt}, and
23410 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
23411
23412 It may be necessary to edit these options files to update or correct the
23413 library names if, for example, the newer X/Motif bindings from
23414 @file{ADA$EXAMPLES}
23415 had been (previous to installing GNAT) copied and renamed to supersede the
23416 default @file{ADA$PREDEFINED} versions.
23417
23418 @menu
23419 * Shared Libraries and Options Files::
23420 * Interfaces to C::
23421 @end menu
23422
23423 @node Shared Libraries and Options Files
23424 @subsection Shared Libraries and Options Files
23425
23426 @noindent
23427 When using the HP Ada
23428 predefined X and Motif bindings, the linking with their sharable images is
23429 done automatically by @command{GNAT LINK}.
23430 When using other X and Motif bindings, you need
23431 to add the corresponding sharable images to the command line for
23432 @code{GNAT LINK}. When linking with shared libraries, or with
23433 @file{.OPT} files, you must
23434 also add them to the command line for @command{GNAT LINK}.
23435
23436 A shared library to be used with GNAT is built in the same way as other
23437 libraries under VMS. The VMS Link command can be used in standard fashion.
23438
23439 @node Interfaces to C
23440 @subsection Interfaces to C
23441
23442 @noindent
23443 HP Ada
23444 provides the following Ada types and operations:
23445
23446 @itemize @bullet
23447 @item C types package (@code{C_TYPES})
23448
23449 @item C strings (@code{C_TYPES.NULL_TERMINATED})
23450
23451 @item Other_types (@code{SHORT_INT})
23452 @end itemize
23453
23454 @noindent
23455 Interfacing to C with GNAT, you can use the above approach
23456 described for HP Ada or the facilities of Annex B of
23457 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
23458 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
23459 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
23460
23461 The @option{-gnatF} qualifier forces default and explicit
23462 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
23463 to be uppercased for compatibility with the default behavior
23464 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
23465
23466 @node Main Program Definition
23467 @section Main Program Definition
23468
23469 @noindent
23470 The following section discusses differences in the
23471 definition of main programs on HP Ada and GNAT.
23472 On HP Ada, main programs are defined to meet the
23473 following conditions:
23474 @itemize @bullet
23475 @item Procedure with no formal parameters (returns @code{0} upon
23476 normal completion)
23477
23478 @item Procedure with no formal parameters (returns @code{42} when
23479 an unhandled exception is raised)
23480
23481 @item Function with no formal parameters whose returned value
23482 is of a discrete type
23483
23484 @item Procedure with one @code{out} formal of a discrete type for
23485 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
23486
23487 @end itemize
23488
23489 @noindent
23490 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
23491 a main function or main procedure returns a discrete
23492 value whose size is less than 64 bits (32 on VAX systems),
23493 the value is zero- or sign-extended as appropriate.
23494 On GNAT, main programs are defined as follows:
23495 @itemize @bullet
23496 @item Must be a non-generic, parameterless subprogram that
23497 is either a procedure or function returning an Ada
23498 @code{STANDARD.INTEGER} (the predefined type)
23499
23500 @item Cannot be a generic subprogram or an instantiation of a
23501 generic subprogram
23502 @end itemize
23503
23504 @node Implementation-Defined Attributes
23505 @section Implementation-Defined Attributes
23506
23507 @noindent
23508 GNAT provides all HP Ada implementation-defined
23509 attributes.
23510
23511 @node Compiler and Run-Time Interfacing
23512 @section Compiler and Run-Time Interfacing
23513
23514 @noindent
23515 HP Ada provides the following qualifiers to pass options to the linker
23516 (ACS LINK):
23517 @itemize @bullet
23518 @item @option{/WAIT} and @option{/SUBMIT}
23519
23520 @item @option{/COMMAND}
23521
23522 @item @option{/@r{[}NO@r{]}MAP}
23523
23524 @item @option{/OUTPUT=@var{file-spec}}
23525
23526 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
23527 @end itemize
23528
23529 @noindent
23530 To pass options to the linker, GNAT provides the following
23531 switches:
23532
23533 @itemize @bullet
23534 @item @option{/EXECUTABLE=@var{exec-name}}
23535
23536 @item @option{/VERBOSE}
23537
23538 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
23539 @end itemize
23540
23541 @noindent
23542 For more information on these switches, see
23543 @ref{Switches for gnatlink}.
23544 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
23545 to control optimization. HP Ada also supplies the
23546 following pragmas:
23547 @itemize @bullet
23548 @item @code{OPTIMIZE}
23549
23550 @item @code{INLINE}
23551
23552 @item @code{INLINE_GENERIC}
23553
23554 @item @code{SUPPRESS_ALL}
23555
23556 @item @code{PASSIVE}
23557 @end itemize
23558
23559 @noindent
23560 In GNAT, optimization is controlled strictly by command
23561 line parameters, as described in the corresponding section of this guide.
23562 The HP pragmas for control of optimization are
23563 recognized but ignored.
23564
23565 Note that in GNAT, the default is optimization off, whereas in HP Ada
23566 the default is that optimization is turned on.
23567
23568 @node Program Compilation and Library Management
23569 @section Program Compilation and Library Management
23570
23571 @noindent
23572 HP Ada and GNAT provide a comparable set of commands to
23573 build programs. HP Ada also provides a program library,
23574 which is a concept that does not exist on GNAT. Instead,
23575 GNAT provides directories of sources that are compiled as
23576 needed.
23577
23578 The following table summarizes
23579 the HP Ada commands and provides
23580 equivalent GNAT commands. In this table, some GNAT
23581 equivalents reflect the fact that GNAT does not use the
23582 concept of a program library. Instead, it uses a model
23583 in which collections of source and object files are used
23584 in a manner consistent with other languages like C and
23585 Fortran. Therefore, standard system file commands are used
23586 to manipulate these elements. Those GNAT commands are marked with
23587 an asterisk.
23588 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
23589
23590 @need 1500
23591 @multitable @columnfractions .35 .65
23592
23593 @item @emph{HP Ada Command}
23594 @tab @emph{GNAT Equivalent / Description}
23595
23596 @item @command{ADA}
23597 @tab @command{GNAT COMPILE}@*
23598 Invokes the compiler to compile one or more Ada source files.
23599
23600 @item @command{ACS ATTACH}@*
23601 @tab [No equivalent]@*
23602 Switches control of terminal from current process running the program
23603 library manager.
23604
23605 @item @command{ACS CHECK}
23606 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
23607 Forms the execution closure of one
23608 or more compiled units and checks completeness and currency.
23609
23610 @item @command{ACS COMPILE}
23611 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23612 Forms the execution closure of one or
23613 more specified units, checks completeness and currency,
23614 identifies units that have revised source files, compiles same,
23615 and recompiles units that are or will become obsolete.
23616 Also completes incomplete generic instantiations.
23617
23618 @item @command{ACS COPY FOREIGN}
23619 @tab Copy (*)@*
23620 Copies a foreign object file into the program library as a
23621 library unit body.
23622
23623 @item @command{ACS COPY UNIT}
23624 @tab Copy (*)@*
23625 Copies a compiled unit from one program library to another.
23626
23627 @item @command{ACS CREATE LIBRARY}
23628 @tab Create /directory (*)@*
23629 Creates a program library.
23630
23631 @item @command{ACS CREATE SUBLIBRARY}
23632 @tab Create /directory (*)@*
23633 Creates a program sublibrary.
23634
23635 @item @command{ACS DELETE LIBRARY}
23636 @tab @*
23637 Deletes a program library and its contents.
23638
23639 @item @command{ACS DELETE SUBLIBRARY}
23640 @tab @*
23641 Deletes a program sublibrary and its contents.
23642
23643 @item @command{ACS DELETE UNIT}
23644 @tab Delete file (*)@*
23645 On OpenVMS systems, deletes one or more compiled units from
23646 the current program library.
23647
23648 @item @command{ACS DIRECTORY}
23649 @tab Directory (*)@*
23650 On OpenVMS systems, lists units contained in the current
23651 program library.
23652
23653 @item @command{ACS ENTER FOREIGN}
23654 @tab Copy (*)@*
23655 Allows the import of a foreign body as an Ada library
23656 spec and enters a reference to a pointer.
23657
23658 @item @command{ACS ENTER UNIT}
23659 @tab Copy (*)@*
23660 Enters a reference (pointer) from the current program library to
23661 a unit compiled into another program library.
23662
23663 @item @command{ACS EXIT}
23664 @tab [No equivalent]@*
23665 Exits from the program library manager.
23666
23667 @item @command{ACS EXPORT}
23668 @tab Copy (*)@*
23669 Creates an object file that contains system-specific object code
23670 for one or more units. With GNAT, object files can simply be copied
23671 into the desired directory.
23672
23673 @item @command{ACS EXTRACT SOURCE}
23674 @tab Copy (*)@*
23675 Allows access to the copied source file for each Ada compilation unit
23676
23677 @item @command{ACS HELP}
23678 @tab @command{HELP GNAT}@*
23679 Provides online help.
23680
23681 @item @command{ACS LINK}
23682 @tab @command{GNAT LINK}@*
23683 Links an object file containing Ada units into an executable file.
23684
23685 @item @command{ACS LOAD}
23686 @tab Copy (*)@*
23687 Loads (partially compiles) Ada units into the program library.
23688 Allows loading a program from a collection of files into a library
23689 without knowing the relationship among units.
23690
23691 @item @command{ACS MERGE}
23692 @tab Copy (*)@*
23693 Merges into the current program library, one or more units from
23694 another library where they were modified.
23695
23696 @item @command{ACS RECOMPILE}
23697 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23698 Recompiles from external or copied source files any obsolete
23699 unit in the closure. Also, completes any incomplete generic
23700 instantiations.
23701
23702 @item @command{ACS REENTER}
23703 @tab @command{GNAT MAKE}@*
23704 Reenters current references to units compiled after last entered
23705 with the @command{ACS ENTER UNIT} command.
23706
23707 @item @command{ACS SET LIBRARY}
23708 @tab Set default (*)@*
23709 Defines a program library to be the compilation context as well
23710 as the target library for compiler output and commands in general.
23711
23712 @item @command{ACS SET PRAGMA}
23713 @tab Edit @file{gnat.adc} (*)@*
23714 Redefines specified values of the library characteristics
23715 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
23716 and @code{Float_Representation}.
23717
23718 @item @command{ACS SET SOURCE}
23719 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
23720 Defines the source file search list for the @command{ACS COMPILE} command.
23721
23722 @item @command{ACS SHOW LIBRARY}
23723 @tab Directory (*)@*
23724 Lists information about one or more program libraries.
23725
23726 @item @command{ACS SHOW PROGRAM}
23727 @tab [No equivalent]@*
23728 Lists information about the execution closure of one or
23729 more units in the program library.
23730
23731 @item @command{ACS SHOW SOURCE}
23732 @tab Show logical @code{ADA_INCLUDE_PATH}@*
23733 Shows the source file search used when compiling units.
23734
23735 @item @command{ACS SHOW VERSION}
23736 @tab Compile with @option{VERBOSE} option
23737 Displays the version number of the compiler and program library
23738 manager used.
23739
23740 @item @command{ACS SPAWN}
23741 @tab [No equivalent]@*
23742 Creates a subprocess of the current process (same as @command{DCL SPAWN}
23743 command).
23744
23745 @item @command{ACS VERIFY}
23746 @tab [No equivalent]@*
23747 Performs a series of consistency checks on a program library to
23748 determine whether the library structure and library files are in
23749 valid form.
23750 @end multitable
23751
23752 @noindent
23753
23754 @node Input-Output
23755 @section Input-Output
23756
23757 @noindent
23758 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
23759 Management Services (RMS) to perform operations on
23760 external files.
23761
23762 @noindent
23763 HP Ada and GNAT predefine an identical set of input-
23764 output packages. To make the use of the
23765 generic @code{TEXT_IO} operations more convenient, HP Ada
23766 provides predefined library packages that instantiate the
23767 integer and floating-point operations for the predefined
23768 integer and floating-point types as shown in the following table.
23769
23770 @multitable @columnfractions .45 .55
23771 @item @emph{Package Name} @tab Instantiation
23772
23773 @item @code{INTEGER_TEXT_IO}
23774 @tab @code{INTEGER_IO(INTEGER)}
23775
23776 @item @code{SHORT_INTEGER_TEXT_IO}
23777 @tab @code{INTEGER_IO(SHORT_INTEGER)}
23778
23779 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
23780 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
23781
23782 @item @code{FLOAT_TEXT_IO}
23783 @tab @code{FLOAT_IO(FLOAT)}
23784
23785 @item @code{LONG_FLOAT_TEXT_IO}
23786 @tab @code{FLOAT_IO(LONG_FLOAT)}
23787 @end multitable
23788
23789 @noindent
23790 The HP Ada predefined packages and their operations
23791 are implemented using OpenVMS Alpha files and input-output
23792 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
23793 Familiarity with the following is recommended:
23794 @itemize @bullet
23795 @item RMS file organizations and access methods
23796
23797 @item OpenVMS file specifications and directories
23798
23799 @item OpenVMS File Definition Language (FDL)
23800 @end itemize
23801
23802 @noindent
23803 GNAT provides I/O facilities that are completely
23804 compatible with HP Ada. The distribution includes the
23805 standard HP Ada versions of all I/O packages, operating
23806 in a manner compatible with HP Ada. In particular, the
23807 following packages are by default the HP Ada (Ada 83)
23808 versions of these packages rather than the renamings
23809 suggested in Annex J of the Ada Reference Manual:
23810 @itemize @bullet
23811 @item @code{TEXT_IO}
23812
23813 @item @code{SEQUENTIAL_IO}
23814
23815 @item @code{DIRECT_IO}
23816 @end itemize
23817
23818 @noindent
23819 The use of the standard child package syntax (for
23820 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
23821 packages.
23822 GNAT provides HP-compatible predefined instantiations
23823 of the @code{TEXT_IO} packages, and also
23824 provides the standard predefined instantiations required
23825 by the @cite{Ada Reference Manual}.
23826
23827 For further information on how GNAT interfaces to the file
23828 system or how I/O is implemented in programs written in
23829 mixed languages, see @ref{Implementation of the Standard I/O,,,
23830 gnat_rm, GNAT Reference Manual}.
23831 This chapter covers the following:
23832 @itemize @bullet
23833 @item Standard I/O packages
23834
23835 @item @code{FORM} strings
23836
23837 @item @code{ADA.DIRECT_IO}
23838
23839 @item @code{ADA.SEQUENTIAL_IO}
23840
23841 @item @code{ADA.TEXT_IO}
23842
23843 @item Stream pointer positioning
23844
23845 @item Reading and writing non-regular files
23846
23847 @item @code{GET_IMMEDIATE}
23848
23849 @item Treating @code{TEXT_IO} files as streams
23850
23851 @item Shared files
23852
23853 @item Open modes
23854 @end itemize
23855
23856 @node Implementation Limits
23857 @section Implementation Limits
23858
23859 @noindent
23860 The following table lists implementation limits for HP Ada
23861 and GNAT systems.
23862 @multitable @columnfractions .60 .20 .20
23863 @sp 1
23864 @item @emph{Compilation Parameter}
23865 @tab @emph{HP Ada}
23866 @tab @emph{GNAT}
23867 @sp 1
23868
23869 @item In a subprogram or entry declaration, maximum number of
23870 formal parameters that are of an unconstrained record type
23871 @tab 32
23872 @tab No set limit
23873 @sp 1
23874
23875 @item Maximum identifier length (number of characters)
23876 @tab 255
23877 @tab 32766
23878 @sp 1
23879
23880 @item Maximum number of characters in a source line
23881 @tab 255
23882 @tab 32766
23883 @sp 1
23884
23885 @item Maximum collection size (number of bytes)
23886 @tab 2**31-1
23887 @tab 2**31-1
23888 @sp 1
23889
23890 @item Maximum number of discriminants for a record type
23891 @tab 245
23892 @tab No set limit
23893 @sp 1
23894
23895 @item Maximum number of formal parameters in an entry or
23896 subprogram declaration
23897 @tab 246
23898 @tab No set limit
23899 @sp 1
23900
23901 @item Maximum number of dimensions in an array type
23902 @tab 255
23903 @tab No set limit
23904 @sp 1
23905
23906 @item Maximum number of library units and subunits in a compilation.
23907 @tab 4095
23908 @tab No set limit
23909 @sp 1
23910
23911 @item Maximum number of library units and subunits in an execution.
23912 @tab 16383
23913 @tab No set limit
23914 @sp 1
23915
23916 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
23917 or @code{PSECT_OBJECT}
23918 @tab 32757
23919 @tab No set limit
23920 @sp 1
23921
23922 @item Maximum number of enumeration literals in an enumeration type
23923 definition
23924 @tab 65535
23925 @tab No set limit
23926 @sp 1
23927
23928 @item Maximum number of lines in a source file
23929 @tab 65534
23930 @tab No set limit
23931 @sp 1
23932
23933 @item Maximum number of bits in any object
23934 @tab 2**31-1
23935 @tab 2**31-1
23936 @sp 1
23937
23938 @item Maximum size of the static portion of a stack frame (approximate)
23939 @tab 2**31-1
23940 @tab 2**31-1
23941 @end multitable
23942
23943 @node Tools and Utilities
23944 @section Tools and Utilities
23945
23946 @noindent
23947 The following table lists some of the OpenVMS development tools
23948 available for HP Ada, and the corresponding tools for
23949 use with @value{EDITION} on Alpha and I64 platforms.
23950 Aside from the debugger, all the OpenVMS tools identified are part
23951 of the DECset package.
23952
23953 @iftex
23954 @c Specify table in TeX since Texinfo does a poor job
23955 @tex
23956 \smallskip
23957 \smallskip
23958 \settabs\+Language-Sensitive Editor\quad
23959 &Product with HP Ada\quad
23960 &\cr
23961 \+\it Tool
23962 &\it Product with HP Ada
23963 & \it Product with @value{EDITION}\cr
23964 \smallskip
23965 \+Code Management System
23966 &HP CMS
23967 & HP CMS\cr
23968 \smallskip
23969 \+Language-Sensitive Editor
23970 &HP LSE
23971 & emacs or HP LSE (Alpha)\cr
23972 \+
23973 &
23974 & HP LSE (I64)\cr
23975 \smallskip
23976 \+Debugger
23977 &OpenVMS Debug
23978 & gdb (Alpha),\cr
23979 \+
23980 &
23981 & OpenVMS Debug (I64)\cr
23982 \smallskip
23983 \+Source Code Analyzer /
23984 &HP SCA
23985 & GNAT XREF\cr
23986 \+Cross Referencer
23987 &
23988 &\cr
23989 \smallskip
23990 \+Test Manager
23991 &HP Digital Test
23992 & HP DTM\cr
23993 \+
23994 &Manager (DTM)
23995 &\cr
23996 \smallskip
23997 \+Performance and
23998 & HP PCA
23999 & HP PCA\cr
24000 \+Coverage Analyzer
24001 &
24002 &\cr
24003 \smallskip
24004 \+Module Management
24005 & HP MMS
24006 & Not applicable\cr
24007 \+ System
24008 &
24009 &\cr
24010 \smallskip
24011 \smallskip
24012 @end tex
24013 @end iftex
24014
24015 @ifnottex
24016 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
24017 @c the TeX version above for the printed version
24018 @flushleft
24019 @c @multitable @columnfractions .3 .4 .4
24020 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
24021 @item @i{Tool}
24022 @tab @i{Tool with HP Ada}
24023 @tab @i{Tool with @value{EDITION}}
24024 @item Code Management@*System
24025 @tab HP CMS
24026 @tab HP CMS
24027 @item Language-Sensitive@*Editor
24028 @tab HP LSE
24029 @tab emacs or HP LSE (Alpha)
24030 @item
24031 @tab
24032 @tab HP LSE (I64)
24033 @item Debugger
24034 @tab OpenVMS Debug
24035 @tab gdb (Alpha),
24036 @item
24037 @tab
24038 @tab OpenVMS Debug (I64)
24039 @item Source Code Analyzer /@*Cross Referencer
24040 @tab HP SCA
24041 @tab GNAT XREF
24042 @item Test Manager
24043 @tab HP Digital Test@*Manager (DTM)
24044 @tab HP DTM
24045 @item Performance and@*Coverage Analyzer
24046 @tab HP PCA
24047 @tab HP PCA
24048 @item Module Management@*System
24049 @tab HP MMS
24050 @tab Not applicable
24051 @end multitable
24052 @end flushleft
24053 @end ifnottex
24054
24055 @end ifset
24056
24057 @c **************************************
24058 @node Platform-Specific Information for the Run-Time Libraries
24059 @appendix Platform-Specific Information for the Run-Time Libraries
24060 @cindex Tasking and threads libraries
24061 @cindex Threads libraries and tasking
24062 @cindex Run-time libraries (platform-specific information)
24063
24064 @noindent
24065 The GNAT run-time implementation may vary with respect to both the
24066 underlying threads library and the exception handling scheme.
24067 For threads support, one or more of the following are supplied:
24068 @itemize @bullet
24069 @item @b{native threads library}, a binding to the thread package from
24070 the underlying operating system
24071
24072 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
24073 POSIX thread package
24074 @end itemize
24075
24076 @noindent
24077 For exception handling, either or both of two models are supplied:
24078 @itemize @bullet
24079 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
24080 Most programs should experience a substantial speed improvement by
24081 being compiled with a ZCX run-time.
24082 This is especially true for
24083 tasking applications or applications with many exception handlers.}
24084 @cindex Zero-Cost Exceptions
24085 @cindex ZCX (Zero-Cost Exceptions)
24086 which uses binder-generated tables that
24087 are interrogated at run time to locate a handler
24088
24089 @item @b{setjmp / longjmp} (``SJLJ''),
24090 @cindex setjmp/longjmp Exception Model
24091 @cindex SJLJ (setjmp/longjmp Exception Model)
24092 which uses dynamically-set data to establish
24093 the set of handlers
24094 @end itemize
24095
24096 @noindent
24097 This appendix summarizes which combinations of threads and exception support
24098 are supplied on various GNAT platforms.
24099 It then shows how to select a particular library either
24100 permanently or temporarily,
24101 explains the properties of (and tradeoffs among) the various threads
24102 libraries, and provides some additional
24103 information about several specific platforms.
24104
24105 @menu
24106 * Summary of Run-Time Configurations::
24107 * Specifying a Run-Time Library::
24108 * Choosing the Scheduling Policy::
24109 * Solaris-Specific Considerations::
24110 * Linux-Specific Considerations::
24111 * AIX-Specific Considerations::
24112 * RTX-Specific Considerations::
24113 * HP-UX-Specific Considerations::
24114 @end menu
24115
24116 @node Summary of Run-Time Configurations
24117 @section Summary of Run-Time Configurations
24118
24119 @multitable @columnfractions .30 .70
24120 @item @b{alpha-openvms}
24121 @item @code{@ @ }@i{rts-native (default)}
24122 @item @code{@ @ @ @ }Tasking @tab native VMS threads
24123 @item @code{@ @ @ @ }Exceptions @tab ZCX
24124 @*
24125 @item @code{@ @ }@i{rts-sjlj}
24126 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
24127 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24128 @*
24129 @item @b{ia64-hp_linux}
24130 @item @code{@ @ }@i{rts-native (default)}
24131 @item @code{@ @ @ @ }Tasking @tab pthread library
24132 @item @code{@ @ @ @ }Exceptions @tab ZCX
24133 @*
24134 @item @b{ia64-hpux}
24135 @item @code{@ @ }@i{rts-native (default)}
24136 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
24137 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24138 @*
24139 @item @b{ia64-openvms}
24140 @item @code{@ @ }@i{rts-native (default)}
24141 @item @code{@ @ @ @ }Tasking @tab native VMS threads
24142 @item @code{@ @ @ @ }Exceptions @tab ZCX
24143 @*
24144 @item @b{ia64-sgi_linux}
24145 @item @code{@ @ }@i{rts-native (default)}
24146 @item @code{@ @ @ @ }Tasking @tab pthread library
24147 @item @code{@ @ @ @ }Exceptions @tab ZCX
24148 @*
24149 @item @b{pa-hpux}
24150 @item @code{@ @ }@i{rts-native (default)}
24151 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
24152 @item @code{@ @ @ @ }Exceptions @tab ZCX
24153 @*
24154 @item @code{@ @ }@i{rts-sjlj}
24155 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
24156 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24157 @*
24158 @item @b{ppc-aix}
24159 @item @code{@ @ }@i{rts-native (default)}
24160 @item @code{@ @ @ @ }Tasking @tab native AIX threads
24161 @item @code{@ @ @ @ }Exceptions @tab ZCX
24162 @*
24163 @item @code{@ @ }@i{rts-sjlj}
24164 @item @code{@ @ @ @ }Tasking @tab native AIX threads
24165 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24166 @*
24167 @item @b{ppc-darwin}
24168 @item @code{@ @ }@i{rts-native (default)}
24169 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
24170 @item @code{@ @ @ @ }Exceptions @tab ZCX
24171 @*
24172 @item @b{sparc-solaris} @tab
24173 @item @code{@ @ }@i{rts-native (default)}
24174 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24175 @item @code{@ @ @ @ }Exceptions @tab ZCX
24176 @*
24177 @item @code{@ @ }@i{rts-pthread}
24178 @item @code{@ @ @ @ }Tasking @tab pthread library
24179 @item @code{@ @ @ @ }Exceptions @tab ZCX
24180 @*
24181 @item @code{@ @ }@i{rts-sjlj}
24182 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24183 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24184 @*
24185 @item @b{sparc64-solaris} @tab
24186 @item @code{@ @ }@i{rts-native (default)}
24187 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24188 @item @code{@ @ @ @ }Exceptions @tab ZCX
24189 @*
24190 @item @b{x86-linux}
24191 @item @code{@ @ }@i{rts-native (default)}
24192 @item @code{@ @ @ @ }Tasking @tab pthread library
24193 @item @code{@ @ @ @ }Exceptions @tab ZCX
24194 @*
24195 @item @code{@ @ }@i{rts-sjlj}
24196 @item @code{@ @ @ @ }Tasking @tab pthread library
24197 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24198 @*
24199 @item @b{x86-lynx}
24200 @item @code{@ @ }@i{rts-native (default)}
24201 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
24202 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24203 @*
24204 @item @b{x86-solaris}
24205 @item @code{@ @ }@i{rts-native (default)}
24206 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
24207 @item @code{@ @ @ @ }Exceptions @tab ZCX
24208 @*
24209 @item @code{@ @ }@i{rts-sjlj}
24210 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24211 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24212 @*
24213 @item @b{x86-windows}
24214 @item @code{@ @ }@i{rts-native (default)}
24215 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
24216 @item @code{@ @ @ @ }Exceptions @tab ZCX
24217 @*
24218 @item @code{@ @ }@i{rts-sjlj}
24219 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
24220 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24221 @*
24222 @item @b{x86-windows-rtx}
24223 @item @code{@ @ }@i{rts-rtx-rtss (default)}
24224 @item @code{@ @ @ @ }Tasking @tab RTX real-time subsystem RTSS threads (kernel mode)
24225 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24226 @*
24227 @item @code{@ @ }@i{rts-rtx-w32}
24228 @item @code{@ @ @ @ }Tasking @tab RTX Win32 threads (user mode)
24229 @item @code{@ @ @ @ }Exceptions @tab ZCX
24230 @*
24231 @item @b{x86_64-linux}
24232 @item @code{@ @ }@i{rts-native (default)}
24233 @item @code{@ @ @ @ }Tasking @tab pthread library
24234 @item @code{@ @ @ @ }Exceptions @tab ZCX
24235 @*
24236 @item @code{@ @ }@i{rts-sjlj}
24237 @item @code{@ @ @ @ }Tasking @tab pthread library
24238 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24239 @*
24240 @end multitable
24241
24242 @node Specifying a Run-Time Library
24243 @section Specifying a Run-Time Library
24244
24245 @noindent
24246 The @file{adainclude} subdirectory containing the sources of the GNAT
24247 run-time library, and the @file{adalib} subdirectory containing the
24248 @file{ALI} files and the static and/or shared GNAT library, are located
24249 in the gcc target-dependent area:
24250
24251 @smallexample
24252 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
24253 @end smallexample
24254
24255 @noindent
24256 As indicated above, on some platforms several run-time libraries are supplied.
24257 These libraries are installed in the target dependent area and
24258 contain a complete source and binary subdirectory. The detailed description
24259 below explains the differences between the different libraries in terms of
24260 their thread support.
24261
24262 The default run-time library (when GNAT is installed) is @emph{rts-native}.
24263 This default run time is selected by the means of soft links.
24264 For example on x86-linux:
24265
24266 @smallexample
24267 @group
24268 $(target-dir)
24269 |
24270 +--- adainclude----------+
24271 | |
24272 +--- adalib-----------+ |
24273 | | |
24274 +--- rts-native | |
24275 | | | |
24276 | +--- adainclude <---+
24277 | | |
24278 | +--- adalib <----+
24279 |
24280 +--- rts-sjlj
24281 |
24282 +--- adainclude
24283 |
24284 +--- adalib
24285 @end group
24286 @end smallexample
24287
24288 @noindent
24289 If the @i{rts-sjlj} library is to be selected on a permanent basis,
24290 these soft links can be modified with the following commands:
24291
24292 @smallexample
24293 $ cd $target
24294 $ rm -f adainclude adalib
24295 $ ln -s rts-sjlj/adainclude adainclude
24296 $ ln -s rts-sjlj/adalib adalib
24297 @end smallexample
24298
24299 @noindent
24300 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
24301 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
24302 @file{$target/ada_object_path}.
24303
24304 Selecting another run-time library temporarily can be
24305 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
24306 @cindex @option{--RTS} option
24307
24308 @node Choosing the Scheduling Policy
24309 @section Choosing the Scheduling Policy
24310
24311 @noindent
24312 When using a POSIX threads implementation, you have a choice of several
24313 scheduling policies: @code{SCHED_FIFO},
24314 @cindex @code{SCHED_FIFO} scheduling policy
24315 @code{SCHED_RR}
24316 @cindex @code{SCHED_RR} scheduling policy
24317 and @code{SCHED_OTHER}.
24318 @cindex @code{SCHED_OTHER} scheduling policy
24319 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
24320 or @code{SCHED_RR} requires special (e.g., root) privileges.
24321
24322 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
24323 @code{SCHED_FIFO},
24324 @cindex @code{SCHED_FIFO} scheduling policy
24325 you can use one of the following:
24326
24327 @itemize @bullet
24328 @item
24329 @code{pragma Time_Slice (0.0)}
24330 @cindex pragma Time_Slice
24331 @item
24332 the corresponding binder option @option{-T0}
24333 @cindex @option{-T0} option
24334 @item
24335 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
24336 @cindex pragma Task_Dispatching_Policy
24337 @end itemize
24338
24339 @noindent
24340 To specify @code{SCHED_RR},
24341 @cindex @code{SCHED_RR} scheduling policy
24342 you should use @code{pragma Time_Slice} with a
24343 value greater than @code{0.0}, or else use the corresponding @option{-T}
24344 binder option.
24345
24346 @node Solaris-Specific Considerations
24347 @section Solaris-Specific Considerations
24348 @cindex Solaris Sparc threads libraries
24349
24350 @noindent
24351 This section addresses some topics related to the various threads libraries
24352 on Sparc Solaris.
24353
24354 @menu
24355 * Solaris Threads Issues::
24356 @end menu
24357
24358 @node Solaris Threads Issues
24359 @subsection Solaris Threads Issues
24360
24361 @noindent
24362 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
24363 library based on POSIX threads --- @emph{rts-pthread}.
24364 @cindex rts-pthread threads library
24365 This run-time library has the advantage of being mostly shared across all
24366 POSIX-compliant thread implementations, and it also provides under
24367 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
24368 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
24369 and @code{PTHREAD_PRIO_PROTECT}
24370 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
24371 semantics that can be selected using the predefined pragma
24372 @code{Locking_Policy}
24373 @cindex pragma Locking_Policy (under rts-pthread)
24374 with respectively
24375 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
24376 @cindex @code{Inheritance_Locking} (under rts-pthread)
24377 @cindex @code{Ceiling_Locking} (under rts-pthread)
24378
24379 As explained above, the native run-time library is based on the Solaris thread
24380 library (@code{libthread}) and is the default library.
24381
24382 When the Solaris threads library is used (this is the default), programs
24383 compiled with GNAT can automatically take advantage of
24384 and can thus execute on multiple processors.
24385 The user can alternatively specify a processor on which the program should run
24386 to emulate a single-processor system. The multiprocessor / uniprocessor choice
24387 is made by
24388 setting the environment variable @env{GNAT_PROCESSOR}
24389 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
24390 to one of the following:
24391
24392 @table @code
24393 @item -2
24394 Use the default configuration (run the program on all
24395 available processors) - this is the same as having @code{GNAT_PROCESSOR}
24396 unset
24397
24398 @item -1
24399 Let the run-time implementation choose one processor and run the program on
24400 that processor
24401
24402 @item 0 .. Last_Proc
24403 Run the program on the specified processor.
24404 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
24405 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
24406 @end table
24407
24408 @node Linux-Specific Considerations
24409 @section Linux-Specific Considerations
24410 @cindex Linux threads libraries
24411
24412 @noindent
24413 On GNU/Linux without NPTL support (usually system with GNU C Library
24414 older than 2.3), the signal model is not POSIX compliant, which means
24415 that to send a signal to the process, you need to send the signal to all
24416 threads, e.g.@: by using @code{killpg()}.
24417
24418 @node AIX-Specific Considerations
24419 @section AIX-Specific Considerations
24420 @cindex AIX resolver library
24421
24422 @noindent
24423 On AIX, the resolver library initializes some internal structure on
24424 the first call to @code{get*by*} functions, which are used to implement
24425 @code{GNAT.Sockets.Get_Host_By_Name} and
24426 @code{GNAT.Sockets.Get_Host_By_Address}.
24427 If such initialization occurs within an Ada task, and the stack size for
24428 the task is the default size, a stack overflow may occur.
24429
24430 To avoid this overflow, the user should either ensure that the first call
24431 to @code{GNAT.Sockets.Get_Host_By_Name} or
24432 @code{GNAT.Sockets.Get_Host_By_Addrss}
24433 occurs in the environment task, or use @code{pragma Storage_Size} to
24434 specify a sufficiently large size for the stack of the task that contains
24435 this call.
24436
24437 @node RTX-Specific Considerations
24438 @section RTX-Specific Considerations
24439 @cindex RTX libraries
24440
24441 @noindent
24442 The Real-time Extension (RTX) to Windows is based on the Windows Win32
24443 API. Applications can be built to work in two different modes:
24444
24445 @itemize @bullet
24446 @item
24447 Windows executables that run in Ring 3 to utilize memory protection
24448 (@emph{rts-rtx-w32}).
24449
24450 @item
24451 Real-time subsystem (RTSS) executables that run in Ring 0, where
24452 performance can be optimized with RTSS applications taking precedent
24453 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
24454 the Microsoft linker to handle RTSS libraries.
24455
24456 @end itemize
24457
24458 @node HP-UX-Specific Considerations
24459 @section HP-UX-Specific Considerations
24460 @cindex HP-UX Scheduling
24461
24462 @noindent
24463 On HP-UX, appropriate privileges are required to change the scheduling
24464 parameters of a task. The calling process must have appropriate
24465 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
24466 successfully change the scheduling parameters.
24467
24468 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
24469 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
24470 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
24471
24472 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
24473 one of the following:
24474
24475 @itemize @bullet
24476 @item
24477 @code{pragma Time_Slice (0.0)}
24478 @cindex pragma Time_Slice
24479 @item
24480 the corresponding binder option @option{-T0}
24481 @cindex @option{-T0} option
24482 @item
24483 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
24484 @cindex pragma Task_Dispatching_Policy
24485 @end itemize
24486
24487 @noindent
24488 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
24489 you should use @code{pragma Time_Slice} with a
24490 value greater than @code{0.0}, or use the corresponding @option{-T}
24491 binder option, or set the @code{pragma Task_Dispatching_Policy
24492 (Round_Robin_Within_Priorities)}.
24493
24494 @c *******************************
24495 @node Example of Binder Output File
24496 @appendix Example of Binder Output File
24497
24498 @noindent
24499 This Appendix displays the source code for @command{gnatbind}'s output
24500 file generated for a simple ``Hello World'' program.
24501 Comments have been added for clarification purposes.
24502
24503 @smallexample @c adanocomment
24504 @iftex
24505 @leftskip=0cm
24506 @end iftex
24507 -- The package is called Ada_Main unless this name is actually used
24508 -- as a unit name in the partition, in which case some other unique
24509 -- name is used.
24510
24511 with System;
24512 package ada_main is
24513
24514 Elab_Final_Code : Integer;
24515 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
24516
24517 -- The main program saves the parameters (argument count,
24518 -- argument values, environment pointer) in global variables
24519 -- for later access by other units including
24520 -- Ada.Command_Line.
24521
24522 gnat_argc : Integer;
24523 gnat_argv : System.Address;
24524 gnat_envp : System.Address;
24525
24526 -- The actual variables are stored in a library routine. This
24527 -- is useful for some shared library situations, where there
24528 -- are problems if variables are not in the library.
24529
24530 pragma Import (C, gnat_argc);
24531 pragma Import (C, gnat_argv);
24532 pragma Import (C, gnat_envp);
24533
24534 -- The exit status is similarly an external location
24535
24536 gnat_exit_status : Integer;
24537 pragma Import (C, gnat_exit_status);
24538
24539 GNAT_Version : constant String :=
24540 "GNAT Version: 6.0.0w (20061115)";
24541 pragma Export (C, GNAT_Version, "__gnat_version");
24542
24543 -- This is the generated adafinal routine that performs
24544 -- finalization at the end of execution. In the case where
24545 -- Ada is the main program, this main program makes a call
24546 -- to adafinal at program termination.
24547
24548 procedure adafinal;
24549 pragma Export (C, adafinal, "adafinal");
24550
24551 -- This is the generated adainit routine that performs
24552 -- initialization at the start of execution. In the case
24553 -- where Ada is the main program, this main program makes
24554 -- a call to adainit at program startup.
24555
24556 procedure adainit;
24557 pragma Export (C, adainit, "adainit");
24558
24559 -- This routine is called at the start of execution. It is
24560 -- a dummy routine that is used by the debugger to breakpoint
24561 -- at the start of execution.
24562
24563 procedure Break_Start;
24564 pragma Import (C, Break_Start, "__gnat_break_start");
24565
24566 -- This is the actual generated main program (it would be
24567 -- suppressed if the no main program switch were used). As
24568 -- required by standard system conventions, this program has
24569 -- the external name main.
24570
24571 function main
24572 (argc : Integer;
24573 argv : System.Address;
24574 envp : System.Address)
24575 return Integer;
24576 pragma Export (C, main, "main");
24577
24578 -- The following set of constants give the version
24579 -- identification values for every unit in the bound
24580 -- partition. This identification is computed from all
24581 -- dependent semantic units, and corresponds to the
24582 -- string that would be returned by use of the
24583 -- Body_Version or Version attributes.
24584
24585 type Version_32 is mod 2 ** 32;
24586 u00001 : constant Version_32 := 16#7880BEB3#;
24587 u00002 : constant Version_32 := 16#0D24CBD0#;
24588 u00003 : constant Version_32 := 16#3283DBEB#;
24589 u00004 : constant Version_32 := 16#2359F9ED#;
24590 u00005 : constant Version_32 := 16#664FB847#;
24591 u00006 : constant Version_32 := 16#68E803DF#;
24592 u00007 : constant Version_32 := 16#5572E604#;
24593 u00008 : constant Version_32 := 16#46B173D8#;
24594 u00009 : constant Version_32 := 16#156A40CF#;
24595 u00010 : constant Version_32 := 16#033DABE0#;
24596 u00011 : constant Version_32 := 16#6AB38FEA#;
24597 u00012 : constant Version_32 := 16#22B6217D#;
24598 u00013 : constant Version_32 := 16#68A22947#;
24599 u00014 : constant Version_32 := 16#18CC4A56#;
24600 u00015 : constant Version_32 := 16#08258E1B#;
24601 u00016 : constant Version_32 := 16#367D5222#;
24602 u00017 : constant Version_32 := 16#20C9ECA4#;
24603 u00018 : constant Version_32 := 16#50D32CB6#;
24604 u00019 : constant Version_32 := 16#39A8BB77#;
24605 u00020 : constant Version_32 := 16#5CF8FA2B#;
24606 u00021 : constant Version_32 := 16#2F1EB794#;
24607 u00022 : constant Version_32 := 16#31AB6444#;
24608 u00023 : constant Version_32 := 16#1574B6E9#;
24609 u00024 : constant Version_32 := 16#5109C189#;
24610 u00025 : constant Version_32 := 16#56D770CD#;
24611 u00026 : constant Version_32 := 16#02F9DE3D#;
24612 u00027 : constant Version_32 := 16#08AB6B2C#;
24613 u00028 : constant Version_32 := 16#3FA37670#;
24614 u00029 : constant Version_32 := 16#476457A0#;
24615 u00030 : constant Version_32 := 16#731E1B6E#;
24616 u00031 : constant Version_32 := 16#23C2E789#;
24617 u00032 : constant Version_32 := 16#0F1BD6A1#;
24618 u00033 : constant Version_32 := 16#7C25DE96#;
24619 u00034 : constant Version_32 := 16#39ADFFA2#;
24620 u00035 : constant Version_32 := 16#571DE3E7#;
24621 u00036 : constant Version_32 := 16#5EB646AB#;
24622 u00037 : constant Version_32 := 16#4249379B#;
24623 u00038 : constant Version_32 := 16#0357E00A#;
24624 u00039 : constant Version_32 := 16#3784FB72#;
24625 u00040 : constant Version_32 := 16#2E723019#;
24626 u00041 : constant Version_32 := 16#623358EA#;
24627 u00042 : constant Version_32 := 16#107F9465#;
24628 u00043 : constant Version_32 := 16#6843F68A#;
24629 u00044 : constant Version_32 := 16#63305874#;
24630 u00045 : constant Version_32 := 16#31E56CE1#;
24631 u00046 : constant Version_32 := 16#02917970#;
24632 u00047 : constant Version_32 := 16#6CCBA70E#;
24633 u00048 : constant Version_32 := 16#41CD4204#;
24634 u00049 : constant Version_32 := 16#572E3F58#;
24635 u00050 : constant Version_32 := 16#20729FF5#;
24636 u00051 : constant Version_32 := 16#1D4F93E8#;
24637 u00052 : constant Version_32 := 16#30B2EC3D#;
24638 u00053 : constant Version_32 := 16#34054F96#;
24639 u00054 : constant Version_32 := 16#5A199860#;
24640 u00055 : constant Version_32 := 16#0E7F912B#;
24641 u00056 : constant Version_32 := 16#5760634A#;
24642 u00057 : constant Version_32 := 16#5D851835#;
24643
24644 -- The following Export pragmas export the version numbers
24645 -- with symbolic names ending in B (for body) or S
24646 -- (for spec) so that they can be located in a link. The
24647 -- information provided here is sufficient to track down
24648 -- the exact versions of units used in a given build.
24649
24650 pragma Export (C, u00001, "helloB");
24651 pragma Export (C, u00002, "system__standard_libraryB");
24652 pragma Export (C, u00003, "system__standard_libraryS");
24653 pragma Export (C, u00004, "adaS");
24654 pragma Export (C, u00005, "ada__text_ioB");
24655 pragma Export (C, u00006, "ada__text_ioS");
24656 pragma Export (C, u00007, "ada__exceptionsB");
24657 pragma Export (C, u00008, "ada__exceptionsS");
24658 pragma Export (C, u00009, "gnatS");
24659 pragma Export (C, u00010, "gnat__heap_sort_aB");
24660 pragma Export (C, u00011, "gnat__heap_sort_aS");
24661 pragma Export (C, u00012, "systemS");
24662 pragma Export (C, u00013, "system__exception_tableB");
24663 pragma Export (C, u00014, "system__exception_tableS");
24664 pragma Export (C, u00015, "gnat__htableB");
24665 pragma Export (C, u00016, "gnat__htableS");
24666 pragma Export (C, u00017, "system__exceptionsS");
24667 pragma Export (C, u00018, "system__machine_state_operationsB");
24668 pragma Export (C, u00019, "system__machine_state_operationsS");
24669 pragma Export (C, u00020, "system__machine_codeS");
24670 pragma Export (C, u00021, "system__storage_elementsB");
24671 pragma Export (C, u00022, "system__storage_elementsS");
24672 pragma Export (C, u00023, "system__secondary_stackB");
24673 pragma Export (C, u00024, "system__secondary_stackS");
24674 pragma Export (C, u00025, "system__parametersB");
24675 pragma Export (C, u00026, "system__parametersS");
24676 pragma Export (C, u00027, "system__soft_linksB");
24677 pragma Export (C, u00028, "system__soft_linksS");
24678 pragma Export (C, u00029, "system__stack_checkingB");
24679 pragma Export (C, u00030, "system__stack_checkingS");
24680 pragma Export (C, u00031, "system__tracebackB");
24681 pragma Export (C, u00032, "system__tracebackS");
24682 pragma Export (C, u00033, "ada__streamsS");
24683 pragma Export (C, u00034, "ada__tagsB");
24684 pragma Export (C, u00035, "ada__tagsS");
24685 pragma Export (C, u00036, "system__string_opsB");
24686 pragma Export (C, u00037, "system__string_opsS");
24687 pragma Export (C, u00038, "interfacesS");
24688 pragma Export (C, u00039, "interfaces__c_streamsB");
24689 pragma Export (C, u00040, "interfaces__c_streamsS");
24690 pragma Export (C, u00041, "system__file_ioB");
24691 pragma Export (C, u00042, "system__file_ioS");
24692 pragma Export (C, u00043, "ada__finalizationB");
24693 pragma Export (C, u00044, "ada__finalizationS");
24694 pragma Export (C, u00045, "system__finalization_rootB");
24695 pragma Export (C, u00046, "system__finalization_rootS");
24696 pragma Export (C, u00047, "system__finalization_implementationB");
24697 pragma Export (C, u00048, "system__finalization_implementationS");
24698 pragma Export (C, u00049, "system__string_ops_concat_3B");
24699 pragma Export (C, u00050, "system__string_ops_concat_3S");
24700 pragma Export (C, u00051, "system__stream_attributesB");
24701 pragma Export (C, u00052, "system__stream_attributesS");
24702 pragma Export (C, u00053, "ada__io_exceptionsS");
24703 pragma Export (C, u00054, "system__unsigned_typesS");
24704 pragma Export (C, u00055, "system__file_control_blockS");
24705 pragma Export (C, u00056, "ada__finalization__list_controllerB");
24706 pragma Export (C, u00057, "ada__finalization__list_controllerS");
24707
24708 -- BEGIN ELABORATION ORDER
24709 -- ada (spec)
24710 -- gnat (spec)
24711 -- gnat.heap_sort_a (spec)
24712 -- gnat.heap_sort_a (body)
24713 -- gnat.htable (spec)
24714 -- gnat.htable (body)
24715 -- interfaces (spec)
24716 -- system (spec)
24717 -- system.machine_code (spec)
24718 -- system.parameters (spec)
24719 -- system.parameters (body)
24720 -- interfaces.c_streams (spec)
24721 -- interfaces.c_streams (body)
24722 -- system.standard_library (spec)
24723 -- ada.exceptions (spec)
24724 -- system.exception_table (spec)
24725 -- system.exception_table (body)
24726 -- ada.io_exceptions (spec)
24727 -- system.exceptions (spec)
24728 -- system.storage_elements (spec)
24729 -- system.storage_elements (body)
24730 -- system.machine_state_operations (spec)
24731 -- system.machine_state_operations (body)
24732 -- system.secondary_stack (spec)
24733 -- system.stack_checking (spec)
24734 -- system.soft_links (spec)
24735 -- system.soft_links (body)
24736 -- system.stack_checking (body)
24737 -- system.secondary_stack (body)
24738 -- system.standard_library (body)
24739 -- system.string_ops (spec)
24740 -- system.string_ops (body)
24741 -- ada.tags (spec)
24742 -- ada.tags (body)
24743 -- ada.streams (spec)
24744 -- system.finalization_root (spec)
24745 -- system.finalization_root (body)
24746 -- system.string_ops_concat_3 (spec)
24747 -- system.string_ops_concat_3 (body)
24748 -- system.traceback (spec)
24749 -- system.traceback (body)
24750 -- ada.exceptions (body)
24751 -- system.unsigned_types (spec)
24752 -- system.stream_attributes (spec)
24753 -- system.stream_attributes (body)
24754 -- system.finalization_implementation (spec)
24755 -- system.finalization_implementation (body)
24756 -- ada.finalization (spec)
24757 -- ada.finalization (body)
24758 -- ada.finalization.list_controller (spec)
24759 -- ada.finalization.list_controller (body)
24760 -- system.file_control_block (spec)
24761 -- system.file_io (spec)
24762 -- system.file_io (body)
24763 -- ada.text_io (spec)
24764 -- ada.text_io (body)
24765 -- hello (body)
24766 -- END ELABORATION ORDER
24767
24768 end ada_main;
24769
24770 -- The following source file name pragmas allow the generated file
24771 -- names to be unique for different main programs. They are needed
24772 -- since the package name will always be Ada_Main.
24773
24774 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
24775 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
24776
24777 -- Generated package body for Ada_Main starts here
24778
24779 package body ada_main is
24780
24781 -- The actual finalization is performed by calling the
24782 -- library routine in System.Standard_Library.Adafinal
24783
24784 procedure Do_Finalize;
24785 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
24786
24787 -------------
24788 -- adainit --
24789 -------------
24790
24791 @findex adainit
24792 procedure adainit is
24793
24794 -- These booleans are set to True once the associated unit has
24795 -- been elaborated. It is also used to avoid elaborating the
24796 -- same unit twice.
24797
24798 E040 : Boolean;
24799 pragma Import (Ada, E040, "interfaces__c_streams_E");
24800
24801 E008 : Boolean;
24802 pragma Import (Ada, E008, "ada__exceptions_E");
24803
24804 E014 : Boolean;
24805 pragma Import (Ada, E014, "system__exception_table_E");
24806
24807 E053 : Boolean;
24808 pragma Import (Ada, E053, "ada__io_exceptions_E");
24809
24810 E017 : Boolean;
24811 pragma Import (Ada, E017, "system__exceptions_E");
24812
24813 E024 : Boolean;
24814 pragma Import (Ada, E024, "system__secondary_stack_E");
24815
24816 E030 : Boolean;
24817 pragma Import (Ada, E030, "system__stack_checking_E");
24818
24819 E028 : Boolean;
24820 pragma Import (Ada, E028, "system__soft_links_E");
24821
24822 E035 : Boolean;
24823 pragma Import (Ada, E035, "ada__tags_E");
24824
24825 E033 : Boolean;
24826 pragma Import (Ada, E033, "ada__streams_E");
24827
24828 E046 : Boolean;
24829 pragma Import (Ada, E046, "system__finalization_root_E");
24830
24831 E048 : Boolean;
24832 pragma Import (Ada, E048, "system__finalization_implementation_E");
24833
24834 E044 : Boolean;
24835 pragma Import (Ada, E044, "ada__finalization_E");
24836
24837 E057 : Boolean;
24838 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
24839
24840 E055 : Boolean;
24841 pragma Import (Ada, E055, "system__file_control_block_E");
24842
24843 E042 : Boolean;
24844 pragma Import (Ada, E042, "system__file_io_E");
24845
24846 E006 : Boolean;
24847 pragma Import (Ada, E006, "ada__text_io_E");
24848
24849 -- Set_Globals is a library routine that stores away the
24850 -- value of the indicated set of global values in global
24851 -- variables within the library.
24852
24853 procedure Set_Globals
24854 (Main_Priority : Integer;
24855 Time_Slice_Value : Integer;
24856 WC_Encoding : Character;
24857 Locking_Policy : Character;
24858 Queuing_Policy : Character;
24859 Task_Dispatching_Policy : Character;
24860 Adafinal : System.Address;
24861 Unreserve_All_Interrupts : Integer;
24862 Exception_Tracebacks : Integer);
24863 @findex __gnat_set_globals
24864 pragma Import (C, Set_Globals, "__gnat_set_globals");
24865
24866 -- SDP_Table_Build is a library routine used to build the
24867 -- exception tables. See unit Ada.Exceptions in files
24868 -- a-except.ads/adb for full details of how zero cost
24869 -- exception handling works. This procedure, the call to
24870 -- it, and the two following tables are all omitted if the
24871 -- build is in longjmp/setjmp exception mode.
24872
24873 @findex SDP_Table_Build
24874 @findex Zero Cost Exceptions
24875 procedure SDP_Table_Build
24876 (SDP_Addresses : System.Address;
24877 SDP_Count : Natural;
24878 Elab_Addresses : System.Address;
24879 Elab_Addr_Count : Natural);
24880 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
24881
24882 -- Table of Unit_Exception_Table addresses. Used for zero
24883 -- cost exception handling to build the top level table.
24884
24885 ST : aliased constant array (1 .. 23) of System.Address := (
24886 Hello'UET_Address,
24887 Ada.Text_Io'UET_Address,
24888 Ada.Exceptions'UET_Address,
24889 Gnat.Heap_Sort_A'UET_Address,
24890 System.Exception_Table'UET_Address,
24891 System.Machine_State_Operations'UET_Address,
24892 System.Secondary_Stack'UET_Address,
24893 System.Parameters'UET_Address,
24894 System.Soft_Links'UET_Address,
24895 System.Stack_Checking'UET_Address,
24896 System.Traceback'UET_Address,
24897 Ada.Streams'UET_Address,
24898 Ada.Tags'UET_Address,
24899 System.String_Ops'UET_Address,
24900 Interfaces.C_Streams'UET_Address,
24901 System.File_Io'UET_Address,
24902 Ada.Finalization'UET_Address,
24903 System.Finalization_Root'UET_Address,
24904 System.Finalization_Implementation'UET_Address,
24905 System.String_Ops_Concat_3'UET_Address,
24906 System.Stream_Attributes'UET_Address,
24907 System.File_Control_Block'UET_Address,
24908 Ada.Finalization.List_Controller'UET_Address);
24909
24910 -- Table of addresses of elaboration routines. Used for
24911 -- zero cost exception handling to make sure these
24912 -- addresses are included in the top level procedure
24913 -- address table.
24914
24915 EA : aliased constant array (1 .. 23) of System.Address := (
24916 adainit'Code_Address,
24917 Do_Finalize'Code_Address,
24918 Ada.Exceptions'Elab_Spec'Address,
24919 System.Exceptions'Elab_Spec'Address,
24920 Interfaces.C_Streams'Elab_Spec'Address,
24921 System.Exception_Table'Elab_Body'Address,
24922 Ada.Io_Exceptions'Elab_Spec'Address,
24923 System.Stack_Checking'Elab_Spec'Address,
24924 System.Soft_Links'Elab_Body'Address,
24925 System.Secondary_Stack'Elab_Body'Address,
24926 Ada.Tags'Elab_Spec'Address,
24927 Ada.Tags'Elab_Body'Address,
24928 Ada.Streams'Elab_Spec'Address,
24929 System.Finalization_Root'Elab_Spec'Address,
24930 Ada.Exceptions'Elab_Body'Address,
24931 System.Finalization_Implementation'Elab_Spec'Address,
24932 System.Finalization_Implementation'Elab_Body'Address,
24933 Ada.Finalization'Elab_Spec'Address,
24934 Ada.Finalization.List_Controller'Elab_Spec'Address,
24935 System.File_Control_Block'Elab_Spec'Address,
24936 System.File_Io'Elab_Body'Address,
24937 Ada.Text_Io'Elab_Spec'Address,
24938 Ada.Text_Io'Elab_Body'Address);
24939
24940 -- Start of processing for adainit
24941
24942 begin
24943
24944 -- Call SDP_Table_Build to build the top level procedure
24945 -- table for zero cost exception handling (omitted in
24946 -- longjmp/setjmp mode).
24947
24948 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
24949
24950 -- Call Set_Globals to record various information for
24951 -- this partition. The values are derived by the binder
24952 -- from information stored in the ali files by the compiler.
24953
24954 @findex __gnat_set_globals
24955 Set_Globals
24956 (Main_Priority => -1,
24957 -- Priority of main program, -1 if no pragma Priority used
24958
24959 Time_Slice_Value => -1,
24960 -- Time slice from Time_Slice pragma, -1 if none used
24961
24962 WC_Encoding => 'b',
24963 -- Wide_Character encoding used, default is brackets
24964
24965 Locking_Policy => ' ',
24966 -- Locking_Policy used, default of space means not
24967 -- specified, otherwise it is the first character of
24968 -- the policy name.
24969
24970 Queuing_Policy => ' ',
24971 -- Queuing_Policy used, default of space means not
24972 -- specified, otherwise it is the first character of
24973 -- the policy name.
24974
24975 Task_Dispatching_Policy => ' ',
24976 -- Task_Dispatching_Policy used, default of space means
24977 -- not specified, otherwise first character of the
24978 -- policy name.
24979
24980 Adafinal => System.Null_Address,
24981 -- Address of Adafinal routine, not used anymore
24982
24983 Unreserve_All_Interrupts => 0,
24984 -- Set true if pragma Unreserve_All_Interrupts was used
24985
24986 Exception_Tracebacks => 0);
24987 -- Indicates if exception tracebacks are enabled
24988
24989 Elab_Final_Code := 1;
24990
24991 -- Now we have the elaboration calls for all units in the partition.
24992 -- The Elab_Spec and Elab_Body attributes generate references to the
24993 -- implicit elaboration procedures generated by the compiler for
24994 -- each unit that requires elaboration.
24995
24996 if not E040 then
24997 Interfaces.C_Streams'Elab_Spec;
24998 end if;
24999 E040 := True;
25000 if not E008 then
25001 Ada.Exceptions'Elab_Spec;
25002 end if;
25003 if not E014 then
25004 System.Exception_Table'Elab_Body;
25005 E014 := True;
25006 end if;
25007 if not E053 then
25008 Ada.Io_Exceptions'Elab_Spec;
25009 E053 := True;
25010 end if;
25011 if not E017 then
25012 System.Exceptions'Elab_Spec;
25013 E017 := True;
25014 end if;
25015 if not E030 then
25016 System.Stack_Checking'Elab_Spec;
25017 end if;
25018 if not E028 then
25019 System.Soft_Links'Elab_Body;
25020 E028 := True;
25021 end if;
25022 E030 := True;
25023 if not E024 then
25024 System.Secondary_Stack'Elab_Body;
25025 E024 := True;
25026 end if;
25027 if not E035 then
25028 Ada.Tags'Elab_Spec;
25029 end if;
25030 if not E035 then
25031 Ada.Tags'Elab_Body;
25032 E035 := True;
25033 end if;
25034 if not E033 then
25035 Ada.Streams'Elab_Spec;
25036 E033 := True;
25037 end if;
25038 if not E046 then
25039 System.Finalization_Root'Elab_Spec;
25040 end if;
25041 E046 := True;
25042 if not E008 then
25043 Ada.Exceptions'Elab_Body;
25044 E008 := True;
25045 end if;
25046 if not E048 then
25047 System.Finalization_Implementation'Elab_Spec;
25048 end if;
25049 if not E048 then
25050 System.Finalization_Implementation'Elab_Body;
25051 E048 := True;
25052 end if;
25053 if not E044 then
25054 Ada.Finalization'Elab_Spec;
25055 end if;
25056 E044 := True;
25057 if not E057 then
25058 Ada.Finalization.List_Controller'Elab_Spec;
25059 end if;
25060 E057 := True;
25061 if not E055 then
25062 System.File_Control_Block'Elab_Spec;
25063 E055 := True;
25064 end if;
25065 if not E042 then
25066 System.File_Io'Elab_Body;
25067 E042 := True;
25068 end if;
25069 if not E006 then
25070 Ada.Text_Io'Elab_Spec;
25071 end if;
25072 if not E006 then
25073 Ada.Text_Io'Elab_Body;
25074 E006 := True;
25075 end if;
25076
25077 Elab_Final_Code := 0;
25078 end adainit;
25079
25080 --------------
25081 -- adafinal --
25082 --------------
25083
25084 @findex adafinal
25085 procedure adafinal is
25086 begin
25087 Do_Finalize;
25088 end adafinal;
25089
25090 ----------
25091 -- main --
25092 ----------
25093
25094 -- main is actually a function, as in the ANSI C standard,
25095 -- defined to return the exit status. The three parameters
25096 -- are the argument count, argument values and environment
25097 -- pointer.
25098
25099 @findex Main Program
25100 function main
25101 (argc : Integer;
25102 argv : System.Address;
25103 envp : System.Address)
25104 return Integer
25105 is
25106 -- The initialize routine performs low level system
25107 -- initialization using a standard library routine which
25108 -- sets up signal handling and performs any other
25109 -- required setup. The routine can be found in file
25110 -- a-init.c.
25111
25112 @findex __gnat_initialize
25113 procedure initialize;
25114 pragma Import (C, initialize, "__gnat_initialize");
25115
25116 -- The finalize routine performs low level system
25117 -- finalization using a standard library routine. The
25118 -- routine is found in file a-final.c and in the standard
25119 -- distribution is a dummy routine that does nothing, so
25120 -- really this is a hook for special user finalization.
25121
25122 @findex __gnat_finalize
25123 procedure finalize;
25124 pragma Import (C, finalize, "__gnat_finalize");
25125
25126 -- We get to the main program of the partition by using
25127 -- pragma Import because if we try to with the unit and
25128 -- call it Ada style, then not only do we waste time
25129 -- recompiling it, but also, we don't really know the right
25130 -- switches (e.g.@: identifier character set) to be used
25131 -- to compile it.
25132
25133 procedure Ada_Main_Program;
25134 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
25135
25136 -- Start of processing for main
25137
25138 begin
25139 -- Save global variables
25140
25141 gnat_argc := argc;
25142 gnat_argv := argv;
25143 gnat_envp := envp;
25144
25145 -- Call low level system initialization
25146
25147 Initialize;
25148
25149 -- Call our generated Ada initialization routine
25150
25151 adainit;
25152
25153 -- This is the point at which we want the debugger to get
25154 -- control
25155
25156 Break_Start;
25157
25158 -- Now we call the main program of the partition
25159
25160 Ada_Main_Program;
25161
25162 -- Perform Ada finalization
25163
25164 adafinal;
25165
25166 -- Perform low level system finalization
25167
25168 Finalize;
25169
25170 -- Return the proper exit status
25171 return (gnat_exit_status);
25172 end;
25173
25174 -- This section is entirely comments, so it has no effect on the
25175 -- compilation of the Ada_Main package. It provides the list of
25176 -- object files and linker options, as well as some standard
25177 -- libraries needed for the link. The gnatlink utility parses
25178 -- this b~hello.adb file to read these comment lines to generate
25179 -- the appropriate command line arguments for the call to the
25180 -- system linker. The BEGIN/END lines are used for sentinels for
25181 -- this parsing operation.
25182
25183 -- The exact file names will of course depend on the environment,
25184 -- host/target and location of files on the host system.
25185
25186 @findex Object file list
25187 -- BEGIN Object file/option list
25188 -- ./hello.o
25189 -- -L./
25190 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
25191 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
25192 -- END Object file/option list
25193
25194 end ada_main;
25195 @end smallexample
25196
25197 @noindent
25198 The Ada code in the above example is exactly what is generated by the
25199 binder. We have added comments to more clearly indicate the function
25200 of each part of the generated @code{Ada_Main} package.
25201
25202 The code is standard Ada in all respects, and can be processed by any
25203 tools that handle Ada. In particular, it is possible to use the debugger
25204 in Ada mode to debug the generated @code{Ada_Main} package. For example,
25205 suppose that for reasons that you do not understand, your program is crashing
25206 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
25207 you can place a breakpoint on the call:
25208
25209 @smallexample @c ada
25210 Ada.Text_Io'Elab_Body;
25211 @end smallexample
25212
25213 @noindent
25214 and trace the elaboration routine for this package to find out where
25215 the problem might be (more usually of course you would be debugging
25216 elaboration code in your own application).
25217
25218 @node Elaboration Order Handling in GNAT
25219 @appendix Elaboration Order Handling in GNAT
25220 @cindex Order of elaboration
25221 @cindex Elaboration control
25222
25223 @menu
25224 * Elaboration Code::
25225 * Checking the Elaboration Order::
25226 * Controlling the Elaboration Order::
25227 * Controlling Elaboration in GNAT - Internal Calls::
25228 * Controlling Elaboration in GNAT - External Calls::
25229 * Default Behavior in GNAT - Ensuring Safety::
25230 * Treatment of Pragma Elaborate::
25231 * Elaboration Issues for Library Tasks::
25232 * Mixing Elaboration Models::
25233 * What to Do If the Default Elaboration Behavior Fails::
25234 * Elaboration for Indirect Calls::
25235 * Summary of Procedures for Elaboration Control::
25236 * Other Elaboration Order Considerations::
25237 * Determining the Chosen Elaboration Order::
25238 @end menu
25239
25240 @noindent
25241 This chapter describes the handling of elaboration code in Ada and
25242 in GNAT, and discusses how the order of elaboration of program units can
25243 be controlled in GNAT, either automatically or with explicit programming
25244 features.
25245
25246 @node Elaboration Code
25247 @section Elaboration Code
25248
25249 @noindent
25250 Ada provides rather general mechanisms for executing code at elaboration
25251 time, that is to say before the main program starts executing. Such code arises
25252 in three contexts:
25253
25254 @table @asis
25255 @item Initializers for variables.
25256 Variables declared at the library level, in package specs or bodies, can
25257 require initialization that is performed at elaboration time, as in:
25258 @smallexample @c ada
25259 @cartouche
25260 Sqrt_Half : Float := Sqrt (0.5);
25261 @end cartouche
25262 @end smallexample
25263
25264 @item Package initialization code
25265 Code in a @code{BEGIN-END} section at the outer level of a package body is
25266 executed as part of the package body elaboration code.
25267
25268 @item Library level task allocators
25269 Tasks that are declared using task allocators at the library level
25270 start executing immediately and hence can execute at elaboration time.
25271 @end table
25272
25273 @noindent
25274 Subprogram calls are possible in any of these contexts, which means that
25275 any arbitrary part of the program may be executed as part of the elaboration
25276 code. It is even possible to write a program which does all its work at
25277 elaboration time, with a null main program, although stylistically this
25278 would usually be considered an inappropriate way to structure
25279 a program.
25280
25281 An important concern arises in the context of elaboration code:
25282 we have to be sure that it is executed in an appropriate order. What we
25283 have is a series of elaboration code sections, potentially one section
25284 for each unit in the program. It is important that these execute
25285 in the correct order. Correctness here means that, taking the above
25286 example of the declaration of @code{Sqrt_Half},
25287 if some other piece of
25288 elaboration code references @code{Sqrt_Half},
25289 then it must run after the
25290 section of elaboration code that contains the declaration of
25291 @code{Sqrt_Half}.
25292
25293 There would never be any order of elaboration problem if we made a rule
25294 that whenever you @code{with} a unit, you must elaborate both the spec and body
25295 of that unit before elaborating the unit doing the @code{with}'ing:
25296
25297 @smallexample @c ada
25298 @group
25299 @cartouche
25300 with Unit_1;
25301 package Unit_2 is @dots{}
25302 @end cartouche
25303 @end group
25304 @end smallexample
25305
25306 @noindent
25307 would require that both the body and spec of @code{Unit_1} be elaborated
25308 before the spec of @code{Unit_2}. However, a rule like that would be far too
25309 restrictive. In particular, it would make it impossible to have routines
25310 in separate packages that were mutually recursive.
25311
25312 You might think that a clever enough compiler could look at the actual
25313 elaboration code and determine an appropriate correct order of elaboration,
25314 but in the general case, this is not possible. Consider the following
25315 example.
25316
25317 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
25318 that references
25319 the variable @code{Sqrt_1}, which is declared in the elaboration code
25320 of the body of @code{Unit_1}:
25321
25322 @smallexample @c ada
25323 @cartouche
25324 Sqrt_1 : Float := Sqrt (0.1);
25325 @end cartouche
25326 @end smallexample
25327
25328 @noindent
25329 The elaboration code of the body of @code{Unit_1} also contains:
25330
25331 @smallexample @c ada
25332 @group
25333 @cartouche
25334 if expression_1 = 1 then
25335 Q := Unit_2.Func_2;
25336 end if;
25337 @end cartouche
25338 @end group
25339 @end smallexample
25340
25341 @noindent
25342 @code{Unit_2} is exactly parallel,
25343 it has a procedure @code{Func_2} that references
25344 the variable @code{Sqrt_2}, which is declared in the elaboration code of
25345 the body @code{Unit_2}:
25346
25347 @smallexample @c ada
25348 @cartouche
25349 Sqrt_2 : Float := Sqrt (0.1);
25350 @end cartouche
25351 @end smallexample
25352
25353 @noindent
25354 The elaboration code of the body of @code{Unit_2} also contains:
25355
25356 @smallexample @c ada
25357 @group
25358 @cartouche
25359 if expression_2 = 2 then
25360 Q := Unit_1.Func_1;
25361 end if;
25362 @end cartouche
25363 @end group
25364 @end smallexample
25365
25366 @noindent
25367 Now the question is, which of the following orders of elaboration is
25368 acceptable:
25369
25370 @smallexample
25371 @group
25372 Spec of Unit_1
25373 Spec of Unit_2
25374 Body of Unit_1
25375 Body of Unit_2
25376 @end group
25377 @end smallexample
25378
25379 @noindent
25380 or
25381
25382 @smallexample
25383 @group
25384 Spec of Unit_2
25385 Spec of Unit_1
25386 Body of Unit_2
25387 Body of Unit_1
25388 @end group
25389 @end smallexample
25390
25391 @noindent
25392 If you carefully analyze the flow here, you will see that you cannot tell
25393 at compile time the answer to this question.
25394 If @code{expression_1} is not equal to 1,
25395 and @code{expression_2} is not equal to 2,
25396 then either order is acceptable, because neither of the function calls is
25397 executed. If both tests evaluate to true, then neither order is acceptable
25398 and in fact there is no correct order.
25399
25400 If one of the two expressions is true, and the other is false, then one
25401 of the above orders is correct, and the other is incorrect. For example,
25402 if @code{expression_1} /= 1 and @code{expression_2} = 2,
25403 then the call to @code{Func_1}
25404 will occur, but not the call to @code{Func_2.}
25405 This means that it is essential
25406 to elaborate the body of @code{Unit_1} before
25407 the body of @code{Unit_2}, so the first
25408 order of elaboration is correct and the second is wrong.
25409
25410 By making @code{expression_1} and @code{expression_2}
25411 depend on input data, or perhaps
25412 the time of day, we can make it impossible for the compiler or binder
25413 to figure out which of these expressions will be true, and hence it
25414 is impossible to guarantee a safe order of elaboration at run time.
25415
25416 @node Checking the Elaboration Order
25417 @section Checking the Elaboration Order
25418
25419 @noindent
25420 In some languages that involve the same kind of elaboration problems,
25421 e.g.@: Java and C++, the programmer is expected to worry about these
25422 ordering problems himself, and it is common to
25423 write a program in which an incorrect elaboration order gives
25424 surprising results, because it references variables before they
25425 are initialized.
25426 Ada is designed to be a safe language, and a programmer-beware approach is
25427 clearly not sufficient. Consequently, the language provides three lines
25428 of defense:
25429
25430 @table @asis
25431 @item Standard rules
25432 Some standard rules restrict the possible choice of elaboration
25433 order. In particular, if you @code{with} a unit, then its spec is always
25434 elaborated before the unit doing the @code{with}. Similarly, a parent
25435 spec is always elaborated before the child spec, and finally
25436 a spec is always elaborated before its corresponding body.
25437
25438 @item Dynamic elaboration checks
25439 @cindex Elaboration checks
25440 @cindex Checks, elaboration
25441 Dynamic checks are made at run time, so that if some entity is accessed
25442 before it is elaborated (typically by means of a subprogram call)
25443 then the exception (@code{Program_Error}) is raised.
25444
25445 @item Elaboration control
25446 Facilities are provided for the programmer to specify the desired order
25447 of elaboration.
25448 @end table
25449
25450 Let's look at these facilities in more detail. First, the rules for
25451 dynamic checking. One possible rule would be simply to say that the
25452 exception is raised if you access a variable which has not yet been
25453 elaborated. The trouble with this approach is that it could require
25454 expensive checks on every variable reference. Instead Ada has two
25455 rules which are a little more restrictive, but easier to check, and
25456 easier to state:
25457
25458 @table @asis
25459 @item Restrictions on calls
25460 A subprogram can only be called at elaboration time if its body
25461 has been elaborated. The rules for elaboration given above guarantee
25462 that the spec of the subprogram has been elaborated before the
25463 call, but not the body. If this rule is violated, then the
25464 exception @code{Program_Error} is raised.
25465
25466 @item Restrictions on instantiations
25467 A generic unit can only be instantiated if the body of the generic
25468 unit has been elaborated. Again, the rules for elaboration given above
25469 guarantee that the spec of the generic unit has been elaborated
25470 before the instantiation, but not the body. If this rule is
25471 violated, then the exception @code{Program_Error} is raised.
25472 @end table
25473
25474 @noindent
25475 The idea is that if the body has been elaborated, then any variables
25476 it references must have been elaborated; by checking for the body being
25477 elaborated we guarantee that none of its references causes any
25478 trouble. As we noted above, this is a little too restrictive, because a
25479 subprogram that has no non-local references in its body may in fact be safe
25480 to call. However, it really would be unsafe to rely on this, because
25481 it would mean that the caller was aware of details of the implementation
25482 in the body. This goes against the basic tenets of Ada.
25483
25484 A plausible implementation can be described as follows.
25485 A Boolean variable is associated with each subprogram
25486 and each generic unit. This variable is initialized to False, and is set to
25487 True at the point body is elaborated. Every call or instantiation checks the
25488 variable, and raises @code{Program_Error} if the variable is False.
25489
25490 Note that one might think that it would be good enough to have one Boolean
25491 variable for each package, but that would not deal with cases of trying
25492 to call a body in the same package as the call
25493 that has not been elaborated yet.
25494 Of course a compiler may be able to do enough analysis to optimize away
25495 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
25496 does such optimizations, but still the easiest conceptual model is to
25497 think of there being one variable per subprogram.
25498
25499 @node Controlling the Elaboration Order
25500 @section Controlling the Elaboration Order
25501
25502 @noindent
25503 In the previous section we discussed the rules in Ada which ensure
25504 that @code{Program_Error} is raised if an incorrect elaboration order is
25505 chosen. This prevents erroneous executions, but we need mechanisms to
25506 specify a correct execution and avoid the exception altogether.
25507 To achieve this, Ada provides a number of features for controlling
25508 the order of elaboration. We discuss these features in this section.
25509
25510 First, there are several ways of indicating to the compiler that a given
25511 unit has no elaboration problems:
25512
25513 @table @asis
25514 @item packages that do not require a body
25515 A library package that does not require a body does not permit
25516 a body (this rule was introduced in Ada 95).
25517 Thus if we have a such a package, as in:
25518
25519 @smallexample @c ada
25520 @group
25521 @cartouche
25522 package Definitions is
25523 generic
25524 type m is new integer;
25525 package Subp is
25526 type a is array (1 .. 10) of m;
25527 type b is array (1 .. 20) of m;
25528 end Subp;
25529 end Definitions;
25530 @end cartouche
25531 @end group
25532 @end smallexample
25533
25534 @noindent
25535 A package that @code{with}'s @code{Definitions} may safely instantiate
25536 @code{Definitions.Subp} because the compiler can determine that there
25537 definitely is no package body to worry about in this case
25538
25539 @item pragma Pure
25540 @cindex pragma Pure
25541 @findex Pure
25542 Places sufficient restrictions on a unit to guarantee that
25543 no call to any subprogram in the unit can result in an
25544 elaboration problem. This means that the compiler does not need
25545 to worry about the point of elaboration of such units, and in
25546 particular, does not need to check any calls to any subprograms
25547 in this unit.
25548
25549 @item pragma Preelaborate
25550 @findex Preelaborate
25551 @cindex pragma Preelaborate
25552 This pragma places slightly less stringent restrictions on a unit than
25553 does pragma Pure,
25554 but these restrictions are still sufficient to ensure that there
25555 are no elaboration problems with any calls to the unit.
25556
25557 @item pragma Elaborate_Body
25558 @findex Elaborate_Body
25559 @cindex pragma Elaborate_Body
25560 This pragma requires that the body of a unit be elaborated immediately
25561 after its spec. Suppose a unit @code{A} has such a pragma,
25562 and unit @code{B} does
25563 a @code{with} of unit @code{A}. Recall that the standard rules require
25564 the spec of unit @code{A}
25565 to be elaborated before the @code{with}'ing unit; given the pragma in
25566 @code{A}, we also know that the body of @code{A}
25567 will be elaborated before @code{B}, so
25568 that calls to @code{A} are safe and do not need a check.
25569 @end table
25570
25571 @noindent
25572 Note that,
25573 unlike pragma @code{Pure} and pragma @code{Preelaborate},
25574 the use of
25575 @code{Elaborate_Body} does not guarantee that the program is
25576 free of elaboration problems, because it may not be possible
25577 to satisfy the requested elaboration order.
25578 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
25579 If a programmer
25580 marks @code{Unit_1} as @code{Elaborate_Body},
25581 and not @code{Unit_2,} then the order of
25582 elaboration will be:
25583
25584 @smallexample
25585 @group
25586 Spec of Unit_2
25587 Spec of Unit_1
25588 Body of Unit_1
25589 Body of Unit_2
25590 @end group
25591 @end smallexample
25592
25593 @noindent
25594 Now that means that the call to @code{Func_1} in @code{Unit_2}
25595 need not be checked,
25596 it must be safe. But the call to @code{Func_2} in
25597 @code{Unit_1} may still fail if
25598 @code{Expression_1} is equal to 1,
25599 and the programmer must still take
25600 responsibility for this not being the case.
25601
25602 If all units carry a pragma @code{Elaborate_Body}, then all problems are
25603 eliminated, except for calls entirely within a body, which are
25604 in any case fully under programmer control. However, using the pragma
25605 everywhere is not always possible.
25606 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
25607 we marked both of them as having pragma @code{Elaborate_Body}, then
25608 clearly there would be no possible elaboration order.
25609
25610 The above pragmas allow a server to guarantee safe use by clients, and
25611 clearly this is the preferable approach. Consequently a good rule
25612 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
25613 and if this is not possible,
25614 mark them as @code{Elaborate_Body} if possible.
25615 As we have seen, there are situations where neither of these
25616 three pragmas can be used.
25617 So we also provide methods for clients to control the
25618 order of elaboration of the servers on which they depend:
25619
25620 @table @asis
25621 @item pragma Elaborate (unit)
25622 @findex Elaborate
25623 @cindex pragma Elaborate
25624 This pragma is placed in the context clause, after a @code{with} clause,
25625 and it requires that the body of the named unit be elaborated before
25626 the unit in which the pragma occurs. The idea is to use this pragma
25627 if the current unit calls at elaboration time, directly or indirectly,
25628 some subprogram in the named unit.
25629
25630 @item pragma Elaborate_All (unit)
25631 @findex Elaborate_All
25632 @cindex pragma Elaborate_All
25633 This is a stronger version of the Elaborate pragma. Consider the
25634 following example:
25635
25636 @smallexample
25637 Unit A @code{with}'s unit B and calls B.Func in elab code
25638 Unit B @code{with}'s unit C, and B.Func calls C.Func
25639 @end smallexample
25640
25641 @noindent
25642 Now if we put a pragma @code{Elaborate (B)}
25643 in unit @code{A}, this ensures that the
25644 body of @code{B} is elaborated before the call, but not the
25645 body of @code{C}, so
25646 the call to @code{C.Func} could still cause @code{Program_Error} to
25647 be raised.
25648
25649 The effect of a pragma @code{Elaborate_All} is stronger, it requires
25650 not only that the body of the named unit be elaborated before the
25651 unit doing the @code{with}, but also the bodies of all units that the
25652 named unit uses, following @code{with} links transitively. For example,
25653 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
25654 then it requires
25655 not only that the body of @code{B} be elaborated before @code{A},
25656 but also the
25657 body of @code{C}, because @code{B} @code{with}'s @code{C}.
25658 @end table
25659
25660 @noindent
25661 We are now in a position to give a usage rule in Ada for avoiding
25662 elaboration problems, at least if dynamic dispatching and access to
25663 subprogram values are not used. We will handle these cases separately
25664 later.
25665
25666 The rule is simple. If a unit has elaboration code that can directly or
25667 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
25668 a generic package in a @code{with}'ed unit,
25669 then if the @code{with}'ed unit does not have
25670 pragma @code{Pure} or @code{Preelaborate}, then the client should have
25671 a pragma @code{Elaborate_All}
25672 for the @code{with}'ed unit. By following this rule a client is
25673 assured that calls can be made without risk of an exception.
25674
25675 For generic subprogram instantiations, the rule can be relaxed to
25676 require only a pragma @code{Elaborate} since elaborating the body
25677 of a subprogram cannot cause any transitive elaboration (we are
25678 not calling the subprogram in this case, just elaborating its
25679 declaration).
25680
25681 If this rule is not followed, then a program may be in one of four
25682 states:
25683
25684 @table @asis
25685 @item No order exists
25686 No order of elaboration exists which follows the rules, taking into
25687 account any @code{Elaborate}, @code{Elaborate_All},
25688 or @code{Elaborate_Body} pragmas. In
25689 this case, an Ada compiler must diagnose the situation at bind
25690 time, and refuse to build an executable program.
25691
25692 @item One or more orders exist, all incorrect
25693 One or more acceptable elaboration orders exist, and all of them
25694 generate an elaboration order problem. In this case, the binder
25695 can build an executable program, but @code{Program_Error} will be raised
25696 when the program is run.
25697
25698 @item Several orders exist, some right, some incorrect
25699 One or more acceptable elaboration orders exists, and some of them
25700 work, and some do not. The programmer has not controlled
25701 the order of elaboration, so the binder may or may not pick one of
25702 the correct orders, and the program may or may not raise an
25703 exception when it is run. This is the worst case, because it means
25704 that the program may fail when moved to another compiler, or even
25705 another version of the same compiler.
25706
25707 @item One or more orders exists, all correct
25708 One ore more acceptable elaboration orders exist, and all of them
25709 work. In this case the program runs successfully. This state of
25710 affairs can be guaranteed by following the rule we gave above, but
25711 may be true even if the rule is not followed.
25712 @end table
25713
25714 @noindent
25715 Note that one additional advantage of following our rules on the use
25716 of @code{Elaborate} and @code{Elaborate_All}
25717 is that the program continues to stay in the ideal (all orders OK) state
25718 even if maintenance
25719 changes some bodies of some units. Conversely, if a program that does
25720 not follow this rule happens to be safe at some point, this state of affairs
25721 may deteriorate silently as a result of maintenance changes.
25722
25723 You may have noticed that the above discussion did not mention
25724 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
25725 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
25726 code in the body makes calls to some other unit, so it is still necessary
25727 to use @code{Elaborate_All} on such units.
25728
25729 @node Controlling Elaboration in GNAT - Internal Calls
25730 @section Controlling Elaboration in GNAT - Internal Calls
25731
25732 @noindent
25733 In the case of internal calls, i.e., calls within a single package, the
25734 programmer has full control over the order of elaboration, and it is up
25735 to the programmer to elaborate declarations in an appropriate order. For
25736 example writing:
25737
25738 @smallexample @c ada
25739 @group
25740 @cartouche
25741 function One return Float;
25742
25743 Q : Float := One;
25744
25745 function One return Float is
25746 begin
25747 return 1.0;
25748 end One;
25749 @end cartouche
25750 @end group
25751 @end smallexample
25752
25753 @noindent
25754 will obviously raise @code{Program_Error} at run time, because function
25755 One will be called before its body is elaborated. In this case GNAT will
25756 generate a warning that the call will raise @code{Program_Error}:
25757
25758 @smallexample
25759 @group
25760 @cartouche
25761 1. procedure y is
25762 2. function One return Float;
25763 3.
25764 4. Q : Float := One;
25765 |
25766 >>> warning: cannot call "One" before body is elaborated
25767 >>> warning: Program_Error will be raised at run time
25768
25769 5.
25770 6. function One return Float is
25771 7. begin
25772 8. return 1.0;
25773 9. end One;
25774 10.
25775 11. begin
25776 12. null;
25777 13. end;
25778 @end cartouche
25779 @end group
25780 @end smallexample
25781
25782 @noindent
25783 Note that in this particular case, it is likely that the call is safe, because
25784 the function @code{One} does not access any global variables.
25785 Nevertheless in Ada, we do not want the validity of the check to depend on
25786 the contents of the body (think about the separate compilation case), so this
25787 is still wrong, as we discussed in the previous sections.
25788
25789 The error is easily corrected by rearranging the declarations so that the
25790 body of @code{One} appears before the declaration containing the call
25791 (note that in Ada 95 and Ada 2005,
25792 declarations can appear in any order, so there is no restriction that
25793 would prevent this reordering, and if we write:
25794
25795 @smallexample @c ada
25796 @group
25797 @cartouche
25798 function One return Float;
25799
25800 function One return Float is
25801 begin
25802 return 1.0;
25803 end One;
25804
25805 Q : Float := One;
25806 @end cartouche
25807 @end group
25808 @end smallexample
25809
25810 @noindent
25811 then all is well, no warning is generated, and no
25812 @code{Program_Error} exception
25813 will be raised.
25814 Things are more complicated when a chain of subprograms is executed:
25815
25816 @smallexample @c ada
25817 @group
25818 @cartouche
25819 function A return Integer;
25820 function B return Integer;
25821 function C return Integer;
25822
25823 function B return Integer is begin return A; end;
25824 function C return Integer is begin return B; end;
25825
25826 X : Integer := C;
25827
25828 function A return Integer is begin return 1; end;
25829 @end cartouche
25830 @end group
25831 @end smallexample
25832
25833 @noindent
25834 Now the call to @code{C}
25835 at elaboration time in the declaration of @code{X} is correct, because
25836 the body of @code{C} is already elaborated,
25837 and the call to @code{B} within the body of
25838 @code{C} is correct, but the call
25839 to @code{A} within the body of @code{B} is incorrect, because the body
25840 of @code{A} has not been elaborated, so @code{Program_Error}
25841 will be raised on the call to @code{A}.
25842 In this case GNAT will generate a
25843 warning that @code{Program_Error} may be
25844 raised at the point of the call. Let's look at the warning:
25845
25846 @smallexample
25847 @group
25848 @cartouche
25849 1. procedure x is
25850 2. function A return Integer;
25851 3. function B return Integer;
25852 4. function C return Integer;
25853 5.
25854 6. function B return Integer is begin return A; end;
25855 |
25856 >>> warning: call to "A" before body is elaborated may
25857 raise Program_Error
25858 >>> warning: "B" called at line 7
25859 >>> warning: "C" called at line 9
25860
25861 7. function C return Integer is begin return B; end;
25862 8.
25863 9. X : Integer := C;
25864 10.
25865 11. function A return Integer is begin return 1; end;
25866 12.
25867 13. begin
25868 14. null;
25869 15. end;
25870 @end cartouche
25871 @end group
25872 @end smallexample
25873
25874 @noindent
25875 Note that the message here says ``may raise'', instead of the direct case,
25876 where the message says ``will be raised''. That's because whether
25877 @code{A} is
25878 actually called depends in general on run-time flow of control.
25879 For example, if the body of @code{B} said
25880
25881 @smallexample @c ada
25882 @group
25883 @cartouche
25884 function B return Integer is
25885 begin
25886 if some-condition-depending-on-input-data then
25887 return A;
25888 else
25889 return 1;
25890 end if;
25891 end B;
25892 @end cartouche
25893 @end group
25894 @end smallexample
25895
25896 @noindent
25897 then we could not know until run time whether the incorrect call to A would
25898 actually occur, so @code{Program_Error} might
25899 or might not be raised. It is possible for a compiler to
25900 do a better job of analyzing bodies, to
25901 determine whether or not @code{Program_Error}
25902 might be raised, but it certainly
25903 couldn't do a perfect job (that would require solving the halting problem
25904 and is provably impossible), and because this is a warning anyway, it does
25905 not seem worth the effort to do the analysis. Cases in which it
25906 would be relevant are rare.
25907
25908 In practice, warnings of either of the forms given
25909 above will usually correspond to
25910 real errors, and should be examined carefully and eliminated.
25911 In the rare case where a warning is bogus, it can be suppressed by any of
25912 the following methods:
25913
25914 @itemize @bullet
25915 @item
25916 Compile with the @option{-gnatws} switch set
25917
25918 @item
25919 Suppress @code{Elaboration_Check} for the called subprogram
25920
25921 @item
25922 Use pragma @code{Warnings_Off} to turn warnings off for the call
25923 @end itemize
25924
25925 @noindent
25926 For the internal elaboration check case,
25927 GNAT by default generates the
25928 necessary run-time checks to ensure
25929 that @code{Program_Error} is raised if any
25930 call fails an elaboration check. Of course this can only happen if a
25931 warning has been issued as described above. The use of pragma
25932 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
25933 some of these checks, meaning that it may be possible (but is not
25934 guaranteed) for a program to be able to call a subprogram whose body
25935 is not yet elaborated, without raising a @code{Program_Error} exception.
25936
25937 @node Controlling Elaboration in GNAT - External Calls
25938 @section Controlling Elaboration in GNAT - External Calls
25939
25940 @noindent
25941 The previous section discussed the case in which the execution of a
25942 particular thread of elaboration code occurred entirely within a
25943 single unit. This is the easy case to handle, because a programmer
25944 has direct and total control over the order of elaboration, and
25945 furthermore, checks need only be generated in cases which are rare
25946 and which the compiler can easily detect.
25947 The situation is more complex when separate compilation is taken into account.
25948 Consider the following:
25949
25950 @smallexample @c ada
25951 @cartouche
25952 @group
25953 package Math is
25954 function Sqrt (Arg : Float) return Float;
25955 end Math;
25956
25957 package body Math is
25958 function Sqrt (Arg : Float) return Float is
25959 begin
25960 @dots{}
25961 end Sqrt;
25962 end Math;
25963 @end group
25964 @group
25965 with Math;
25966 package Stuff is
25967 X : Float := Math.Sqrt (0.5);
25968 end Stuff;
25969
25970 with Stuff;
25971 procedure Main is
25972 begin
25973 @dots{}
25974 end Main;
25975 @end group
25976 @end cartouche
25977 @end smallexample
25978
25979 @noindent
25980 where @code{Main} is the main program. When this program is executed, the
25981 elaboration code must first be executed, and one of the jobs of the
25982 binder is to determine the order in which the units of a program are
25983 to be elaborated. In this case we have four units: the spec and body
25984 of @code{Math},
25985 the spec of @code{Stuff} and the body of @code{Main}).
25986 In what order should the four separate sections of elaboration code
25987 be executed?
25988
25989 There are some restrictions in the order of elaboration that the binder
25990 can choose. In particular, if unit U has a @code{with}
25991 for a package @code{X}, then you
25992 are assured that the spec of @code{X}
25993 is elaborated before U , but you are
25994 not assured that the body of @code{X}
25995 is elaborated before U.
25996 This means that in the above case, the binder is allowed to choose the
25997 order:
25998
25999 @smallexample
26000 spec of Math
26001 spec of Stuff
26002 body of Math
26003 body of Main
26004 @end smallexample
26005
26006 @noindent
26007 but that's not good, because now the call to @code{Math.Sqrt}
26008 that happens during
26009 the elaboration of the @code{Stuff}
26010 spec happens before the body of @code{Math.Sqrt} is
26011 elaborated, and hence causes @code{Program_Error} exception to be raised.
26012 At first glance, one might say that the binder is misbehaving, because
26013 obviously you want to elaborate the body of something you @code{with}
26014 first, but
26015 that is not a general rule that can be followed in all cases. Consider
26016
26017 @smallexample @c ada
26018 @group
26019 @cartouche
26020 package X is @dots{}
26021
26022 package Y is @dots{}
26023
26024 with X;
26025 package body Y is @dots{}
26026
26027 with Y;
26028 package body X is @dots{}
26029 @end cartouche
26030 @end group
26031 @end smallexample
26032
26033 @noindent
26034 This is a common arrangement, and, apart from the order of elaboration
26035 problems that might arise in connection with elaboration code, this works fine.
26036 A rule that says that you must first elaborate the body of anything you
26037 @code{with} cannot work in this case:
26038 the body of @code{X} @code{with}'s @code{Y},
26039 which means you would have to
26040 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
26041 which means
26042 you have to elaborate the body of @code{X} first, but @dots{} and we have a
26043 loop that cannot be broken.
26044
26045 It is true that the binder can in many cases guess an order of elaboration
26046 that is unlikely to cause a @code{Program_Error}
26047 exception to be raised, and it tries to do so (in the
26048 above example of @code{Math/Stuff/Spec}, the GNAT binder will
26049 by default
26050 elaborate the body of @code{Math} right after its spec, so all will be well).
26051
26052 However, a program that blindly relies on the binder to be helpful can
26053 get into trouble, as we discussed in the previous sections, so
26054 GNAT
26055 provides a number of facilities for assisting the programmer in
26056 developing programs that are robust with respect to elaboration order.
26057
26058 @node Default Behavior in GNAT - Ensuring Safety
26059 @section Default Behavior in GNAT - Ensuring Safety
26060
26061 @noindent
26062 The default behavior in GNAT ensures elaboration safety. In its
26063 default mode GNAT implements the
26064 rule we previously described as the right approach. Let's restate it:
26065
26066 @itemize
26067 @item
26068 @emph{If a unit has elaboration code that can directly or indirectly make a
26069 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
26070 package in a @code{with}'ed unit, then if the @code{with}'ed unit
26071 does not have pragma @code{Pure} or
26072 @code{Preelaborate}, then the client should have an
26073 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
26074
26075 @emph{In the case of instantiating a generic subprogram, it is always
26076 sufficient to have only an @code{Elaborate} pragma for the
26077 @code{with}'ed unit.}
26078 @end itemize
26079
26080 @noindent
26081 By following this rule a client is assured that calls and instantiations
26082 can be made without risk of an exception.
26083
26084 In this mode GNAT traces all calls that are potentially made from
26085 elaboration code, and puts in any missing implicit @code{Elaborate}
26086 and @code{Elaborate_All} pragmas.
26087 The advantage of this approach is that no elaboration problems
26088 are possible if the binder can find an elaboration order that is
26089 consistent with these implicit @code{Elaborate} and
26090 @code{Elaborate_All} pragmas. The
26091 disadvantage of this approach is that no such order may exist.
26092
26093 If the binder does not generate any diagnostics, then it means that it has
26094 found an elaboration order that is guaranteed to be safe. However, the binder
26095 may still be relying on implicitly generated @code{Elaborate} and
26096 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
26097 guaranteed.
26098
26099 If it is important to guarantee portability, then the compilations should
26100 use the
26101 @option{-gnatel}
26102 (info messages for elaboration prag mas) switch. This will cause info messages
26103 to be generated indicating the missing @code{Elaborate} and
26104 @code{Elaborate_All} pragmas.
26105 Consider the following source program:
26106
26107 @smallexample @c ada
26108 @group
26109 @cartouche
26110 with k;
26111 package j is
26112 m : integer := k.r;
26113 end;
26114 @end cartouche
26115 @end group
26116 @end smallexample
26117
26118 @noindent
26119 where it is clear that there
26120 should be a pragma @code{Elaborate_All}
26121 for unit @code{k}. An implicit pragma will be generated, and it is
26122 likely that the binder will be able to honor it. However, if you want
26123 to port this program to some other Ada compiler than GNAT.
26124 it is safer to include the pragma explicitly in the source. If this
26125 unit is compiled with the
26126 @option{-gnatel}
26127 switch, then the compiler outputs an information message:
26128
26129 @smallexample
26130 @group
26131 @cartouche
26132 1. with k;
26133 2. package j is
26134 3. m : integer := k.r;
26135 |
26136 >>> info: call to "r" may raise Program_Error
26137 >>> info: missing pragma Elaborate_All for "k"
26138
26139 4. end;
26140 @end cartouche
26141 @end group
26142 @end smallexample
26143
26144 @noindent
26145 and these messages can be used as a guide for supplying manually
26146 the missing pragmas. It is usually a bad idea to use this
26147 option during development. That's because it will tell you when
26148 you need to put in a pragma, but cannot tell you when it is time
26149 to take it out. So the use of pragma @code{Elaborate_All} may lead to
26150 unnecessary dependencies and even false circularities.
26151
26152 This default mode is more restrictive than the Ada Reference
26153 Manual, and it is possible to construct programs which will compile
26154 using the dynamic model described there, but will run into a
26155 circularity using the safer static model we have described.
26156
26157 Of course any Ada compiler must be able to operate in a mode
26158 consistent with the requirements of the Ada Reference Manual,
26159 and in particular must have the capability of implementing the
26160 standard dynamic model of elaboration with run-time checks.
26161
26162 In GNAT, this standard mode can be achieved either by the use of
26163 the @option{-gnatE} switch on the compiler (@command{gcc} or
26164 @command{gnatmake}) command, or by the use of the configuration pragma:
26165
26166 @smallexample @c ada
26167 pragma Elaboration_Checks (DYNAMIC);
26168 @end smallexample
26169
26170 @noindent
26171 Either approach will cause the unit affected to be compiled using the
26172 standard dynamic run-time elaboration checks described in the Ada
26173 Reference Manual. The static model is generally preferable, since it
26174 is clearly safer to rely on compile and link time checks rather than
26175 run-time checks. However, in the case of legacy code, it may be
26176 difficult to meet the requirements of the static model. This
26177 issue is further discussed in
26178 @ref{What to Do If the Default Elaboration Behavior Fails}.
26179
26180 Note that the static model provides a strict subset of the allowed
26181 behavior and programs of the Ada Reference Manual, so if you do
26182 adhere to the static model and no circularities exist,
26183 then you are assured that your program will
26184 work using the dynamic model, providing that you remove any
26185 pragma Elaborate statements from the source.
26186
26187 @node Treatment of Pragma Elaborate
26188 @section Treatment of Pragma Elaborate
26189 @cindex Pragma Elaborate
26190
26191 @noindent
26192 The use of @code{pragma Elaborate}
26193 should generally be avoided in Ada 95 and Ada 2005 programs,
26194 since there is no guarantee that transitive calls
26195 will be properly handled. Indeed at one point, this pragma was placed
26196 in Annex J (Obsolescent Features), on the grounds that it is never useful.
26197
26198 Now that's a bit restrictive. In practice, the case in which
26199 @code{pragma Elaborate} is useful is when the caller knows that there
26200 are no transitive calls, or that the called unit contains all necessary
26201 transitive @code{pragma Elaborate} statements, and legacy code often
26202 contains such uses.
26203
26204 Strictly speaking the static mode in GNAT should ignore such pragmas,
26205 since there is no assurance at compile time that the necessary safety
26206 conditions are met. In practice, this would cause GNAT to be incompatible
26207 with correctly written Ada 83 code that had all necessary
26208 @code{pragma Elaborate} statements in place. Consequently, we made the
26209 decision that GNAT in its default mode will believe that if it encounters
26210 a @code{pragma Elaborate} then the programmer knows what they are doing,
26211 and it will trust that no elaboration errors can occur.
26212
26213 The result of this decision is two-fold. First to be safe using the
26214 static mode, you should remove all @code{pragma Elaborate} statements.
26215 Second, when fixing circularities in existing code, you can selectively
26216 use @code{pragma Elaborate} statements to convince the static mode of
26217 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
26218 statement.
26219
26220 When using the static mode with @option{-gnatwl}, any use of
26221 @code{pragma Elaborate} will generate a warning about possible
26222 problems.
26223
26224 @node Elaboration Issues for Library Tasks
26225 @section Elaboration Issues for Library Tasks
26226 @cindex Library tasks, elaboration issues
26227 @cindex Elaboration of library tasks
26228
26229 @noindent
26230 In this section we examine special elaboration issues that arise for
26231 programs that declare library level tasks.
26232
26233 Generally the model of execution of an Ada program is that all units are
26234 elaborated, and then execution of the program starts. However, the
26235 declaration of library tasks definitely does not fit this model. The
26236 reason for this is that library tasks start as soon as they are declared
26237 (more precisely, as soon as the statement part of the enclosing package
26238 body is reached), that is to say before elaboration
26239 of the program is complete. This means that if such a task calls a
26240 subprogram, or an entry in another task, the callee may or may not be
26241 elaborated yet, and in the standard
26242 Reference Manual model of dynamic elaboration checks, you can even
26243 get timing dependent Program_Error exceptions, since there can be
26244 a race between the elaboration code and the task code.
26245
26246 The static model of elaboration in GNAT seeks to avoid all such
26247 dynamic behavior, by being conservative, and the conservative
26248 approach in this particular case is to assume that all the code
26249 in a task body is potentially executed at elaboration time if
26250 a task is declared at the library level.
26251
26252 This can definitely result in unexpected circularities. Consider
26253 the following example
26254
26255 @smallexample @c ada
26256 package Decls is
26257 task Lib_Task is
26258 entry Start;
26259 end Lib_Task;
26260
26261 type My_Int is new Integer;
26262
26263 function Ident (M : My_Int) return My_Int;
26264 end Decls;
26265
26266 with Utils;
26267 package body Decls is
26268 task body Lib_Task is
26269 begin
26270 accept Start;
26271 Utils.Put_Val (2);
26272 end Lib_Task;
26273
26274 function Ident (M : My_Int) return My_Int is
26275 begin
26276 return M;
26277 end Ident;
26278 end Decls;
26279
26280 with Decls;
26281 package Utils is
26282 procedure Put_Val (Arg : Decls.My_Int);
26283 end Utils;
26284
26285 with Text_IO;
26286 package body Utils is
26287 procedure Put_Val (Arg : Decls.My_Int) is
26288 begin
26289 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
26290 end Put_Val;
26291 end Utils;
26292
26293 with Decls;
26294 procedure Main is
26295 begin
26296 Decls.Lib_Task.Start;
26297 end;
26298 @end smallexample
26299
26300 @noindent
26301 If the above example is compiled in the default static elaboration
26302 mode, then a circularity occurs. The circularity comes from the call
26303 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
26304 this call occurs in elaboration code, we need an implicit pragma
26305 @code{Elaborate_All} for @code{Utils}. This means that not only must
26306 the spec and body of @code{Utils} be elaborated before the body
26307 of @code{Decls}, but also the spec and body of any unit that is
26308 @code{with'ed} by the body of @code{Utils} must also be elaborated before
26309 the body of @code{Decls}. This is the transitive implication of
26310 pragma @code{Elaborate_All} and it makes sense, because in general
26311 the body of @code{Put_Val} might have a call to something in a
26312 @code{with'ed} unit.
26313
26314 In this case, the body of Utils (actually its spec) @code{with's}
26315 @code{Decls}. Unfortunately this means that the body of @code{Decls}
26316 must be elaborated before itself, in case there is a call from the
26317 body of @code{Utils}.
26318
26319 Here is the exact chain of events we are worrying about:
26320
26321 @enumerate
26322 @item
26323 In the body of @code{Decls} a call is made from within the body of a library
26324 task to a subprogram in the package @code{Utils}. Since this call may
26325 occur at elaboration time (given that the task is activated at elaboration
26326 time), we have to assume the worst, i.e., that the
26327 call does happen at elaboration time.
26328
26329 @item
26330 This means that the body and spec of @code{Util} must be elaborated before
26331 the body of @code{Decls} so that this call does not cause an access before
26332 elaboration.
26333
26334 @item
26335 Within the body of @code{Util}, specifically within the body of
26336 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
26337 by this package.
26338
26339 @item
26340 One such @code{with}'ed package is package @code{Decls}, so there
26341 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
26342 In fact there is such a call in this example, but we would have to
26343 assume that there was such a call even if it were not there, since
26344 we are not supposed to write the body of @code{Decls} knowing what
26345 is in the body of @code{Utils}; certainly in the case of the
26346 static elaboration model, the compiler does not know what is in
26347 other bodies and must assume the worst.
26348
26349 @item
26350 This means that the spec and body of @code{Decls} must also be
26351 elaborated before we elaborate the unit containing the call, but
26352 that unit is @code{Decls}! This means that the body of @code{Decls}
26353 must be elaborated before itself, and that's a circularity.
26354 @end enumerate
26355
26356 @noindent
26357 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
26358 the body of @code{Decls} you will get a true Ada Reference Manual
26359 circularity that makes the program illegal.
26360
26361 In practice, we have found that problems with the static model of
26362 elaboration in existing code often arise from library tasks, so
26363 we must address this particular situation.
26364
26365 Note that if we compile and run the program above, using the dynamic model of
26366 elaboration (that is to say use the @option{-gnatE} switch),
26367 then it compiles, binds,
26368 links, and runs, printing the expected result of 2. Therefore in some sense
26369 the circularity here is only apparent, and we need to capture
26370 the properties of this program that distinguish it from other library-level
26371 tasks that have real elaboration problems.
26372
26373 We have four possible answers to this question:
26374
26375 @itemize @bullet
26376
26377 @item
26378 Use the dynamic model of elaboration.
26379
26380 If we use the @option{-gnatE} switch, then as noted above, the program works.
26381 Why is this? If we examine the task body, it is apparent that the task cannot
26382 proceed past the
26383 @code{accept} statement until after elaboration has been completed, because
26384 the corresponding entry call comes from the main program, not earlier.
26385 This is why the dynamic model works here. But that's really giving
26386 up on a precise analysis, and we prefer to take this approach only if we cannot
26387 solve the
26388 problem in any other manner. So let us examine two ways to reorganize
26389 the program to avoid the potential elaboration problem.
26390
26391 @item
26392 Split library tasks into separate packages.
26393
26394 Write separate packages, so that library tasks are isolated from
26395 other declarations as much as possible. Let us look at a variation on
26396 the above program.
26397
26398 @smallexample @c ada
26399 package Decls1 is
26400 task Lib_Task is
26401 entry Start;
26402 end Lib_Task;
26403 end Decls1;
26404
26405 with Utils;
26406 package body Decls1 is
26407 task body Lib_Task is
26408 begin
26409 accept Start;
26410 Utils.Put_Val (2);
26411 end Lib_Task;
26412 end Decls1;
26413
26414 package Decls2 is
26415 type My_Int is new Integer;
26416 function Ident (M : My_Int) return My_Int;
26417 end Decls2;
26418
26419 with Utils;
26420 package body Decls2 is
26421 function Ident (M : My_Int) return My_Int is
26422 begin
26423 return M;
26424 end Ident;
26425 end Decls2;
26426
26427 with Decls2;
26428 package Utils is
26429 procedure Put_Val (Arg : Decls2.My_Int);
26430 end Utils;
26431
26432 with Text_IO;
26433 package body Utils is
26434 procedure Put_Val (Arg : Decls2.My_Int) is
26435 begin
26436 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
26437 end Put_Val;
26438 end Utils;
26439
26440 with Decls1;
26441 procedure Main is
26442 begin
26443 Decls1.Lib_Task.Start;
26444 end;
26445 @end smallexample
26446
26447 @noindent
26448 All we have done is to split @code{Decls} into two packages, one
26449 containing the library task, and one containing everything else. Now
26450 there is no cycle, and the program compiles, binds, links and executes
26451 using the default static model of elaboration.
26452
26453 @item
26454 Declare separate task types.
26455
26456 A significant part of the problem arises because of the use of the
26457 single task declaration form. This means that the elaboration of
26458 the task type, and the elaboration of the task itself (i.e.@: the
26459 creation of the task) happen at the same time. A good rule
26460 of style in Ada is to always create explicit task types. By
26461 following the additional step of placing task objects in separate
26462 packages from the task type declaration, many elaboration problems
26463 are avoided. Here is another modified example of the example program:
26464
26465 @smallexample @c ada
26466 package Decls is
26467 task type Lib_Task_Type is
26468 entry Start;
26469 end Lib_Task_Type;
26470
26471 type My_Int is new Integer;
26472
26473 function Ident (M : My_Int) return My_Int;
26474 end Decls;
26475
26476 with Utils;
26477 package body Decls is
26478 task body Lib_Task_Type is
26479 begin
26480 accept Start;
26481 Utils.Put_Val (2);
26482 end Lib_Task_Type;
26483
26484 function Ident (M : My_Int) return My_Int is
26485 begin
26486 return M;
26487 end Ident;
26488 end Decls;
26489
26490 with Decls;
26491 package Utils is
26492 procedure Put_Val (Arg : Decls.My_Int);
26493 end Utils;
26494
26495 with Text_IO;
26496 package body Utils is
26497 procedure Put_Val (Arg : Decls.My_Int) is
26498 begin
26499 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
26500 end Put_Val;
26501 end Utils;
26502
26503 with Decls;
26504 package Declst is
26505 Lib_Task : Decls.Lib_Task_Type;
26506 end Declst;
26507
26508 with Declst;
26509 procedure Main is
26510 begin
26511 Declst.Lib_Task.Start;
26512 end;
26513 @end smallexample
26514
26515 @noindent
26516 What we have done here is to replace the @code{task} declaration in
26517 package @code{Decls} with a @code{task type} declaration. Then we
26518 introduce a separate package @code{Declst} to contain the actual
26519 task object. This separates the elaboration issues for
26520 the @code{task type}
26521 declaration, which causes no trouble, from the elaboration issues
26522 of the task object, which is also unproblematic, since it is now independent
26523 of the elaboration of @code{Utils}.
26524 This separation of concerns also corresponds to
26525 a generally sound engineering principle of separating declarations
26526 from instances. This version of the program also compiles, binds, links,
26527 and executes, generating the expected output.
26528
26529 @item
26530 Use No_Entry_Calls_In_Elaboration_Code restriction.
26531 @cindex No_Entry_Calls_In_Elaboration_Code
26532
26533 The previous two approaches described how a program can be restructured
26534 to avoid the special problems caused by library task bodies. in practice,
26535 however, such restructuring may be difficult to apply to existing legacy code,
26536 so we must consider solutions that do not require massive rewriting.
26537
26538 Let us consider more carefully why our original sample program works
26539 under the dynamic model of elaboration. The reason is that the code
26540 in the task body blocks immediately on the @code{accept}
26541 statement. Now of course there is nothing to prohibit elaboration
26542 code from making entry calls (for example from another library level task),
26543 so we cannot tell in isolation that
26544 the task will not execute the accept statement during elaboration.
26545
26546 However, in practice it is very unusual to see elaboration code
26547 make any entry calls, and the pattern of tasks starting
26548 at elaboration time and then immediately blocking on @code{accept} or
26549 @code{select} statements is very common. What this means is that
26550 the compiler is being too pessimistic when it analyzes the
26551 whole package body as though it might be executed at elaboration
26552 time.
26553
26554 If we know that the elaboration code contains no entry calls, (a very safe
26555 assumption most of the time, that could almost be made the default
26556 behavior), then we can compile all units of the program under control
26557 of the following configuration pragma:
26558
26559 @smallexample
26560 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
26561 @end smallexample
26562
26563 @noindent
26564 This pragma can be placed in the @file{gnat.adc} file in the usual
26565 manner. If we take our original unmodified program and compile it
26566 in the presence of a @file{gnat.adc} containing the above pragma,
26567 then once again, we can compile, bind, link, and execute, obtaining
26568 the expected result. In the presence of this pragma, the compiler does
26569 not trace calls in a task body, that appear after the first @code{accept}
26570 or @code{select} statement, and therefore does not report a potential
26571 circularity in the original program.
26572
26573 The compiler will check to the extent it can that the above
26574 restriction is not violated, but it is not always possible to do a
26575 complete check at compile time, so it is important to use this
26576 pragma only if the stated restriction is in fact met, that is to say
26577 no task receives an entry call before elaboration of all units is completed.
26578
26579 @end itemize
26580
26581 @node Mixing Elaboration Models
26582 @section Mixing Elaboration Models
26583 @noindent
26584 So far, we have assumed that the entire program is either compiled
26585 using the dynamic model or static model, ensuring consistency. It
26586 is possible to mix the two models, but rules have to be followed
26587 if this mixing is done to ensure that elaboration checks are not
26588 omitted.
26589
26590 The basic rule is that @emph{a unit compiled with the static model cannot
26591 be @code{with'ed} by a unit compiled with the dynamic model}. The
26592 reason for this is that in the static model, a unit assumes that
26593 its clients guarantee to use (the equivalent of) pragma
26594 @code{Elaborate_All} so that no elaboration checks are required
26595 in inner subprograms, and this assumption is violated if the
26596 client is compiled with dynamic checks.
26597
26598 The precise rule is as follows. A unit that is compiled with dynamic
26599 checks can only @code{with} a unit that meets at least one of the
26600 following criteria:
26601
26602 @itemize @bullet
26603
26604 @item
26605 The @code{with'ed} unit is itself compiled with dynamic elaboration
26606 checks (that is with the @option{-gnatE} switch.
26607
26608 @item
26609 The @code{with'ed} unit is an internal GNAT implementation unit from
26610 the System, Interfaces, Ada, or GNAT hierarchies.
26611
26612 @item
26613 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
26614
26615 @item
26616 The @code{with'ing} unit (that is the client) has an explicit pragma
26617 @code{Elaborate_All} for the @code{with'ed} unit.
26618
26619 @end itemize
26620
26621 @noindent
26622 If this rule is violated, that is if a unit with dynamic elaboration
26623 checks @code{with's} a unit that does not meet one of the above four
26624 criteria, then the binder (@code{gnatbind}) will issue a warning
26625 similar to that in the following example:
26626
26627 @smallexample
26628 warning: "x.ads" has dynamic elaboration checks and with's
26629 warning: "y.ads" which has static elaboration checks
26630 @end smallexample
26631
26632 @noindent
26633 These warnings indicate that the rule has been violated, and that as a result
26634 elaboration checks may be missed in the resulting executable file.
26635 This warning may be suppressed using the @option{-ws} binder switch
26636 in the usual manner.
26637
26638 One useful application of this mixing rule is in the case of a subsystem
26639 which does not itself @code{with} units from the remainder of the
26640 application. In this case, the entire subsystem can be compiled with
26641 dynamic checks to resolve a circularity in the subsystem, while
26642 allowing the main application that uses this subsystem to be compiled
26643 using the more reliable default static model.
26644
26645 @node What to Do If the Default Elaboration Behavior Fails
26646 @section What to Do If the Default Elaboration Behavior Fails
26647
26648 @noindent
26649 If the binder cannot find an acceptable order, it outputs detailed
26650 diagnostics. For example:
26651 @smallexample
26652 @group
26653 @iftex
26654 @leftskip=0cm
26655 @end iftex
26656 error: elaboration circularity detected
26657 info: "proc (body)" must be elaborated before "pack (body)"
26658 info: reason: Elaborate_All probably needed in unit "pack (body)"
26659 info: recompile "pack (body)" with -gnatel
26660 info: for full details
26661 info: "proc (body)"
26662 info: is needed by its spec:
26663 info: "proc (spec)"
26664 info: which is withed by:
26665 info: "pack (body)"
26666 info: "pack (body)" must be elaborated before "proc (body)"
26667 info: reason: pragma Elaborate in unit "proc (body)"
26668 @end group
26669
26670 @end smallexample
26671
26672 @noindent
26673 In this case we have a cycle that the binder cannot break. On the one
26674 hand, there is an explicit pragma Elaborate in @code{proc} for
26675 @code{pack}. This means that the body of @code{pack} must be elaborated
26676 before the body of @code{proc}. On the other hand, there is elaboration
26677 code in @code{pack} that calls a subprogram in @code{proc}. This means
26678 that for maximum safety, there should really be a pragma
26679 Elaborate_All in @code{pack} for @code{proc} which would require that
26680 the body of @code{proc} be elaborated before the body of
26681 @code{pack}. Clearly both requirements cannot be satisfied.
26682 Faced with a circularity of this kind, you have three different options.
26683
26684 @table @asis
26685 @item Fix the program
26686 The most desirable option from the point of view of long-term maintenance
26687 is to rearrange the program so that the elaboration problems are avoided.
26688 One useful technique is to place the elaboration code into separate
26689 child packages. Another is to move some of the initialization code to
26690 explicitly called subprograms, where the program controls the order
26691 of initialization explicitly. Although this is the most desirable option,
26692 it may be impractical and involve too much modification, especially in
26693 the case of complex legacy code.
26694
26695 @item Perform dynamic checks
26696 If the compilations are done using the
26697 @option{-gnatE}
26698 (dynamic elaboration check) switch, then GNAT behaves in a quite different
26699 manner. Dynamic checks are generated for all calls that could possibly result
26700 in raising an exception. With this switch, the compiler does not generate
26701 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
26702 exactly as specified in the @cite{Ada Reference Manual}.
26703 The binder will generate
26704 an executable program that may or may not raise @code{Program_Error}, and then
26705 it is the programmer's job to ensure that it does not raise an exception. Note
26706 that it is important to compile all units with the switch, it cannot be used
26707 selectively.
26708
26709 @item Suppress checks
26710 The drawback of dynamic checks is that they generate a
26711 significant overhead at run time, both in space and time. If you
26712 are absolutely sure that your program cannot raise any elaboration
26713 exceptions, and you still want to use the dynamic elaboration model,
26714 then you can use the configuration pragma
26715 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
26716 example this pragma could be placed in the @file{gnat.adc} file.
26717
26718 @item Suppress checks selectively
26719 When you know that certain calls or instantiations in elaboration code cannot
26720 possibly lead to an elaboration error, and the binder nevertheless complains
26721 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
26722 elaboration circularities, it is possible to remove those warnings locally and
26723 obtain a program that will bind. Clearly this can be unsafe, and it is the
26724 responsibility of the programmer to make sure that the resulting program has no
26725 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
26726 used with different granularity to suppress warnings and break elaboration
26727 circularities:
26728
26729 @itemize @bullet
26730 @item
26731 Place the pragma that names the called subprogram in the declarative part
26732 that contains the call.
26733
26734 @item
26735 Place the pragma in the declarative part, without naming an entity. This
26736 disables warnings on all calls in the corresponding declarative region.
26737
26738 @item
26739 Place the pragma in the package spec that declares the called subprogram,
26740 and name the subprogram. This disables warnings on all elaboration calls to
26741 that subprogram.
26742
26743 @item
26744 Place the pragma in the package spec that declares the called subprogram,
26745 without naming any entity. This disables warnings on all elaboration calls to
26746 all subprograms declared in this spec.
26747
26748 @item Use Pragma Elaborate
26749 As previously described in section @xref{Treatment of Pragma Elaborate},
26750 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
26751 that no elaboration checks are required on calls to the designated unit.
26752 There may be cases in which the caller knows that no transitive calls
26753 can occur, so that a @code{pragma Elaborate} will be sufficient in a
26754 case where @code{pragma Elaborate_All} would cause a circularity.
26755 @end itemize
26756
26757 @noindent
26758 These five cases are listed in order of decreasing safety, and therefore
26759 require increasing programmer care in their application. Consider the
26760 following program:
26761
26762 @smallexample @c adanocomment
26763 package Pack1 is
26764 function F1 return Integer;
26765 X1 : Integer;
26766 end Pack1;
26767
26768 package Pack2 is
26769 function F2 return Integer;
26770 function Pure (x : integer) return integer;
26771 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
26772 -- pragma Suppress (Elaboration_Check); -- (4)
26773 end Pack2;
26774
26775 with Pack2;
26776 package body Pack1 is
26777 function F1 return Integer is
26778 begin
26779 return 100;
26780 end F1;
26781 Val : integer := Pack2.Pure (11); -- Elab. call (1)
26782 begin
26783 declare
26784 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
26785 -- pragma Suppress(Elaboration_Check); -- (2)
26786 begin
26787 X1 := Pack2.F2 + 1; -- Elab. call (2)
26788 end;
26789 end Pack1;
26790
26791 with Pack1;
26792 package body Pack2 is
26793 function F2 return Integer is
26794 begin
26795 return Pack1.F1;
26796 end F2;
26797 function Pure (x : integer) return integer is
26798 begin
26799 return x ** 3 - 3 * x;
26800 end;
26801 end Pack2;
26802
26803 with Pack1, Ada.Text_IO;
26804 procedure Proc3 is
26805 begin
26806 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
26807 end Proc3;
26808 @end smallexample
26809 In the absence of any pragmas, an attempt to bind this program produces
26810 the following diagnostics:
26811 @smallexample
26812 @group
26813 @iftex
26814 @leftskip=.5cm
26815 @end iftex
26816 error: elaboration circularity detected
26817 info: "pack1 (body)" must be elaborated before "pack1 (body)"
26818 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
26819 info: recompile "pack1 (body)" with -gnatel for full details
26820 info: "pack1 (body)"
26821 info: must be elaborated along with its spec:
26822 info: "pack1 (spec)"
26823 info: which is withed by:
26824 info: "pack2 (body)"
26825 info: which must be elaborated along with its spec:
26826 info: "pack2 (spec)"
26827 info: which is withed by:
26828 info: "pack1 (body)"
26829 @end group
26830 @end smallexample
26831 The sources of the circularity are the two calls to @code{Pack2.Pure} and
26832 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
26833 F2 is safe, even though F2 calls F1, because the call appears after the
26834 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
26835 remove the warning on the call. It is also possible to use pragma (2)
26836 because there are no other potentially unsafe calls in the block.
26837
26838 @noindent
26839 The call to @code{Pure} is safe because this function does not depend on the
26840 state of @code{Pack2}. Therefore any call to this function is safe, and it
26841 is correct to place pragma (3) in the corresponding package spec.
26842
26843 @noindent
26844 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
26845 warnings on all calls to functions declared therein. Note that this is not
26846 necessarily safe, and requires more detailed examination of the subprogram
26847 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
26848 be already elaborated.
26849 @end table
26850
26851 @noindent
26852 It is hard to generalize on which of these four approaches should be
26853 taken. Obviously if it is possible to fix the program so that the default
26854 treatment works, this is preferable, but this may not always be practical.
26855 It is certainly simple enough to use
26856 @option{-gnatE}
26857 but the danger in this case is that, even if the GNAT binder
26858 finds a correct elaboration order, it may not always do so,
26859 and certainly a binder from another Ada compiler might not. A
26860 combination of testing and analysis (for which the
26861 information messages generated with the
26862 @option{-gnatel}
26863 switch can be useful) must be used to ensure that the program is free
26864 of errors. One switch that is useful in this testing is the
26865 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
26866 switch for
26867 @code{gnatbind}.
26868 Normally the binder tries to find an order that has the best chance
26869 of avoiding elaboration problems. However, if this switch is used, the binder
26870 plays a devil's advocate role, and tries to choose the order that
26871 has the best chance of failing. If your program works even with this
26872 switch, then it has a better chance of being error free, but this is still
26873 not a guarantee.
26874
26875 For an example of this approach in action, consider the C-tests (executable
26876 tests) from the ACVC suite. If these are compiled and run with the default
26877 treatment, then all but one of them succeed without generating any error
26878 diagnostics from the binder. However, there is one test that fails, and
26879 this is not surprising, because the whole point of this test is to ensure
26880 that the compiler can handle cases where it is impossible to determine
26881 a correct order statically, and it checks that an exception is indeed
26882 raised at run time.
26883
26884 This one test must be compiled and run using the
26885 @option{-gnatE}
26886 switch, and then it passes. Alternatively, the entire suite can
26887 be run using this switch. It is never wrong to run with the dynamic
26888 elaboration switch if your code is correct, and we assume that the
26889 C-tests are indeed correct (it is less efficient, but efficiency is
26890 not a factor in running the ACVC tests.)
26891
26892 @node Elaboration for Indirect Calls
26893 @section Elaboration for Indirect Calls
26894 @cindex Dispatching calls
26895 @cindex Indirect calls
26896
26897 @noindent
26898 In rare cases, the static elaboration model fails to prevent
26899 dispatching calls to not-yet-elaborated subprograms. In such cases, we
26900 fall back to run-time checks; premature calls to any primitive
26901 operation of a tagged type before the body of the operation has been
26902 elaborated will raise @code{Program_Error}.
26903
26904 Access-to-subprogram types, however, are handled conservatively, and
26905 do not require run-time checks. This was not true in earlier versions
26906 of the compiler; you can use the @option{-gnatd.U} debug switch to
26907 revert to the old behavior if the new conservative behavior causes
26908 elaboration cycles. Here, ``conservative'' means that if you do
26909 @code{P'Access} during elaboration, the compiler will assume that you
26910 might call @code{P} indirectly during elaboration, so it adds an
26911 implicit @code{pragma Elaborate_All} on the library unit containing
26912 @code{P}. The @option{-gnatd.U} switch is safe if you know there are
26913 no such calls. If the program worked before, it will continue to work
26914 with @option{-gnatd.U}. But beware that code modifications such as
26915 adding an indirect call can cause erroneous behavior in the presence
26916 of @option{-gnatd.U}.
26917
26918 @node Summary of Procedures for Elaboration Control
26919 @section Summary of Procedures for Elaboration Control
26920 @cindex Elaboration control
26921
26922 @noindent
26923 First, compile your program with the default options, using none of
26924 the special elaboration control switches. If the binder successfully
26925 binds your program, then you can be confident that, apart from issues
26926 raised by the use of access-to-subprogram types and dynamic dispatching,
26927 the program is free of elaboration errors. If it is important that the
26928 program be portable to other compilers than GNAT, then use the
26929 @option{-gnatel}
26930 switch to generate messages about missing @code{Elaborate} or
26931 @code{Elaborate_All} pragmas, and supply the missing pragmas.
26932
26933 If the program fails to bind using the default static elaboration
26934 handling, then you can fix the program to eliminate the binder
26935 message, or recompile the entire program with the
26936 @option{-gnatE} switch to generate dynamic elaboration checks,
26937 and, if you are sure there really are no elaboration problems,
26938 use a global pragma @code{Suppress (Elaboration_Check)}.
26939
26940 @node Other Elaboration Order Considerations
26941 @section Other Elaboration Order Considerations
26942 @noindent
26943 This section has been entirely concerned with the issue of finding a valid
26944 elaboration order, as defined by the Ada Reference Manual. In a case
26945 where several elaboration orders are valid, the task is to find one
26946 of the possible valid elaboration orders (and the static model in GNAT
26947 will ensure that this is achieved).
26948
26949 The purpose of the elaboration rules in the Ada Reference Manual is to
26950 make sure that no entity is accessed before it has been elaborated. For
26951 a subprogram, this means that the spec and body must have been elaborated
26952 before the subprogram is called. For an object, this means that the object
26953 must have been elaborated before its value is read or written. A violation
26954 of either of these two requirements is an access before elaboration order,
26955 and this section has been all about avoiding such errors.
26956
26957 In the case where more than one order of elaboration is possible, in the
26958 sense that access before elaboration errors are avoided, then any one of
26959 the orders is ``correct'' in the sense that it meets the requirements of
26960 the Ada Reference Manual, and no such error occurs.
26961
26962 However, it may be the case for a given program, that there are
26963 constraints on the order of elaboration that come not from consideration
26964 of avoiding elaboration errors, but rather from extra-lingual logic
26965 requirements. Consider this example:
26966
26967 @smallexample @c ada
26968 with Init_Constants;
26969 package Constants is
26970 X : Integer := 0;
26971 Y : Integer := 0;
26972 end Constants;
26973
26974 package Init_Constants is
26975 procedure P; -- require a body
26976 end Init_Constants;
26977
26978 with Constants;
26979 package body Init_Constants is
26980 procedure P is begin null; end;
26981 begin
26982 Constants.X := 3;
26983 Constants.Y := 4;
26984 end Init_Constants;
26985
26986 with Constants;
26987 package Calc is
26988 Z : Integer := Constants.X + Constants.Y;
26989 end Calc;
26990
26991 with Calc;
26992 with Text_IO; use Text_IO;
26993 procedure Main is
26994 begin
26995 Put_Line (Calc.Z'Img);
26996 end Main;
26997 @end smallexample
26998
26999 @noindent
27000 In this example, there is more than one valid order of elaboration. For
27001 example both the following are correct orders:
27002
27003 @smallexample
27004 Init_Constants spec
27005 Constants spec
27006 Calc spec
27007 Init_Constants body
27008 Main body
27009
27010 and
27011
27012 Init_Constants spec
27013 Init_Constants body
27014 Constants spec
27015 Calc spec
27016 Main body
27017 @end smallexample
27018
27019 @noindent
27020 There is no language rule to prefer one or the other, both are correct
27021 from an order of elaboration point of view. But the programmatic effects
27022 of the two orders are very different. In the first, the elaboration routine
27023 of @code{Calc} initializes @code{Z} to zero, and then the main program
27024 runs with this value of zero. But in the second order, the elaboration
27025 routine of @code{Calc} runs after the body of Init_Constants has set
27026 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
27027 runs.
27028
27029 One could perhaps by applying pretty clever non-artificial intelligence
27030 to the situation guess that it is more likely that the second order of
27031 elaboration is the one desired, but there is no formal linguistic reason
27032 to prefer one over the other. In fact in this particular case, GNAT will
27033 prefer the second order, because of the rule that bodies are elaborated
27034 as soon as possible, but it's just luck that this is what was wanted
27035 (if indeed the second order was preferred).
27036
27037 If the program cares about the order of elaboration routines in a case like
27038 this, it is important to specify the order required. In this particular
27039 case, that could have been achieved by adding to the spec of Calc:
27040
27041 @smallexample @c ada
27042 pragma Elaborate_All (Constants);
27043 @end smallexample
27044
27045 @noindent
27046 which requires that the body (if any) and spec of @code{Constants},
27047 as well as the body and spec of any unit @code{with}'ed by
27048 @code{Constants} be elaborated before @code{Calc} is elaborated.
27049
27050 Clearly no automatic method can always guess which alternative you require,
27051 and if you are working with legacy code that had constraints of this kind
27052 which were not properly specified by adding @code{Elaborate} or
27053 @code{Elaborate_All} pragmas, then indeed it is possible that two different
27054 compilers can choose different orders.
27055
27056 However, GNAT does attempt to diagnose the common situation where there
27057 are uninitialized variables in the visible part of a package spec, and the
27058 corresponding package body has an elaboration block that directly or
27059 indirectly initialized one or more of these variables. This is the situation
27060 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
27061 a warning that suggests this addition if it detects this situation.
27062
27063 The @code{gnatbind}
27064 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
27065 out problems. This switch causes bodies to be elaborated as late as possible
27066 instead of as early as possible. In the example above, it would have forced
27067 the choice of the first elaboration order. If you get different results
27068 when using this switch, and particularly if one set of results is right,
27069 and one is wrong as far as you are concerned, it shows that you have some
27070 missing @code{Elaborate} pragmas. For the example above, we have the
27071 following output:
27072
27073 @smallexample
27074 gnatmake -f -q main
27075 main
27076 7
27077 gnatmake -f -q main -bargs -p
27078 main
27079 0
27080 @end smallexample
27081
27082 @noindent
27083 It is of course quite unlikely that both these results are correct, so
27084 it is up to you in a case like this to investigate the source of the
27085 difference, by looking at the two elaboration orders that are chosen,
27086 and figuring out which is correct, and then adding the necessary
27087 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
27088
27089 @node Determining the Chosen Elaboration Order
27090 @section Determining the Chosen Elaboration Order
27091 @noindent
27092
27093 To see the elaboration order that the binder chooses, you can look at
27094 the last part of the b~xxx.adb binder output file. Here is an example:
27095
27096 @smallexample @c ada
27097 System.Soft_Links'Elab_Body;
27098 E14 := True;
27099 System.Secondary_Stack'Elab_Body;
27100 E18 := True;
27101 System.Exception_Table'Elab_Body;
27102 E24 := True;
27103 Ada.Io_Exceptions'Elab_Spec;
27104 E67 := True;
27105 Ada.Tags'Elab_Spec;
27106 Ada.Streams'Elab_Spec;
27107 E43 := True;
27108 Interfaces.C'Elab_Spec;
27109 E69 := True;
27110 System.Finalization_Root'Elab_Spec;
27111 E60 := True;
27112 System.Os_Lib'Elab_Body;
27113 E71 := True;
27114 System.Finalization_Implementation'Elab_Spec;
27115 System.Finalization_Implementation'Elab_Body;
27116 E62 := True;
27117 Ada.Finalization'Elab_Spec;
27118 E58 := True;
27119 Ada.Finalization.List_Controller'Elab_Spec;
27120 E76 := True;
27121 System.File_Control_Block'Elab_Spec;
27122 E74 := True;
27123 System.File_Io'Elab_Body;
27124 E56 := True;
27125 Ada.Tags'Elab_Body;
27126 E45 := True;
27127 Ada.Text_Io'Elab_Spec;
27128 Ada.Text_Io'Elab_Body;
27129 E07 := True;
27130 @end smallexample
27131
27132 @noindent
27133 Here Elab_Spec elaborates the spec
27134 and Elab_Body elaborates the body. The assignments to the Exx flags
27135 flag that the corresponding body is now elaborated.
27136
27137 You can also ask the binder to generate a more
27138 readable list of the elaboration order using the
27139 @code{-l} switch when invoking the binder. Here is
27140 an example of the output generated by this switch:
27141
27142 @smallexample
27143 ada (spec)
27144 interfaces (spec)
27145 system (spec)
27146 system.case_util (spec)
27147 system.case_util (body)
27148 system.concat_2 (spec)
27149 system.concat_2 (body)
27150 system.concat_3 (spec)
27151 system.concat_3 (body)
27152 system.htable (spec)
27153 system.parameters (spec)
27154 system.parameters (body)
27155 system.crtl (spec)
27156 interfaces.c_streams (spec)
27157 interfaces.c_streams (body)
27158 system.restrictions (spec)
27159 system.restrictions (body)
27160 system.standard_library (spec)
27161 system.exceptions (spec)
27162 system.exceptions (body)
27163 system.storage_elements (spec)
27164 system.storage_elements (body)
27165 system.secondary_stack (spec)
27166 system.stack_checking (spec)
27167 system.stack_checking (body)
27168 system.string_hash (spec)
27169 system.string_hash (body)
27170 system.htable (body)
27171 system.strings (spec)
27172 system.strings (body)
27173 system.traceback (spec)
27174 system.traceback (body)
27175 system.traceback_entries (spec)
27176 system.traceback_entries (body)
27177 ada.exceptions (spec)
27178 ada.exceptions.last_chance_handler (spec)
27179 system.soft_links (spec)
27180 system.soft_links (body)
27181 ada.exceptions.last_chance_handler (body)
27182 system.secondary_stack (body)
27183 system.exception_table (spec)
27184 system.exception_table (body)
27185 ada.io_exceptions (spec)
27186 ada.tags (spec)
27187 ada.streams (spec)
27188 interfaces.c (spec)
27189 interfaces.c (body)
27190 system.finalization_root (spec)
27191 system.finalization_root (body)
27192 system.memory (spec)
27193 system.memory (body)
27194 system.standard_library (body)
27195 system.os_lib (spec)
27196 system.os_lib (body)
27197 system.unsigned_types (spec)
27198 system.stream_attributes (spec)
27199 system.stream_attributes (body)
27200 system.finalization_implementation (spec)
27201 system.finalization_implementation (body)
27202 ada.finalization (spec)
27203 ada.finalization (body)
27204 ada.finalization.list_controller (spec)
27205 ada.finalization.list_controller (body)
27206 system.file_control_block (spec)
27207 system.file_io (spec)
27208 system.file_io (body)
27209 system.val_uns (spec)
27210 system.val_util (spec)
27211 system.val_util (body)
27212 system.val_uns (body)
27213 system.wch_con (spec)
27214 system.wch_con (body)
27215 system.wch_cnv (spec)
27216 system.wch_jis (spec)
27217 system.wch_jis (body)
27218 system.wch_cnv (body)
27219 system.wch_stw (spec)
27220 system.wch_stw (body)
27221 ada.tags (body)
27222 ada.exceptions (body)
27223 ada.text_io (spec)
27224 ada.text_io (body)
27225 text_io (spec)
27226 gdbstr (body)
27227 @end smallexample
27228
27229 @c **********************************
27230 @node Overflow Check Handling in GNAT
27231 @appendix Overflow Check Handling in GNAT
27232 @cindex Overflow checks
27233 @cindex Checks (overflow)
27234 @c **********************************
27235
27236 @menu
27237 * Background::
27238 * Overflow Checking Modes in GNAT::
27239 * Specifying the Desired Mode::
27240 * Default Settings::
27241 * Implementation Notes::
27242 @end menu
27243
27244
27245 @node Background
27246 @section Background
27247
27248 @noindent
27249 Overflow checks are checks that the compiler may make to ensure
27250 that intermediate results are not out of range. For example:
27251
27252 @smallexample @c ada
27253 A : Integer;
27254 ...
27255 A := A + 1;
27256 @end smallexample
27257
27258 @noindent
27259 if @code{A} has the value @code{Integer'Last}, then the addition may cause
27260 overflow since the result is out of range of the type @code{Integer}.
27261 In this case @code{Constraint_Error} will be raised if checks are
27262 enabled.
27263
27264 A trickier situation arises in examples like the following:
27265
27266 @smallexample @c ada
27267 A, C : Integer;
27268 ...
27269 A := (A + 1) + C;
27270 @end smallexample
27271
27272 @noindent
27273 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
27274 Now the final result of the expression on the right hand side is
27275 @code{Integer'Last} which is in range, but the question arises whether the
27276 intermediate addition of @code{(A + 1)} raises an overflow error.
27277
27278 The (perhaps surprising) answer is that the Ada language
27279 definition does not answer this question. Instead it leaves
27280 it up to the implementation to do one of two things if overflow
27281 checks are enabled.
27282
27283 @itemize @bullet
27284 @item
27285 raise an exception (@code{Constraint_Error}), or
27286
27287 @item
27288 yield the correct mathematical result which is then used in
27289 subsequent operations.
27290 @end itemize
27291
27292 @noindent
27293 If the compiler chooses the first approach, then the assignment of this
27294 example will indeed raise @code{Constraint_Error} if overflow checking is
27295 enabled, or result in erroneous execution if overflow checks are suppressed.
27296
27297 But if the compiler
27298 chooses the second approach, then it can perform both additions yielding
27299 the correct mathematical result, which is in range, so no exception
27300 will be raised, and the right result is obtained, regardless of whether
27301 overflow checks are suppressed.
27302
27303 Note that in the first example an
27304 exception will be raised in either case, since if the compiler
27305 gives the correct mathematical result for the addition, it will
27306 be out of range of the target type of the assignment, and thus
27307 fails the range check.
27308
27309 This lack of specified behavior in the handling of overflow for
27310 intermediate results is a source of non-portability, and can thus
27311 be problematic when programs are ported. Most typically this arises
27312 in a situation where the original compiler did not raise an exception,
27313 and then the application is moved to a compiler where the check is
27314 performed on the intermediate result and an unexpected exception is
27315 raised.
27316
27317 Furthermore, when using Ada 2012's preconditions and other
27318 assertion forms, another issue arises. Consider:
27319
27320 @smallexample @c ada
27321 procedure P (A, B : Integer) with
27322 Pre => A + B <= Integer'Last;
27323 @end smallexample
27324
27325 @noindent
27326 One often wants to regard arithmetic in a context like this from
27327 a mathematical point of view. So for example, if the two actual parameters
27328 for a call to @code{P} are both @code{Integer'Last}, then
27329 the precondition should be regarded as False. If we are executing
27330 in a mode with run-time checks enabled for preconditions, then we would
27331 like this precondition to fail, rather than raising an exception
27332 because of the intermediate overflow.
27333
27334 However, the language definition leaves the specification of
27335 whether the above condition fails (raising @code{Assert_Error}) or
27336 causes an intermediate overflow (raising @code{Constraint_Error})
27337 up to the implementation.
27338
27339 The situation is worse in a case such as the following:
27340
27341 @smallexample @c ada
27342 procedure Q (A, B, C : Integer) with
27343 Pre => A + B + C <= Integer'Last;
27344 @end smallexample
27345
27346 @noindent
27347 Consider the call
27348
27349 @smallexample @c ada
27350 Q (A => Integer'Last, B => 1, C => -1);
27351 @end smallexample
27352
27353 @noindent
27354 From a mathematical point of view the precondition
27355 is True, but at run time we may (but are not guaranteed to) get an
27356 exception raised because of the intermediate overflow (and we really
27357 would prefer this precondition to be considered True at run time).
27358
27359 @node Overflow Checking Modes in GNAT
27360 @section Overflow Checking Modes in GNAT
27361
27362 @noindent
27363 To deal with the portability issue, and with the problem of
27364 mathematical versus run-time interpretation of the expressions in
27365 assertions, GNAT provides comprehensive control over the handling
27366 of intermediate overflow. GNAT can operate in three modes, and
27367 furthemore, permits separate selection of operating modes for
27368 the expressions within assertions (here the term ``assertions''
27369 is used in the technical sense, which includes preconditions and so forth)
27370 and for expressions appearing outside assertions.
27371
27372 The three modes are:
27373
27374 @itemize @bullet
27375 @item @i{Use base type for intermediate operations} (@code{STRICT})
27376
27377 In this mode, all intermediate results for predefined arithmetic
27378 operators are computed using the base type, and the result must
27379 be in range of the base type. If this is not the
27380 case then either an exception is raised (if overflow checks are
27381 enabled) or the execution is erroneous (if overflow checks are suppressed).
27382 This is the normal default mode.
27383
27384 @item @i{Most intermediate overflows avoided} (@code{MINIMIZED})
27385
27386 In this mode, the compiler attempts to avoid intermediate overflows by
27387 using a larger integer type, typically @code{Long_Long_Integer},
27388 as the type in which arithmetic is
27389 performed for predefined arithmetic operators. This may be slightly more
27390 expensive at
27391 run time (compared to suppressing intermediate overflow checks), though
27392 the cost is negligible on modern 64-bit machines. For the examples given
27393 earlier, no intermediate overflows would have resulted in exceptions,
27394 since the intermediate results are all in the range of
27395 @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
27396 of GNAT). In addition, if checks are enabled, this reduces the number of
27397 checks that must be made, so this choice may actually result in an
27398 improvement in space and time behavior.
27399
27400 However, there are cases where @code{Long_Long_Integer} is not large
27401 enough, consider the following example:
27402
27403 @smallexample @c ada
27404 procedure R (A, B, C, D : Integer) with
27405 Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
27406 @end smallexample
27407
27408 where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
27409 Now the intermediate results are
27410 out of the range of @code{Long_Long_Integer} even though the final result
27411 is in range and the precondition is True (from a mathematical point
27412 of view). In such a case, operating in this mode, an overflow occurs
27413 for the intermediate computation (which is why this mode
27414 says @i{most} intermediate overflows are avoided). In this case,
27415 an exception is raised if overflow checks are enabled, and the
27416 execution is erroneous if overflow checks are suppressed.
27417
27418 @item @i{All intermediate overflows avoided} (@code{ELIMINATED})
27419
27420 In this mode, the compiler avoids all intermediate overflows
27421 by using arbitrary precision arithmetic as required. In this
27422 mode, the above example with @code{A**2 * B**2} would
27423 not cause intermediate overflow, because the intermediate result
27424 would be evaluated using sufficient precision, and the result
27425 of evaluating the precondition would be True.
27426
27427 This mode has the advantage of avoiding any intermediate
27428 overflows, but at the expense of significant run-time overhead,
27429 including the use of a library (included automatically in this
27430 mode) for multiple-precision arithmetic.
27431
27432 This mode provides cleaner semantics for assertions, since now
27433 the run-time behavior emulates true arithmetic behavior for the
27434 predefined arithmetic operators, meaning that there is never a
27435 conflict between the mathematical view of the assertion, and its
27436 run-time behavior.
27437
27438 Note that in this mode, the behavior is unaffected by whether or
27439 not overflow checks are suppressed, since overflow does not occur.
27440 It is possible for gigantic intermediate expressions to raise
27441 @code{Storage_Error} as a result of attempting to compute the
27442 results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
27443 but overflow is impossible.
27444
27445
27446 @end itemize
27447
27448 @noindent
27449 Note that these modes apply only to the evaluation of predefined
27450 arithmetic, membership, and comparison operators for signed integer
27451 aritmetic.
27452
27453 For fixed-point arithmetic, checks can be suppressed. But if checks
27454 are enabled
27455 then fixed-point values are always checked for overflow against the
27456 base type for intermediate expressions (that is such checks always
27457 operate in the equivalent of @code{STRICT} mode).
27458
27459 For floating-point, on nearly all architectures, @code{Machine_Overflows}
27460 is False, and IEEE infinities are generated, so overflow exceptions
27461 are never raised. If you want to avoid infinities, and check that
27462 final results of expressions are in range, then you can declare a
27463 constrained floating-point type, and range checks will be carried
27464 out in the normal manner (with infinite values always failing all
27465 range checks).
27466
27467
27468 @c -------------------------
27469 @node Specifying the Desired Mode
27470 @section Specifying the Desired Mode
27471
27472 @noindent
27473 The desired mode of for handling intermediate overflow can be specified using
27474 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
27475 The pragma has the form
27476 @cindex pragma @code{Overflow_Mode}
27477
27478 @smallexample @c ada
27479 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
27480 @end smallexample
27481
27482 @noindent
27483 where @code{MODE} is one of
27484
27485 @itemize @bullet
27486 @item @code{STRICT}: intermediate overflows checked (using base type)
27487 @item @code{MINIMIZED}: minimize intermediate overflows
27488 @item @code{ELIMINATED}: eliminate intermediate overflows
27489 @end itemize
27490
27491 @noindent
27492 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
27493 @code{minimized} all have the same effect.
27494
27495 If only the @code{General} parameter is present, then the given @code{MODE}
27496 applies
27497 to expressions both within and outside assertions. If both arguments
27498 are present, then @code{General} applies to expressions outside assertions,
27499 and @code{Assertions} applies to expressions within assertions. For example:
27500
27501 @smallexample @c ada
27502 pragma Overflow_Mode
27503 (General => Minimized, Assertions => Eliminated);
27504 @end smallexample
27505
27506 @noindent
27507 specifies that general expressions outside assertions be evaluated
27508 in ``minimize intermediate overflows'' mode, and expressions within
27509 assertions be evaluated in ``eliminate intermediate overflows'' mode.
27510 This is often a reasonable choice, avoiding excessive overhead
27511 outside assertions, but assuring a high degree of portability
27512 when importing code from another compiler, while incurring
27513 the extra overhead for assertion expressions to ensure that
27514 the behavior at run time matches the expected mathematical
27515 behavior.
27516
27517 The @code{Overflow_Mode} pragma has the same scoping and placement
27518 rules as pragma @code{Suppress}, so it can occur either as a
27519 configuration pragma, specifying a default for the whole
27520 program, or in a declarative scope, where it applies to the
27521 remaining declarations and statements in that scope.
27522
27523 Note that pragma @code{Overflow_Mode} does not affect whether
27524 overflow checks are enabled or suppressed. It only controls the
27525 method used to compute intermediate values. To control whether
27526 overflow checking is enabled or suppressed, use pragma @code{Suppress}
27527 or @code{Unsuppress} in the usual manner
27528
27529 Additionally, a compiler switch @option{-gnato?} or @option{-gnato??}
27530 can be used to control the checking mode default (which can be subsequently
27531 overridden using pragmas).
27532 @cindex @option{-gnato?} (gcc)
27533 @cindex @option{-gnato??} (gcc)
27534
27535 Here `@code{?}' is one of the digits `@code{1}' through `@code{3}':
27536
27537 @itemize @bullet
27538 @item @code{1}:
27539 use base type for intermediate operations (@code{STRICT})
27540 @item @code{2}:
27541 minimize intermediate overflows (@code{MINIMIZED})
27542 @item @code{3}:
27543 eliminate intermediate overflows (@code{ELIMINATED})
27544 @end itemize
27545
27546 @noindent
27547 As with the pragma, if only one digit appears then it applies to all
27548 cases; if two digits are given, then the first applies outside
27549 assertions, and the second within assertions. Thus the equivalent
27550 of the example pragma above would be
27551 @option{^-gnato23^/OVERFLOW_CHECKS=23^}.
27552
27553 If no digits follow the @option{-gnato}, then it is equivalent to
27554 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
27555 causing all intermediate operations to be computed using the base
27556 type (@code{STRICT} mode).
27557
27558 In addition to setting the mode used for computation of intermediate
27559 results, the @code{-gnato} switch also enables overflow checking (which
27560 is suppressed by default). It thus combines the effect of using
27561 a pragma @code{Overflow_Mode} and pragma @code{Unsuppress}.
27562
27563
27564 @c -------------------------
27565 @node Default Settings
27566 @section Default Settings
27567
27568 The default mode for overflow checks is
27569
27570 @smallexample
27571 General => Strict
27572 @end smallexample
27573
27574 @noindent
27575 which causes all computations both inside and outside assertions to use
27576 the base type. In addition overflow checks are suppressed.
27577
27578 This retains compatibility with previous versions of
27579 GNAT which suppressed overflow checks by default and always
27580 used the base type for computation of intermediate results.
27581
27582 The switch @option{-gnato} (with no digits following) is equivalent to
27583 @cindex @option{-gnato} (gcc)
27584
27585 @smallexample
27586 General => Strict
27587 @end smallexample
27588
27589 @noindent
27590 which causes overflow checking of all intermediate overflows
27591 both inside and outside assertions against the base type.
27592 This provides compatibility
27593 with this switch as implemented in previous versions of GNAT.
27594
27595 The pragma @code{Suppress (Overflow_Check)} disables overflow
27596 checking, but it has no effect on the method used for computing
27597 intermediate results.
27598
27599 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
27600 checking, but it has no effect on the method used for computing
27601 intermediate results.
27602
27603 @c -------------------------
27604 @node Implementation Notes
27605 @section Implementation Notes
27606
27607 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
27608 reasonably efficient, and can be generally used. It also helps
27609 to ensure compatibility with code imported from some other
27610 compiler to GNAT.
27611
27612 Setting all intermediate overflows checking (@code{CHECKED} mode)
27613 makes sense if you want to
27614 make sure that your code is compatible with any other possible
27615 Ada implementation. This may be useful in ensuring portability
27616 for code that is to be exported to some other compiler than GNAT.
27617
27618
27619 The Ada standard allows the reassociation of expressions at
27620 the same precedence level if no parentheses are present. For
27621 example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but
27622 the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly
27623 introducing or eliminating an overflow exception. The GNAT
27624 compiler never takes advantage of this freedom, and the
27625 expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}.
27626 If you need the other order, you can write the parentheses
27627 explicitly @w{@code{A+(B+C)}} and GNAT will respect this order.
27628
27629 The use of @code{ELIMINATED} mode will cause the compiler to
27630 automatically include an appropriate arbitrary precision
27631 integer arithmetic package. The compiler will make calls
27632 to this package, though only in cases where it cannot be
27633 sure that @code{Long_Long_Integer} is sufficient to guard against
27634 intermediate overflows. This package does not use dynamic
27635 alllocation, but it does use the secondary stack, so an
27636 appropriate secondary stack package must be present (this
27637 is always true for standard full Ada, but may require
27638 specific steps for restricted run times such as ZFP).
27639
27640 Although @code{ELIMINATED} mode causes expressions to use arbitrary
27641 precision arithmetic, avoiding overflow, the final result
27642 must be in an appropriate range. This is true even if the
27643 final result is of type @code{[Long_[Long_]]Integer'Base}, which
27644 still has the same bounds as its associated constrained
27645 type at run-time.
27646
27647 Currently, the @code{ELIMINATED} mode is only available on target
27648 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
27649 platforms).
27650
27651 @c *******************************
27652 @node Conditional Compilation
27653 @appendix Conditional Compilation
27654 @c *******************************
27655 @cindex Conditional compilation
27656
27657 @noindent
27658 It is often necessary to arrange for a single source program
27659 to serve multiple purposes, where it is compiled in different
27660 ways to achieve these different goals. Some examples of the
27661 need for this feature are
27662
27663 @itemize @bullet
27664 @item Adapting a program to a different hardware environment
27665 @item Adapting a program to a different target architecture
27666 @item Turning debugging features on and off
27667 @item Arranging for a program to compile with different compilers
27668 @end itemize
27669
27670 @noindent
27671 In C, or C++, the typical approach would be to use the preprocessor
27672 that is defined as part of the language. The Ada language does not
27673 contain such a feature. This is not an oversight, but rather a very
27674 deliberate design decision, based on the experience that overuse of
27675 the preprocessing features in C and C++ can result in programs that
27676 are extremely difficult to maintain. For example, if we have ten
27677 switches that can be on or off, this means that there are a thousand
27678 separate programs, any one of which might not even be syntactically
27679 correct, and even if syntactically correct, the resulting program
27680 might not work correctly. Testing all combinations can quickly become
27681 impossible.
27682
27683 Nevertheless, the need to tailor programs certainly exists, and in
27684 this Appendix we will discuss how this can
27685 be achieved using Ada in general, and GNAT in particular.
27686
27687 @menu
27688 * Use of Boolean Constants::
27689 * Debugging - A Special Case::
27690 * Conditionalizing Declarations::
27691 * Use of Alternative Implementations::
27692 * Preprocessing::
27693 @end menu
27694
27695 @node Use of Boolean Constants
27696 @section Use of Boolean Constants
27697
27698 @noindent
27699 In the case where the difference is simply which code
27700 sequence is executed, the cleanest solution is to use Boolean
27701 constants to control which code is executed.
27702
27703 @smallexample @c ada
27704 @group
27705 FP_Initialize_Required : constant Boolean := True;
27706 @dots{}
27707 if FP_Initialize_Required then
27708 @dots{}
27709 end if;
27710 @end group
27711 @end smallexample
27712
27713 @noindent
27714 Not only will the code inside the @code{if} statement not be executed if
27715 the constant Boolean is @code{False}, but it will also be completely
27716 deleted from the program.
27717 However, the code is only deleted after the @code{if} statement
27718 has been checked for syntactic and semantic correctness.
27719 (In contrast, with preprocessors the code is deleted before the
27720 compiler ever gets to see it, so it is not checked until the switch
27721 is turned on.)
27722 @cindex Preprocessors (contrasted with conditional compilation)
27723
27724 Typically the Boolean constants will be in a separate package,
27725 something like:
27726
27727 @smallexample @c ada
27728 @group
27729 package Config is
27730 FP_Initialize_Required : constant Boolean := True;
27731 Reset_Available : constant Boolean := False;
27732 @dots{}
27733 end Config;
27734 @end group
27735 @end smallexample
27736
27737 @noindent
27738 The @code{Config} package exists in multiple forms for the various targets,
27739 with an appropriate script selecting the version of @code{Config} needed.
27740 Then any other unit requiring conditional compilation can do a @code{with}
27741 of @code{Config} to make the constants visible.
27742
27743
27744 @node Debugging - A Special Case
27745 @section Debugging - A Special Case
27746
27747 @noindent
27748 A common use of conditional code is to execute statements (for example
27749 dynamic checks, or output of intermediate results) under control of a
27750 debug switch, so that the debugging behavior can be turned on and off.
27751 This can be done using a Boolean constant to control whether the code
27752 is active:
27753
27754 @smallexample @c ada
27755 @group
27756 if Debugging then
27757 Put_Line ("got to the first stage!");
27758 end if;
27759 @end group
27760 @end smallexample
27761
27762 @noindent
27763 or
27764
27765 @smallexample @c ada
27766 @group
27767 if Debugging and then Temperature > 999.0 then
27768 raise Temperature_Crazy;
27769 end if;
27770 @end group
27771 @end smallexample
27772
27773 @noindent
27774 Since this is a common case, there are special features to deal with
27775 this in a convenient manner. For the case of tests, Ada 2005 has added
27776 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
27777 @cindex pragma @code{Assert}
27778 on the @code{Assert} pragma that has always been available in GNAT, so this
27779 feature may be used with GNAT even if you are not using Ada 2005 features.
27780 The use of pragma @code{Assert} is described in
27781 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
27782 example, the last test could be written:
27783
27784 @smallexample @c ada
27785 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
27786 @end smallexample
27787
27788 @noindent
27789 or simply
27790
27791 @smallexample @c ada
27792 pragma Assert (Temperature <= 999.0);
27793 @end smallexample
27794
27795 @noindent
27796 In both cases, if assertions are active and the temperature is excessive,
27797 the exception @code{Assert_Failure} will be raised, with the given string in
27798 the first case or a string indicating the location of the pragma in the second
27799 case used as the exception message.
27800
27801 You can turn assertions on and off by using the @code{Assertion_Policy}
27802 pragma.
27803 @cindex pragma @code{Assertion_Policy}
27804 This is an Ada 2005 pragma which is implemented in all modes by
27805 GNAT, but only in the latest versions of GNAT which include Ada 2005
27806 capability. Alternatively, you can use the @option{-gnata} switch
27807 @cindex @option{-gnata} switch
27808 to enable assertions from the command line (this is recognized by all versions
27809 of GNAT).
27810
27811 For the example above with the @code{Put_Line}, the GNAT-specific pragma
27812 @code{Debug} can be used:
27813 @cindex pragma @code{Debug}
27814
27815 @smallexample @c ada
27816 pragma Debug (Put_Line ("got to the first stage!"));
27817 @end smallexample
27818
27819 @noindent
27820 If debug pragmas are enabled, the argument, which must be of the form of
27821 a procedure call, is executed (in this case, @code{Put_Line} will be called).
27822 Only one call can be present, but of course a special debugging procedure
27823 containing any code you like can be included in the program and then
27824 called in a pragma @code{Debug} argument as needed.
27825
27826 One advantage of pragma @code{Debug} over the @code{if Debugging then}
27827 construct is that pragma @code{Debug} can appear in declarative contexts,
27828 such as at the very beginning of a procedure, before local declarations have
27829 been elaborated.
27830
27831 Debug pragmas are enabled using either the @option{-gnata} switch that also
27832 controls assertions, or with a separate Debug_Policy pragma.
27833 @cindex pragma @code{Debug_Policy}
27834 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
27835 in Ada 95 and Ada 83 programs as well), and is analogous to
27836 pragma @code{Assertion_Policy} to control assertions.
27837
27838 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
27839 and thus they can appear in @file{gnat.adc} if you are not using a
27840 project file, or in the file designated to contain configuration pragmas
27841 in a project file.
27842 They then apply to all subsequent compilations. In practice the use of
27843 the @option{-gnata} switch is often the most convenient method of controlling
27844 the status of these pragmas.
27845
27846 Note that a pragma is not a statement, so in contexts where a statement
27847 sequence is required, you can't just write a pragma on its own. You have
27848 to add a @code{null} statement.
27849
27850 @smallexample @c ada
27851 @group
27852 if @dots{} then
27853 @dots{} -- some statements
27854 else
27855 pragma Assert (Num_Cases < 10);
27856 null;
27857 end if;
27858 @end group
27859 @end smallexample
27860
27861
27862 @node Conditionalizing Declarations
27863 @section Conditionalizing Declarations
27864
27865 @noindent
27866 In some cases, it may be necessary to conditionalize declarations to meet
27867 different requirements. For example we might want a bit string whose length
27868 is set to meet some hardware message requirement.
27869
27870 In some cases, it may be possible to do this using declare blocks controlled
27871 by conditional constants:
27872
27873 @smallexample @c ada
27874 @group
27875 if Small_Machine then
27876 declare
27877 X : Bit_String (1 .. 10);
27878 begin
27879 @dots{}
27880 end;
27881 else
27882 declare
27883 X : Large_Bit_String (1 .. 1000);
27884 begin
27885 @dots{}
27886 end;
27887 end if;
27888 @end group
27889 @end smallexample
27890
27891 @noindent
27892 Note that in this approach, both declarations are analyzed by the
27893 compiler so this can only be used where both declarations are legal,
27894 even though one of them will not be used.
27895
27896 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
27897 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
27898 that are parameterized by these constants. For example
27899
27900 @smallexample @c ada
27901 @group
27902 for Rec use
27903 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
27904 end record;
27905 @end group
27906 @end smallexample
27907
27908 @noindent
27909 If @code{Bits_Per_Word} is set to 32, this generates either
27910
27911 @smallexample @c ada
27912 @group
27913 for Rec use
27914 Field1 at 0 range 0 .. 32;
27915 end record;
27916 @end group
27917 @end smallexample
27918
27919 @noindent
27920 for the big endian case, or
27921
27922 @smallexample @c ada
27923 @group
27924 for Rec use record
27925 Field1 at 0 range 10 .. 32;
27926 end record;
27927 @end group
27928 @end smallexample
27929
27930 @noindent
27931 for the little endian case. Since a powerful subset of Ada expression
27932 notation is usable for creating static constants, clever use of this
27933 feature can often solve quite difficult problems in conditionalizing
27934 compilation (note incidentally that in Ada 95, the little endian
27935 constant was introduced as @code{System.Default_Bit_Order}, so you do not
27936 need to define this one yourself).
27937
27938
27939 @node Use of Alternative Implementations
27940 @section Use of Alternative Implementations
27941
27942 @noindent
27943 In some cases, none of the approaches described above are adequate. This
27944 can occur for example if the set of declarations required is radically
27945 different for two different configurations.
27946
27947 In this situation, the official Ada way of dealing with conditionalizing
27948 such code is to write separate units for the different cases. As long as
27949 this does not result in excessive duplication of code, this can be done
27950 without creating maintenance problems. The approach is to share common
27951 code as far as possible, and then isolate the code and declarations
27952 that are different. Subunits are often a convenient method for breaking
27953 out a piece of a unit that is to be conditionalized, with separate files
27954 for different versions of the subunit for different targets, where the
27955 build script selects the right one to give to the compiler.
27956 @cindex Subunits (and conditional compilation)
27957
27958 As an example, consider a situation where a new feature in Ada 2005
27959 allows something to be done in a really nice way. But your code must be able
27960 to compile with an Ada 95 compiler. Conceptually you want to say:
27961
27962 @smallexample @c ada
27963 @group
27964 if Ada_2005 then
27965 @dots{} neat Ada 2005 code
27966 else
27967 @dots{} not quite as neat Ada 95 code
27968 end if;
27969 @end group
27970 @end smallexample
27971
27972 @noindent
27973 where @code{Ada_2005} is a Boolean constant.
27974
27975 But this won't work when @code{Ada_2005} is set to @code{False},
27976 since the @code{then} clause will be illegal for an Ada 95 compiler.
27977 (Recall that although such unreachable code would eventually be deleted
27978 by the compiler, it still needs to be legal. If it uses features
27979 introduced in Ada 2005, it will be illegal in Ada 95.)
27980
27981 So instead we write
27982
27983 @smallexample @c ada
27984 procedure Insert is separate;
27985 @end smallexample
27986
27987 @noindent
27988 Then we have two files for the subunit @code{Insert}, with the two sets of
27989 code.
27990 If the package containing this is called @code{File_Queries}, then we might
27991 have two files
27992
27993 @itemize @bullet
27994 @item @file{file_queries-insert-2005.adb}
27995 @item @file{file_queries-insert-95.adb}
27996 @end itemize
27997
27998 @noindent
27999 and the build script renames the appropriate file to
28000
28001 @smallexample
28002 file_queries-insert.adb
28003 @end smallexample
28004
28005 @noindent
28006 and then carries out the compilation.
28007
28008 This can also be done with project files' naming schemes. For example:
28009
28010 @smallexample @c project
28011 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
28012 @end smallexample
28013
28014 @noindent
28015 Note also that with project files it is desirable to use a different extension
28016 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
28017 conflict may arise through another commonly used feature: to declare as part
28018 of the project a set of directories containing all the sources obeying the
28019 default naming scheme.
28020
28021 The use of alternative units is certainly feasible in all situations,
28022 and for example the Ada part of the GNAT run-time is conditionalized
28023 based on the target architecture using this approach. As a specific example,
28024 consider the implementation of the AST feature in VMS. There is one
28025 spec:
28026
28027 @smallexample
28028 s-asthan.ads
28029 @end smallexample
28030
28031 @noindent
28032 which is the same for all architectures, and three bodies:
28033
28034 @table @file
28035 @item s-asthan.adb
28036 used for all non-VMS operating systems
28037 @item s-asthan-vms-alpha.adb
28038 used for VMS on the Alpha
28039 @item s-asthan-vms-ia64.adb
28040 used for VMS on the ia64
28041 @end table
28042
28043 @noindent
28044 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
28045 this operating system feature is not available, and the two remaining
28046 versions interface with the corresponding versions of VMS to provide
28047 VMS-compatible AST handling. The GNAT build script knows the architecture
28048 and operating system, and automatically selects the right version,
28049 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
28050
28051 Another style for arranging alternative implementations is through Ada's
28052 access-to-subprogram facility.
28053 In case some functionality is to be conditionally included,
28054 you can declare an access-to-procedure variable @code{Ref} that is initialized
28055 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
28056 when appropriate.
28057 In some library package, set @code{Ref} to @code{Proc'Access} for some
28058 procedure @code{Proc} that performs the relevant processing.
28059 The initialization only occurs if the library package is included in the
28060 program.
28061 The same idea can also be implemented using tagged types and dispatching
28062 calls.
28063
28064
28065 @node Preprocessing
28066 @section Preprocessing
28067 @cindex Preprocessing
28068
28069 @noindent
28070 Although it is quite possible to conditionalize code without the use of
28071 C-style preprocessing, as described earlier in this section, it is
28072 nevertheless convenient in some cases to use the C approach. Moreover,
28073 older Ada compilers have often provided some preprocessing capability,
28074 so legacy code may depend on this approach, even though it is not
28075 standard.
28076
28077 To accommodate such use, GNAT provides a preprocessor (modeled to a large
28078 extent on the various preprocessors that have been used
28079 with legacy code on other compilers, to enable easier transition).
28080
28081 The preprocessor may be used in two separate modes. It can be used quite
28082 separately from the compiler, to generate a separate output source file
28083 that is then fed to the compiler as a separate step. This is the
28084 @code{gnatprep} utility, whose use is fully described in
28085 @ref{Preprocessing with gnatprep}.
28086 @cindex @code{gnatprep}
28087
28088 The preprocessing language allows such constructs as
28089
28090 @smallexample
28091 @group
28092 #if DEBUG or else (PRIORITY > 4) then
28093 bunch of declarations
28094 #else
28095 completely different bunch of declarations
28096 #end if;
28097 @end group
28098 @end smallexample
28099
28100 @noindent
28101 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
28102 defined either on the command line or in a separate file.
28103
28104 The other way of running the preprocessor is even closer to the C style and
28105 often more convenient. In this approach the preprocessing is integrated into
28106 the compilation process. The compiler is fed the preprocessor input which
28107 includes @code{#if} lines etc, and then the compiler carries out the
28108 preprocessing internally and processes the resulting output.
28109 For more details on this approach, see @ref{Integrated Preprocessing}.
28110
28111
28112 @c *******************************
28113 @node Inline Assembler
28114 @appendix Inline Assembler
28115 @c *******************************
28116
28117 @noindent
28118 If you need to write low-level software that interacts directly
28119 with the hardware, Ada provides two ways to incorporate assembly
28120 language code into your program. First, you can import and invoke
28121 external routines written in assembly language, an Ada feature fully
28122 supported by GNAT@. However, for small sections of code it may be simpler
28123 or more efficient to include assembly language statements directly
28124 in your Ada source program, using the facilities of the implementation-defined
28125 package @code{System.Machine_Code}, which incorporates the gcc
28126 Inline Assembler. The Inline Assembler approach offers a number of advantages,
28127 including the following:
28128
28129 @itemize @bullet
28130 @item No need to use non-Ada tools
28131 @item Consistent interface over different targets
28132 @item Automatic usage of the proper calling conventions
28133 @item Access to Ada constants and variables
28134 @item Definition of intrinsic routines
28135 @item Possibility of inlining a subprogram comprising assembler code
28136 @item Code optimizer can take Inline Assembler code into account
28137 @end itemize
28138
28139 This chapter presents a series of examples to show you how to use
28140 the Inline Assembler. Although it focuses on the Intel x86,
28141 the general approach applies also to other processors.
28142 It is assumed that you are familiar with Ada
28143 and with assembly language programming.
28144
28145 @menu
28146 * Basic Assembler Syntax::
28147 * A Simple Example of Inline Assembler::
28148 * Output Variables in Inline Assembler::
28149 * Input Variables in Inline Assembler::
28150 * Inlining Inline Assembler Code::
28151 * Other Asm Functionality::
28152 @end menu
28153
28154 @c ---------------------------------------------------------------------------
28155 @node Basic Assembler Syntax
28156 @section Basic Assembler Syntax
28157
28158 @noindent
28159 The assembler used by GNAT and gcc is based not on the Intel assembly
28160 language, but rather on a language that descends from the AT&T Unix
28161 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
28162 The following table summarizes the main features of @emph{as} syntax
28163 and points out the differences from the Intel conventions.
28164 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
28165 pre-processor) documentation for further information.
28166
28167 @table @asis
28168 @item Register names
28169 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
28170 @*
28171 Intel: No extra punctuation; for example @code{eax}
28172
28173 @item Immediate operand
28174 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
28175 @*
28176 Intel: No extra punctuation; for example @code{4}
28177
28178 @item Address
28179 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
28180 @*
28181 Intel: No extra punctuation; for example @code{loc}
28182
28183 @item Memory contents
28184 gcc / @emph{as}: No extra punctuation; for example @code{loc}
28185 @*
28186 Intel: Square brackets; for example @code{[loc]}
28187
28188 @item Register contents
28189 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
28190 @*
28191 Intel: Square brackets; for example @code{[eax]}
28192
28193 @item Hexadecimal numbers
28194 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
28195 @*
28196 Intel: Trailing ``h''; for example @code{A0h}
28197
28198 @item Operand size
28199 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
28200 a 16-bit word
28201 @*
28202 Intel: Implicit, deduced by assembler; for example @code{mov}
28203
28204 @item Instruction repetition
28205 gcc / @emph{as}: Split into two lines; for example
28206 @*
28207 @code{rep}
28208 @*
28209 @code{stosl}
28210 @*
28211 Intel: Keep on one line; for example @code{rep stosl}
28212
28213 @item Order of operands
28214 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
28215 @*
28216 Intel: Destination first; for example @code{mov eax, 4}
28217 @end table
28218
28219 @c ---------------------------------------------------------------------------
28220 @node A Simple Example of Inline Assembler
28221 @section A Simple Example of Inline Assembler
28222
28223 @noindent
28224 The following example will generate a single assembly language statement,
28225 @code{nop}, which does nothing. Despite its lack of run-time effect,
28226 the example will be useful in illustrating the basics of
28227 the Inline Assembler facility.
28228
28229 @smallexample @c ada
28230 @group
28231 with System.Machine_Code; use System.Machine_Code;
28232 procedure Nothing is
28233 begin
28234 Asm ("nop");
28235 end Nothing;
28236 @end group
28237 @end smallexample
28238
28239 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
28240 here it takes one parameter, a @emph{template string} that must be a static
28241 expression and that will form the generated instruction.
28242 @code{Asm} may be regarded as a compile-time procedure that parses
28243 the template string and additional parameters (none here),
28244 from which it generates a sequence of assembly language instructions.
28245
28246 The examples in this chapter will illustrate several of the forms
28247 for invoking @code{Asm}; a complete specification of the syntax
28248 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
28249 Manual}.
28250
28251 Under the standard GNAT conventions, the @code{Nothing} procedure
28252 should be in a file named @file{nothing.adb}.
28253 You can build the executable in the usual way:
28254 @smallexample
28255 gnatmake nothing
28256 @end smallexample
28257 However, the interesting aspect of this example is not its run-time behavior
28258 but rather the generated assembly code.
28259 To see this output, invoke the compiler as follows:
28260 @smallexample
28261 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
28262 @end smallexample
28263 where the options are:
28264
28265 @table @code
28266 @item -c
28267 compile only (no bind or link)
28268 @item -S
28269 generate assembler listing
28270 @item -fomit-frame-pointer
28271 do not set up separate stack frames
28272 @item -gnatp
28273 do not add runtime checks
28274 @end table
28275
28276 This gives a human-readable assembler version of the code. The resulting
28277 file will have the same name as the Ada source file, but with a @code{.s}
28278 extension. In our example, the file @file{nothing.s} has the following
28279 contents:
28280
28281 @smallexample
28282 @group
28283 .file "nothing.adb"
28284 gcc2_compiled.:
28285 ___gnu_compiled_ada:
28286 .text
28287 .align 4
28288 .globl __ada_nothing
28289 __ada_nothing:
28290 #APP
28291 nop
28292 #NO_APP
28293 jmp L1
28294 .align 2,0x90
28295 L1:
28296 ret
28297 @end group
28298 @end smallexample
28299
28300 The assembly code you included is clearly indicated by
28301 the compiler, between the @code{#APP} and @code{#NO_APP}
28302 delimiters. The character before the 'APP' and 'NOAPP'
28303 can differ on different targets. For example, GNU/Linux uses '#APP' while
28304 on NT you will see '/APP'.
28305
28306 If you make a mistake in your assembler code (such as using the
28307 wrong size modifier, or using a wrong operand for the instruction) GNAT
28308 will report this error in a temporary file, which will be deleted when
28309 the compilation is finished. Generating an assembler file will help
28310 in such cases, since you can assemble this file separately using the
28311 @emph{as} assembler that comes with gcc.
28312
28313 Assembling the file using the command
28314
28315 @smallexample
28316 as @file{nothing.s}
28317 @end smallexample
28318 @noindent
28319 will give you error messages whose lines correspond to the assembler
28320 input file, so you can easily find and correct any mistakes you made.
28321 If there are no errors, @emph{as} will generate an object file
28322 @file{nothing.out}.
28323
28324 @c ---------------------------------------------------------------------------
28325 @node Output Variables in Inline Assembler
28326 @section Output Variables in Inline Assembler
28327
28328 @noindent
28329 The examples in this section, showing how to access the processor flags,
28330 illustrate how to specify the destination operands for assembly language
28331 statements.
28332
28333 @smallexample @c ada
28334 @group
28335 with Interfaces; use Interfaces;
28336 with Ada.Text_IO; use Ada.Text_IO;
28337 with System.Machine_Code; use System.Machine_Code;
28338 procedure Get_Flags is
28339 Flags : Unsigned_32;
28340 use ASCII;
28341 begin
28342 Asm ("pushfl" & LF & HT & -- push flags on stack
28343 "popl %%eax" & LF & HT & -- load eax with flags
28344 "movl %%eax, %0", -- store flags in variable
28345 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28346 Put_Line ("Flags register:" & Flags'Img);
28347 end Get_Flags;
28348 @end group
28349 @end smallexample
28350
28351 In order to have a nicely aligned assembly listing, we have separated
28352 multiple assembler statements in the Asm template string with linefeed
28353 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
28354 The resulting section of the assembly output file is:
28355
28356 @smallexample
28357 @group
28358 #APP
28359 pushfl
28360 popl %eax
28361 movl %eax, -40(%ebp)
28362 #NO_APP
28363 @end group
28364 @end smallexample
28365
28366 It would have been legal to write the Asm invocation as:
28367
28368 @smallexample
28369 Asm ("pushfl popl %%eax movl %%eax, %0")
28370 @end smallexample
28371
28372 but in the generated assembler file, this would come out as:
28373
28374 @smallexample
28375 #APP
28376 pushfl popl %eax movl %eax, -40(%ebp)
28377 #NO_APP
28378 @end smallexample
28379
28380 which is not so convenient for the human reader.
28381
28382 We use Ada comments
28383 at the end of each line to explain what the assembler instructions
28384 actually do. This is a useful convention.
28385
28386 When writing Inline Assembler instructions, you need to precede each register
28387 and variable name with a percent sign. Since the assembler already requires
28388 a percent sign at the beginning of a register name, you need two consecutive
28389 percent signs for such names in the Asm template string, thus @code{%%eax}.
28390 In the generated assembly code, one of the percent signs will be stripped off.
28391
28392 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
28393 variables: operands you later define using @code{Input} or @code{Output}
28394 parameters to @code{Asm}.
28395 An output variable is illustrated in
28396 the third statement in the Asm template string:
28397 @smallexample
28398 movl %%eax, %0
28399 @end smallexample
28400 The intent is to store the contents of the eax register in a variable that can
28401 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
28402 necessarily work, since the compiler might optimize by using a register
28403 to hold Flags, and the expansion of the @code{movl} instruction would not be
28404 aware of this optimization. The solution is not to store the result directly
28405 but rather to advise the compiler to choose the correct operand form;
28406 that is the purpose of the @code{%0} output variable.
28407
28408 Information about the output variable is supplied in the @code{Outputs}
28409 parameter to @code{Asm}:
28410 @smallexample
28411 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28412 @end smallexample
28413
28414 The output is defined by the @code{Asm_Output} attribute of the target type;
28415 the general format is
28416 @smallexample
28417 Type'Asm_Output (constraint_string, variable_name)
28418 @end smallexample
28419
28420 The constraint string directs the compiler how
28421 to store/access the associated variable. In the example
28422 @smallexample
28423 Unsigned_32'Asm_Output ("=m", Flags);
28424 @end smallexample
28425 the @code{"m"} (memory) constraint tells the compiler that the variable
28426 @code{Flags} should be stored in a memory variable, thus preventing
28427 the optimizer from keeping it in a register. In contrast,
28428 @smallexample
28429 Unsigned_32'Asm_Output ("=r", Flags);
28430 @end smallexample
28431 uses the @code{"r"} (register) constraint, telling the compiler to
28432 store the variable in a register.
28433
28434 If the constraint is preceded by the equal character (@strong{=}), it tells
28435 the compiler that the variable will be used to store data into it.
28436
28437 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
28438 allowing the optimizer to choose whatever it deems best.
28439
28440 There are a fairly large number of constraints, but the ones that are
28441 most useful (for the Intel x86 processor) are the following:
28442
28443 @table @code
28444 @item =
28445 output constraint
28446 @item g
28447 global (i.e.@: can be stored anywhere)
28448 @item m
28449 in memory
28450 @item I
28451 a constant
28452 @item a
28453 use eax
28454 @item b
28455 use ebx
28456 @item c
28457 use ecx
28458 @item d
28459 use edx
28460 @item S
28461 use esi
28462 @item D
28463 use edi
28464 @item r
28465 use one of eax, ebx, ecx or edx
28466 @item q
28467 use one of eax, ebx, ecx, edx, esi or edi
28468 @end table
28469
28470 The full set of constraints is described in the gcc and @emph{as}
28471 documentation; note that it is possible to combine certain constraints
28472 in one constraint string.
28473
28474 You specify the association of an output variable with an assembler operand
28475 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
28476 integer. Thus in
28477 @smallexample @c ada
28478 @group
28479 Asm ("pushfl" & LF & HT & -- push flags on stack
28480 "popl %%eax" & LF & HT & -- load eax with flags
28481 "movl %%eax, %0", -- store flags in variable
28482 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28483 @end group
28484 @end smallexample
28485 @noindent
28486 @code{%0} will be replaced in the expanded code by the appropriate operand,
28487 whatever
28488 the compiler decided for the @code{Flags} variable.
28489
28490 In general, you may have any number of output variables:
28491 @itemize @bullet
28492 @item
28493 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
28494 @item
28495 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
28496 of @code{Asm_Output} attributes
28497 @end itemize
28498
28499 For example:
28500 @smallexample @c ada
28501 @group
28502 Asm ("movl %%eax, %0" & LF & HT &
28503 "movl %%ebx, %1" & LF & HT &
28504 "movl %%ecx, %2",
28505 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
28506 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
28507 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
28508 @end group
28509 @end smallexample
28510 @noindent
28511 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
28512 in the Ada program.
28513
28514 As a variation on the @code{Get_Flags} example, we can use the constraints
28515 string to direct the compiler to store the eax register into the @code{Flags}
28516 variable, instead of including the store instruction explicitly in the
28517 @code{Asm} template string:
28518
28519 @smallexample @c ada
28520 @group
28521 with Interfaces; use Interfaces;
28522 with Ada.Text_IO; use Ada.Text_IO;
28523 with System.Machine_Code; use System.Machine_Code;
28524 procedure Get_Flags_2 is
28525 Flags : Unsigned_32;
28526 use ASCII;
28527 begin
28528 Asm ("pushfl" & LF & HT & -- push flags on stack
28529 "popl %%eax", -- save flags in eax
28530 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
28531 Put_Line ("Flags register:" & Flags'Img);
28532 end Get_Flags_2;
28533 @end group
28534 @end smallexample
28535
28536 @noindent
28537 The @code{"a"} constraint tells the compiler that the @code{Flags}
28538 variable will come from the eax register. Here is the resulting code:
28539
28540 @smallexample
28541 @group
28542 #APP
28543 pushfl
28544 popl %eax
28545 #NO_APP
28546 movl %eax,-40(%ebp)
28547 @end group
28548 @end smallexample
28549
28550 @noindent
28551 The compiler generated the store of eax into Flags after
28552 expanding the assembler code.
28553
28554 Actually, there was no need to pop the flags into the eax register;
28555 more simply, we could just pop the flags directly into the program variable:
28556
28557 @smallexample @c ada
28558 @group
28559 with Interfaces; use Interfaces;
28560 with Ada.Text_IO; use Ada.Text_IO;
28561 with System.Machine_Code; use System.Machine_Code;
28562 procedure Get_Flags_3 is
28563 Flags : Unsigned_32;
28564 use ASCII;
28565 begin
28566 Asm ("pushfl" & LF & HT & -- push flags on stack
28567 "pop %0", -- save flags in Flags
28568 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28569 Put_Line ("Flags register:" & Flags'Img);
28570 end Get_Flags_3;
28571 @end group
28572 @end smallexample
28573
28574 @c ---------------------------------------------------------------------------
28575 @node Input Variables in Inline Assembler
28576 @section Input Variables in Inline Assembler
28577
28578 @noindent
28579 The example in this section illustrates how to specify the source operands
28580 for assembly language statements.
28581 The program simply increments its input value by 1:
28582
28583 @smallexample @c ada
28584 @group
28585 with Interfaces; use Interfaces;
28586 with Ada.Text_IO; use Ada.Text_IO;
28587 with System.Machine_Code; use System.Machine_Code;
28588 procedure Increment is
28589
28590 function Incr (Value : Unsigned_32) return Unsigned_32 is
28591 Result : Unsigned_32;
28592 begin
28593 Asm ("incl %0",
28594 Outputs => Unsigned_32'Asm_Output ("=a", Result),
28595 Inputs => Unsigned_32'Asm_Input ("a", Value));
28596 return Result;
28597 end Incr;
28598
28599 Value : Unsigned_32;
28600
28601 begin
28602 Value := 5;
28603 Put_Line ("Value before is" & Value'Img);
28604 Value := Incr (Value);
28605 Put_Line ("Value after is" & Value'Img);
28606 end Increment;
28607 @end group
28608 @end smallexample
28609
28610 The @code{Outputs} parameter to @code{Asm} specifies
28611 that the result will be in the eax register and that it is to be stored
28612 in the @code{Result} variable.
28613
28614 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
28615 but with an @code{Asm_Input} attribute.
28616 The @code{"="} constraint, indicating an output value, is not present.
28617
28618 You can have multiple input variables, in the same way that you can have more
28619 than one output variable.
28620
28621 The parameter count (%0, %1) etc, still starts at the first output statement,
28622 and continues with the input statements.
28623
28624 Just as the @code{Outputs} parameter causes the register to be stored into the
28625 target variable after execution of the assembler statements, so does the
28626 @code{Inputs} parameter cause its variable to be loaded into the register
28627 before execution of the assembler statements.
28628
28629 Thus the effect of the @code{Asm} invocation is:
28630 @enumerate
28631 @item load the 32-bit value of @code{Value} into eax
28632 @item execute the @code{incl %eax} instruction
28633 @item store the contents of eax into the @code{Result} variable
28634 @end enumerate
28635
28636 The resulting assembler file (with @option{-O2} optimization) contains:
28637 @smallexample
28638 @group
28639 _increment__incr.1:
28640 subl $4,%esp
28641 movl 8(%esp),%eax
28642 #APP
28643 incl %eax
28644 #NO_APP
28645 movl %eax,%edx
28646 movl %ecx,(%esp)
28647 addl $4,%esp
28648 ret
28649 @end group
28650 @end smallexample
28651
28652 @c ---------------------------------------------------------------------------
28653 @node Inlining Inline Assembler Code
28654 @section Inlining Inline Assembler Code
28655
28656 @noindent
28657 For a short subprogram such as the @code{Incr} function in the previous
28658 section, the overhead of the call and return (creating / deleting the stack
28659 frame) can be significant, compared to the amount of code in the subprogram
28660 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
28661 which directs the compiler to expand invocations of the subprogram at the
28662 point(s) of call, instead of setting up a stack frame for out-of-line calls.
28663 Here is the resulting program:
28664
28665 @smallexample @c ada
28666 @group
28667 with Interfaces; use Interfaces;
28668 with Ada.Text_IO; use Ada.Text_IO;
28669 with System.Machine_Code; use System.Machine_Code;
28670 procedure Increment_2 is
28671
28672 function Incr (Value : Unsigned_32) return Unsigned_32 is
28673 Result : Unsigned_32;
28674 begin
28675 Asm ("incl %0",
28676 Outputs => Unsigned_32'Asm_Output ("=a", Result),
28677 Inputs => Unsigned_32'Asm_Input ("a", Value));
28678 return Result;
28679 end Incr;
28680 pragma Inline (Increment);
28681
28682 Value : Unsigned_32;
28683
28684 begin
28685 Value := 5;
28686 Put_Line ("Value before is" & Value'Img);
28687 Value := Increment (Value);
28688 Put_Line ("Value after is" & Value'Img);
28689 end Increment_2;
28690 @end group
28691 @end smallexample
28692
28693 Compile the program with both optimization (@option{-O2}) and inlining
28694 (@option{-gnatn}) enabled.
28695
28696 The @code{Incr} function is still compiled as usual, but at the
28697 point in @code{Increment} where our function used to be called:
28698
28699 @smallexample
28700 @group
28701 pushl %edi
28702 call _increment__incr.1
28703 @end group
28704 @end smallexample
28705
28706 @noindent
28707 the code for the function body directly appears:
28708
28709 @smallexample
28710 @group
28711 movl %esi,%eax
28712 #APP
28713 incl %eax
28714 #NO_APP
28715 movl %eax,%edx
28716 @end group
28717 @end smallexample
28718
28719 @noindent
28720 thus saving the overhead of stack frame setup and an out-of-line call.
28721
28722 @c ---------------------------------------------------------------------------
28723 @node Other Asm Functionality
28724 @section Other @code{Asm} Functionality
28725
28726 @noindent
28727 This section describes two important parameters to the @code{Asm}
28728 procedure: @code{Clobber}, which identifies register usage;
28729 and @code{Volatile}, which inhibits unwanted optimizations.
28730
28731 @menu
28732 * The Clobber Parameter::
28733 * The Volatile Parameter::
28734 @end menu
28735
28736 @c ---------------------------------------------------------------------------
28737 @node The Clobber Parameter
28738 @subsection The @code{Clobber} Parameter
28739
28740 @noindent
28741 One of the dangers of intermixing assembly language and a compiled language
28742 such as Ada is that the compiler needs to be aware of which registers are
28743 being used by the assembly code. In some cases, such as the earlier examples,
28744 the constraint string is sufficient to indicate register usage (e.g.,
28745 @code{"a"} for
28746 the eax register). But more generally, the compiler needs an explicit
28747 identification of the registers that are used by the Inline Assembly
28748 statements.
28749
28750 Using a register that the compiler doesn't know about
28751 could be a side effect of an instruction (like @code{mull}
28752 storing its result in both eax and edx).
28753 It can also arise from explicit register usage in your
28754 assembly code; for example:
28755 @smallexample
28756 @group
28757 Asm ("movl %0, %%ebx" & LF & HT &
28758 "movl %%ebx, %1",
28759 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28760 Inputs => Unsigned_32'Asm_Input ("g", Var_In));
28761 @end group
28762 @end smallexample
28763 @noindent
28764 where the compiler (since it does not analyze the @code{Asm} template string)
28765 does not know you are using the ebx register.
28766
28767 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
28768 to identify the registers that will be used by your assembly code:
28769
28770 @smallexample
28771 @group
28772 Asm ("movl %0, %%ebx" & LF & HT &
28773 "movl %%ebx, %1",
28774 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28775 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28776 Clobber => "ebx");
28777 @end group
28778 @end smallexample
28779
28780 The Clobber parameter is a static string expression specifying the
28781 register(s) you are using. Note that register names are @emph{not} prefixed
28782 by a percent sign. Also, if more than one register is used then their names
28783 are separated by commas; e.g., @code{"eax, ebx"}
28784
28785 The @code{Clobber} parameter has several additional uses:
28786 @enumerate
28787 @item Use ``register'' name @code{cc} to indicate that flags might have changed
28788 @item Use ``register'' name @code{memory} if you changed a memory location
28789 @end enumerate
28790
28791 @c ---------------------------------------------------------------------------
28792 @node The Volatile Parameter
28793 @subsection The @code{Volatile} Parameter
28794 @cindex Volatile parameter
28795
28796 @noindent
28797 Compiler optimizations in the presence of Inline Assembler may sometimes have
28798 unwanted effects. For example, when an @code{Asm} invocation with an input
28799 variable is inside a loop, the compiler might move the loading of the input
28800 variable outside the loop, regarding it as a one-time initialization.
28801
28802 If this effect is not desired, you can disable such optimizations by setting
28803 the @code{Volatile} parameter to @code{True}; for example:
28804
28805 @smallexample @c ada
28806 @group
28807 Asm ("movl %0, %%ebx" & LF & HT &
28808 "movl %%ebx, %1",
28809 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28810 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28811 Clobber => "ebx",
28812 Volatile => True);
28813 @end group
28814 @end smallexample
28815
28816 By default, @code{Volatile} is set to @code{False} unless there is no
28817 @code{Outputs} parameter.
28818
28819 Although setting @code{Volatile} to @code{True} prevents unwanted
28820 optimizations, it will also disable other optimizations that might be
28821 important for efficiency. In general, you should set @code{Volatile}
28822 to @code{True} only if the compiler's optimizations have created
28823 problems.
28824 @c END OF INLINE ASSEMBLER CHAPTER
28825 @c ===============================
28826
28827 @c ***********************************
28828 @c * Compatibility and Porting Guide *
28829 @c ***********************************
28830 @node Compatibility and Porting Guide
28831 @appendix Compatibility and Porting Guide
28832
28833 @noindent
28834 This chapter describes the compatibility issues that may arise between
28835 GNAT and other Ada compilation systems (including those for Ada 83),
28836 and shows how GNAT can expedite porting
28837 applications developed in other Ada environments.
28838
28839 @menu
28840 * Compatibility with Ada 83::
28841 * Compatibility between Ada 95 and Ada 2005::
28842 * Implementation-dependent characteristics::
28843 * Compatibility with Other Ada Systems::
28844 * Representation Clauses::
28845 @ifclear vms
28846 @c Brief section is only in non-VMS version
28847 @c Full chapter is in VMS version
28848 * Compatibility with HP Ada 83::
28849 @end ifclear
28850 @ifset vms
28851 * Transitioning to 64-Bit GNAT for OpenVMS::
28852 @end ifset
28853 @end menu
28854
28855 @node Compatibility with Ada 83
28856 @section Compatibility with Ada 83
28857 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
28858
28859 @noindent
28860 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
28861 particular, the design intention was that the difficulties associated
28862 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
28863 that occur when moving from one Ada 83 system to another.
28864
28865 However, there are a number of points at which there are minor
28866 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
28867 full details of these issues,
28868 and should be consulted for a complete treatment.
28869 In practice the
28870 following subsections treat the most likely issues to be encountered.
28871
28872 @menu
28873 * Legal Ada 83 programs that are illegal in Ada 95::
28874 * More deterministic semantics::
28875 * Changed semantics::
28876 * Other language compatibility issues::
28877 @end menu
28878
28879 @node Legal Ada 83 programs that are illegal in Ada 95
28880 @subsection Legal Ada 83 programs that are illegal in Ada 95
28881
28882 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
28883 Ada 95 and thus also in Ada 2005:
28884
28885 @table @emph
28886 @item Character literals
28887 Some uses of character literals are ambiguous. Since Ada 95 has introduced
28888 @code{Wide_Character} as a new predefined character type, some uses of
28889 character literals that were legal in Ada 83 are illegal in Ada 95.
28890 For example:
28891 @smallexample @c ada
28892 for Char in 'A' .. 'Z' loop @dots{} end loop;
28893 @end smallexample
28894
28895 @noindent
28896 The problem is that @code{'A'} and @code{'Z'} could be from either
28897 @code{Character} or @code{Wide_Character}. The simplest correction
28898 is to make the type explicit; e.g.:
28899 @smallexample @c ada
28900 for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
28901 @end smallexample
28902
28903 @item New reserved words
28904 The identifiers @code{abstract}, @code{aliased}, @code{protected},
28905 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
28906 Existing Ada 83 code using any of these identifiers must be edited to
28907 use some alternative name.
28908
28909 @item Freezing rules
28910 The rules in Ada 95 are slightly different with regard to the point at
28911 which entities are frozen, and representation pragmas and clauses are
28912 not permitted past the freeze point. This shows up most typically in
28913 the form of an error message complaining that a representation item
28914 appears too late, and the appropriate corrective action is to move
28915 the item nearer to the declaration of the entity to which it refers.
28916
28917 A particular case is that representation pragmas
28918 @ifset vms
28919 (including the
28920 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
28921 @end ifset
28922 cannot be applied to a subprogram body. If necessary, a separate subprogram
28923 declaration must be introduced to which the pragma can be applied.
28924
28925 @item Optional bodies for library packages
28926 In Ada 83, a package that did not require a package body was nevertheless
28927 allowed to have one. This lead to certain surprises in compiling large
28928 systems (situations in which the body could be unexpectedly ignored by the
28929 binder). In Ada 95, if a package does not require a body then it is not
28930 permitted to have a body. To fix this problem, simply remove a redundant
28931 body if it is empty, or, if it is non-empty, introduce a dummy declaration
28932 into the spec that makes the body required. One approach is to add a private
28933 part to the package declaration (if necessary), and define a parameterless
28934 procedure called @code{Requires_Body}, which must then be given a dummy
28935 procedure body in the package body, which then becomes required.
28936 Another approach (assuming that this does not introduce elaboration
28937 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
28938 since one effect of this pragma is to require the presence of a package body.
28939
28940 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
28941 In Ada 95, the exception @code{Numeric_Error} is a renaming of
28942 @code{Constraint_Error}.
28943 This means that it is illegal to have separate exception handlers for
28944 the two exceptions. The fix is simply to remove the handler for the
28945 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
28946 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
28947
28948 @item Indefinite subtypes in generics
28949 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
28950 as the actual for a generic formal private type, but then the instantiation
28951 would be illegal if there were any instances of declarations of variables
28952 of this type in the generic body. In Ada 95, to avoid this clear violation
28953 of the methodological principle known as the ``contract model'',
28954 the generic declaration explicitly indicates whether
28955 or not such instantiations are permitted. If a generic formal parameter
28956 has explicit unknown discriminants, indicated by using @code{(<>)} after the
28957 subtype name, then it can be instantiated with indefinite types, but no
28958 stand-alone variables can be declared of this type. Any attempt to declare
28959 such a variable will result in an illegality at the time the generic is
28960 declared. If the @code{(<>)} notation is not used, then it is illegal
28961 to instantiate the generic with an indefinite type.
28962 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
28963 It will show up as a compile time error, and
28964 the fix is usually simply to add the @code{(<>)} to the generic declaration.
28965 @end table
28966
28967 @node More deterministic semantics
28968 @subsection More deterministic semantics
28969
28970 @table @emph
28971 @item Conversions
28972 Conversions from real types to integer types round away from 0. In Ada 83
28973 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
28974 implementation freedom was intended to support unbiased rounding in
28975 statistical applications, but in practice it interfered with portability.
28976 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
28977 is required. Numeric code may be affected by this change in semantics.
28978 Note, though, that this issue is no worse than already existed in Ada 83
28979 when porting code from one vendor to another.
28980
28981 @item Tasking
28982 The Real-Time Annex introduces a set of policies that define the behavior of
28983 features that were implementation dependent in Ada 83, such as the order in
28984 which open select branches are executed.
28985 @end table
28986
28987 @node Changed semantics
28988 @subsection Changed semantics
28989
28990 @noindent
28991 The worst kind of incompatibility is one where a program that is legal in
28992 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
28993 possible in Ada 83. Fortunately this is extremely rare, but the one
28994 situation that you should be alert to is the change in the predefined type
28995 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
28996
28997 @table @emph
28998 @item Range of type @code{Character}
28999 The range of @code{Standard.Character} is now the full 256 characters
29000 of Latin-1, whereas in most Ada 83 implementations it was restricted
29001 to 128 characters. Although some of the effects of
29002 this change will be manifest in compile-time rejection of legal
29003 Ada 83 programs it is possible for a working Ada 83 program to have
29004 a different effect in Ada 95, one that was not permitted in Ada 83.
29005 As an example, the expression
29006 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
29007 delivers @code{255} as its value.
29008 In general, you should look at the logic of any
29009 character-processing Ada 83 program and see whether it needs to be adapted
29010 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
29011 character handling package that may be relevant if code needs to be adapted
29012 to account for the additional Latin-1 elements.
29013 The desirable fix is to
29014 modify the program to accommodate the full character set, but in some cases
29015 it may be convenient to define a subtype or derived type of Character that
29016 covers only the restricted range.
29017 @cindex Latin-1
29018 @end table
29019
29020 @node Other language compatibility issues
29021 @subsection Other language compatibility issues
29022
29023 @table @emph
29024 @item @option{-gnat83} switch
29025 All implementations of GNAT provide a switch that causes GNAT to operate
29026 in Ada 83 mode. In this mode, some but not all compatibility problems
29027 of the type described above are handled automatically. For example, the
29028 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
29029 as identifiers as in Ada 83.
29030 However,
29031 in practice, it is usually advisable to make the necessary modifications
29032 to the program to remove the need for using this switch.
29033 See @ref{Compiling Different Versions of Ada}.
29034
29035 @item Support for removed Ada 83 pragmas and attributes
29036 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
29037 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
29038 compilers are allowed, but not required, to implement these missing
29039 elements. In contrast with some other compilers, GNAT implements all
29040 such pragmas and attributes, eliminating this compatibility concern. These
29041 include @code{pragma Interface} and the floating point type attributes
29042 (@code{Emax}, @code{Mantissa}, etc.), among other items.
29043 @end table
29044
29045
29046 @node Compatibility between Ada 95 and Ada 2005
29047 @section Compatibility between Ada 95 and Ada 2005
29048 @cindex Compatibility between Ada 95 and Ada 2005
29049
29050 @noindent
29051 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
29052 a number of incompatibilities. Several are enumerated below;
29053 for a complete description please see the
29054 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
29055 @cite{Rationale for Ada 2005}.
29056
29057 @table @emph
29058 @item New reserved words.
29059 The words @code{interface}, @code{overriding} and @code{synchronized} are
29060 reserved in Ada 2005.
29061 A pre-Ada 2005 program that uses any of these as an identifier will be
29062 illegal.
29063
29064 @item New declarations in predefined packages.
29065 A number of packages in the predefined environment contain new declarations:
29066 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
29067 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
29068 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
29069 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
29070 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
29071 If an Ada 95 program does a @code{with} and @code{use} of any of these
29072 packages, the new declarations may cause name clashes.
29073
29074 @item Access parameters.
29075 A nondispatching subprogram with an access parameter cannot be renamed
29076 as a dispatching operation. This was permitted in Ada 95.
29077
29078 @item Access types, discriminants, and constraints.
29079 Rule changes in this area have led to some incompatibilities; for example,
29080 constrained subtypes of some access types are not permitted in Ada 2005.
29081
29082 @item Aggregates for limited types.
29083 The allowance of aggregates for limited types in Ada 2005 raises the
29084 possibility of ambiguities in legal Ada 95 programs, since additional types
29085 now need to be considered in expression resolution.
29086
29087 @item Fixed-point multiplication and division.
29088 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
29089 were legal in Ada 95 and invoked the predefined versions of these operations,
29090 are now ambiguous.
29091 The ambiguity may be resolved either by applying a type conversion to the
29092 expression, or by explicitly invoking the operation from package
29093 @code{Standard}.
29094
29095 @item Return-by-reference types.
29096 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
29097 can declare a function returning a value from an anonymous access type.
29098 @end table
29099
29100
29101 @node Implementation-dependent characteristics
29102 @section Implementation-dependent characteristics
29103 @noindent
29104 Although the Ada language defines the semantics of each construct as
29105 precisely as practical, in some situations (for example for reasons of
29106 efficiency, or where the effect is heavily dependent on the host or target
29107 platform) the implementation is allowed some freedom. In porting Ada 83
29108 code to GNAT, you need to be aware of whether / how the existing code
29109 exercised such implementation dependencies. Such characteristics fall into
29110 several categories, and GNAT offers specific support in assisting the
29111 transition from certain Ada 83 compilers.
29112
29113 @menu
29114 * Implementation-defined pragmas::
29115 * Implementation-defined attributes::
29116 * Libraries::
29117 * Elaboration order::
29118 * Target-specific aspects::
29119 @end menu
29120
29121 @node Implementation-defined pragmas
29122 @subsection Implementation-defined pragmas
29123
29124 @noindent
29125 Ada compilers are allowed to supplement the language-defined pragmas, and
29126 these are a potential source of non-portability. All GNAT-defined pragmas
29127 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
29128 Reference Manual}, and these include several that are specifically
29129 intended to correspond to other vendors' Ada 83 pragmas.
29130 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
29131 For compatibility with HP Ada 83, GNAT supplies the pragmas
29132 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
29133 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
29134 and @code{Volatile}.
29135 Other relevant pragmas include @code{External} and @code{Link_With}.
29136 Some vendor-specific
29137 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
29138 recognized, thus
29139 avoiding compiler rejection of units that contain such pragmas; they are not
29140 relevant in a GNAT context and hence are not otherwise implemented.
29141
29142 @node Implementation-defined attributes
29143 @subsection Implementation-defined attributes
29144
29145 Analogous to pragmas, the set of attributes may be extended by an
29146 implementation. All GNAT-defined attributes are described in
29147 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
29148 Manual}, and these include several that are specifically intended
29149 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
29150 the attribute @code{VADS_Size} may be useful. For compatibility with HP
29151 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
29152 @code{Type_Class}.
29153
29154 @node Libraries
29155 @subsection Libraries
29156 @noindent
29157 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
29158 code uses vendor-specific libraries then there are several ways to manage
29159 this in Ada 95 or Ada 2005:
29160 @enumerate
29161 @item
29162 If the source code for the libraries (specs and bodies) are
29163 available, then the libraries can be migrated in the same way as the
29164 application.
29165 @item
29166 If the source code for the specs but not the bodies are
29167 available, then you can reimplement the bodies.
29168 @item
29169 Some features introduced by Ada 95 obviate the need for library support. For
29170 example most Ada 83 vendors supplied a package for unsigned integers. The
29171 Ada 95 modular type feature is the preferred way to handle this need, so
29172 instead of migrating or reimplementing the unsigned integer package it may
29173 be preferable to retrofit the application using modular types.
29174 @end enumerate
29175
29176 @node Elaboration order
29177 @subsection Elaboration order
29178 @noindent
29179 The implementation can choose any elaboration order consistent with the unit
29180 dependency relationship. This freedom means that some orders can result in
29181 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
29182 to invoke a subprogram its body has been elaborated, or to instantiate a
29183 generic before the generic body has been elaborated. By default GNAT
29184 attempts to choose a safe order (one that will not encounter access before
29185 elaboration problems) by implicitly inserting @code{Elaborate} or
29186 @code{Elaborate_All} pragmas where
29187 needed. However, this can lead to the creation of elaboration circularities
29188 and a resulting rejection of the program by gnatbind. This issue is
29189 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
29190 In brief, there are several
29191 ways to deal with this situation:
29192
29193 @itemize @bullet
29194 @item
29195 Modify the program to eliminate the circularities, e.g.@: by moving
29196 elaboration-time code into explicitly-invoked procedures
29197 @item
29198 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
29199 @code{Elaborate} pragmas, and then inhibit the generation of implicit
29200 @code{Elaborate_All}
29201 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
29202 (by selectively suppressing elaboration checks via pragma
29203 @code{Suppress(Elaboration_Check)} when it is safe to do so).
29204 @end itemize
29205
29206 @node Target-specific aspects
29207 @subsection Target-specific aspects
29208 @noindent
29209 Low-level applications need to deal with machine addresses, data
29210 representations, interfacing with assembler code, and similar issues. If
29211 such an Ada 83 application is being ported to different target hardware (for
29212 example where the byte endianness has changed) then you will need to
29213 carefully examine the program logic; the porting effort will heavily depend
29214 on the robustness of the original design. Moreover, Ada 95 (and thus
29215 Ada 2005) are sometimes
29216 incompatible with typical Ada 83 compiler practices regarding implicit
29217 packing, the meaning of the Size attribute, and the size of access values.
29218 GNAT's approach to these issues is described in @ref{Representation Clauses}.
29219
29220 @node Compatibility with Other Ada Systems
29221 @section Compatibility with Other Ada Systems
29222
29223 @noindent
29224 If programs avoid the use of implementation dependent and
29225 implementation defined features, as documented in the @cite{Ada
29226 Reference Manual}, there should be a high degree of portability between
29227 GNAT and other Ada systems. The following are specific items which
29228 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
29229 compilers, but do not affect porting code to GNAT@.
29230 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
29231 the following issues may or may not arise for Ada 2005 programs
29232 when other compilers appear.)
29233
29234 @table @emph
29235 @item Ada 83 Pragmas and Attributes
29236 Ada 95 compilers are allowed, but not required, to implement the missing
29237 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
29238 GNAT implements all such pragmas and attributes, eliminating this as
29239 a compatibility concern, but some other Ada 95 compilers reject these
29240 pragmas and attributes.
29241
29242 @item Specialized Needs Annexes
29243 GNAT implements the full set of special needs annexes. At the
29244 current time, it is the only Ada 95 compiler to do so. This means that
29245 programs making use of these features may not be portable to other Ada
29246 95 compilation systems.
29247
29248 @item Representation Clauses
29249 Some other Ada 95 compilers implement only the minimal set of
29250 representation clauses required by the Ada 95 reference manual. GNAT goes
29251 far beyond this minimal set, as described in the next section.
29252 @end table
29253
29254 @node Representation Clauses
29255 @section Representation Clauses
29256
29257 @noindent
29258 The Ada 83 reference manual was quite vague in describing both the minimal
29259 required implementation of representation clauses, and also their precise
29260 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
29261 minimal set of capabilities required is still quite limited.
29262
29263 GNAT implements the full required set of capabilities in
29264 Ada 95 and Ada 2005, but also goes much further, and in particular
29265 an effort has been made to be compatible with existing Ada 83 usage to the
29266 greatest extent possible.
29267
29268 A few cases exist in which Ada 83 compiler behavior is incompatible with
29269 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
29270 intentional or accidental dependence on specific implementation dependent
29271 characteristics of these Ada 83 compilers. The following is a list of
29272 the cases most likely to arise in existing Ada 83 code.
29273
29274 @table @emph
29275 @item Implicit Packing
29276 Some Ada 83 compilers allowed a Size specification to cause implicit
29277 packing of an array or record. This could cause expensive implicit
29278 conversions for change of representation in the presence of derived
29279 types, and the Ada design intends to avoid this possibility.
29280 Subsequent AI's were issued to make it clear that such implicit
29281 change of representation in response to a Size clause is inadvisable,
29282 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
29283 Reference Manuals as implementation advice that is followed by GNAT@.
29284 The problem will show up as an error
29285 message rejecting the size clause. The fix is simply to provide
29286 the explicit pragma @code{Pack}, or for more fine tuned control, provide
29287 a Component_Size clause.
29288
29289 @item Meaning of Size Attribute
29290 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
29291 the minimal number of bits required to hold values of the type. For example,
29292 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
29293 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
29294 some 32 in this situation. This problem will usually show up as a compile
29295 time error, but not always. It is a good idea to check all uses of the
29296 'Size attribute when porting Ada 83 code. The GNAT specific attribute
29297 Object_Size can provide a useful way of duplicating the behavior of
29298 some Ada 83 compiler systems.
29299
29300 @item Size of Access Types
29301 A common assumption in Ada 83 code is that an access type is in fact a pointer,
29302 and that therefore it will be the same size as a System.Address value. This
29303 assumption is true for GNAT in most cases with one exception. For the case of
29304 a pointer to an unconstrained array type (where the bounds may vary from one
29305 value of the access type to another), the default is to use a ``fat pointer'',
29306 which is represented as two separate pointers, one to the bounds, and one to
29307 the array. This representation has a number of advantages, including improved
29308 efficiency. However, it may cause some difficulties in porting existing Ada 83
29309 code which makes the assumption that, for example, pointers fit in 32 bits on
29310 a machine with 32-bit addressing.
29311
29312 To get around this problem, GNAT also permits the use of ``thin pointers'' for
29313 access types in this case (where the designated type is an unconstrained array
29314 type). These thin pointers are indeed the same size as a System.Address value.
29315 To specify a thin pointer, use a size clause for the type, for example:
29316
29317 @smallexample @c ada
29318 type X is access all String;
29319 for X'Size use Standard'Address_Size;
29320 @end smallexample
29321
29322 @noindent
29323 which will cause the type X to be represented using a single pointer.
29324 When using this representation, the bounds are right behind the array.
29325 This representation is slightly less efficient, and does not allow quite
29326 such flexibility in the use of foreign pointers or in using the
29327 Unrestricted_Access attribute to create pointers to non-aliased objects.
29328 But for any standard portable use of the access type it will work in
29329 a functionally correct manner and allow porting of existing code.
29330 Note that another way of forcing a thin pointer representation
29331 is to use a component size clause for the element size in an array,
29332 or a record representation clause for an access field in a record.
29333
29334 See the documentation of Unrestricted_Access in the GNAT RM for a
29335 full discussion of possible problems using this attribute in conjunction
29336 with thin pointers.
29337 @end table
29338
29339 @ifclear vms
29340 @c This brief section is only in the non-VMS version
29341 @c The complete chapter on HP Ada is in the VMS version
29342 @node Compatibility with HP Ada 83
29343 @section Compatibility with HP Ada 83
29344
29345 @noindent
29346 The VMS version of GNAT fully implements all the pragmas and attributes
29347 provided by HP Ada 83, as well as providing the standard HP Ada 83
29348 libraries, including Starlet. In addition, data layouts and parameter
29349 passing conventions are highly compatible. This means that porting
29350 existing HP Ada 83 code to GNAT in VMS systems should be easier than
29351 most other porting efforts. The following are some of the most
29352 significant differences between GNAT and HP Ada 83.
29353
29354 @table @emph
29355 @item Default floating-point representation
29356 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
29357 it is VMS format. GNAT does implement the necessary pragmas
29358 (Long_Float, Float_Representation) for changing this default.
29359
29360 @item System
29361 The package System in GNAT exactly corresponds to the definition in the
29362 Ada 95 reference manual, which means that it excludes many of the
29363 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
29364 that contains the additional definitions, and a special pragma,
29365 Extend_System allows this package to be treated transparently as an
29366 extension of package System.
29367
29368 @item To_Address
29369 The definitions provided by Aux_DEC are exactly compatible with those
29370 in the HP Ada 83 version of System, with one exception.
29371 HP Ada provides the following declarations:
29372
29373 @smallexample @c ada
29374 TO_ADDRESS (INTEGER)
29375 TO_ADDRESS (UNSIGNED_LONGWORD)
29376 TO_ADDRESS (@i{universal_integer})
29377 @end smallexample
29378
29379 @noindent
29380 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
29381 an extension to Ada 83 not strictly compatible with the reference manual.
29382 In GNAT, we are constrained to be exactly compatible with the standard,
29383 and this means we cannot provide this capability. In HP Ada 83, the
29384 point of this definition is to deal with a call like:
29385
29386 @smallexample @c ada
29387 TO_ADDRESS (16#12777#);
29388 @end smallexample
29389
29390 @noindent
29391 Normally, according to the Ada 83 standard, one would expect this to be
29392 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
29393 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
29394 definition using @i{universal_integer} takes precedence.
29395
29396 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
29397 is not possible to be 100% compatible. Since there are many programs using
29398 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
29399 to change the name of the function in the UNSIGNED_LONGWORD case, so the
29400 declarations provided in the GNAT version of AUX_Dec are:
29401
29402 @smallexample @c ada
29403 function To_Address (X : Integer) return Address;
29404 pragma Pure_Function (To_Address);
29405
29406 function To_Address_Long (X : Unsigned_Longword)
29407 return Address;
29408 pragma Pure_Function (To_Address_Long);
29409 @end smallexample
29410
29411 @noindent
29412 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
29413 change the name to TO_ADDRESS_LONG@.
29414
29415 @item Task_Id values
29416 The Task_Id values assigned will be different in the two systems, and GNAT
29417 does not provide a specified value for the Task_Id of the environment task,
29418 which in GNAT is treated like any other declared task.
29419 @end table
29420
29421 @noindent
29422 For full details on these and other less significant compatibility issues,
29423 see appendix E of the HP publication entitled @cite{HP Ada, Technical
29424 Overview and Comparison on HP Platforms}.
29425
29426 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
29427 attributes are recognized, although only a subset of them can sensibly
29428 be implemented. The description of pragmas in @ref{Implementation
29429 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
29430 indicates whether or not they are applicable to non-VMS systems.
29431 @end ifclear
29432
29433 @ifset vms
29434 @node Transitioning to 64-Bit GNAT for OpenVMS
29435 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
29436
29437 @noindent
29438 This section is meant to assist users of pre-2006 @value{EDITION}
29439 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
29440 the version of the GNAT technology supplied in 2006 and later for
29441 OpenVMS on both Alpha and I64.
29442
29443 @menu
29444 * Introduction to transitioning::
29445 * Migration of 32 bit code::
29446 * Taking advantage of 64 bit addressing::
29447 * Technical details::
29448 @end menu
29449
29450 @node Introduction to transitioning
29451 @subsection Introduction
29452
29453 @noindent
29454 64-bit @value{EDITION} for Open VMS has been designed to meet
29455 three main goals:
29456
29457 @enumerate
29458 @item
29459 Providing a full conforming implementation of Ada 95 and Ada 2005
29460
29461 @item
29462 Allowing maximum backward compatibility, thus easing migration of existing
29463 Ada source code
29464
29465 @item
29466 Supplying a path for exploiting the full 64-bit address range
29467 @end enumerate
29468
29469 @noindent
29470 Ada's strong typing semantics has made it
29471 impractical to have different 32-bit and 64-bit modes. As soon as
29472 one object could possibly be outside the 32-bit address space, this
29473 would make it necessary for the @code{System.Address} type to be 64 bits.
29474 In particular, this would cause inconsistencies if 32-bit code is
29475 called from 64-bit code that raises an exception.
29476
29477 This issue has been resolved by always using 64-bit addressing
29478 at the system level, but allowing for automatic conversions between
29479 32-bit and 64-bit addresses where required. Thus users who
29480 do not currently require 64-bit addressing capabilities, can
29481 recompile their code with only minimal changes (and indeed
29482 if the code is written in portable Ada, with no assumptions about
29483 the size of the @code{Address} type, then no changes at all are necessary).
29484 At the same time,
29485 this approach provides a simple, gradual upgrade path to future
29486 use of larger memories than available for 32-bit systems.
29487 Also, newly written applications or libraries will by default
29488 be fully compatible with future systems exploiting 64-bit
29489 addressing capabilities.
29490
29491 @ref{Migration of 32 bit code}, will focus on porting applications
29492 that do not require more than 2 GB of
29493 addressable memory. This code will be referred to as
29494 @emph{32-bit code}.
29495 For applications intending to exploit the full 64-bit address space,
29496 @ref{Taking advantage of 64 bit addressing},
29497 will consider further changes that may be required.
29498 Such code will be referred to below as @emph{64-bit code}.
29499
29500 @node Migration of 32 bit code
29501 @subsection Migration of 32-bit code
29502
29503 @menu
29504 * Address types::
29505 * Access types and 32/64-bit allocation::
29506 * Unchecked conversions::
29507 * Predefined constants::
29508 * Interfacing with C::
29509 * 32/64-bit descriptors::
29510 * Experience with source compatibility::
29511 @end menu
29512
29513 @node Address types
29514 @subsubsection Address types
29515
29516 @noindent
29517 To solve the problem of mixing 64-bit and 32-bit addressing,
29518 while maintaining maximum backward compatibility, the following
29519 approach has been taken:
29520
29521 @itemize @bullet
29522 @item
29523 @code{System.Address} always has a size of 64 bits
29524 @cindex @code{System.Address} size
29525 @cindex @code{Address} size
29526
29527 @item
29528 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
29529 @cindex @code{System.Short_Address} size
29530 @cindex @code{Short_Address} size
29531 @end itemize
29532
29533 @noindent
29534 Since @code{System.Short_Address} is a subtype of @code{System.Address},
29535 a @code{Short_Address}
29536 may be used where an @code{Address} is required, and vice versa, without
29537 needing explicit type conversions.
29538 By virtue of the Open VMS parameter passing conventions,
29539 even imported
29540 and exported subprograms that have 32-bit address parameters are
29541 compatible with those that have 64-bit address parameters.
29542 (See @ref{Making code 64 bit clean} for details.)
29543
29544 The areas that may need attention are those where record types have
29545 been defined that contain components of the type @code{System.Address}, and
29546 where objects of this type are passed to code expecting a record layout with
29547 32-bit addresses.
29548
29549 Different compilers on different platforms cannot be
29550 expected to represent the same type in the same way,
29551 since alignment constraints
29552 and other system-dependent properties affect the compiler's decision.
29553 For that reason, Ada code
29554 generally uses representation clauses to specify the expected
29555 layout where required.
29556
29557 If such a representation clause uses 32 bits for a component having
29558 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
29559 will detect that error and produce a specific diagnostic message.
29560 The developer should then determine whether the representation
29561 should be 64 bits or not and make either of two changes:
29562 change the size to 64 bits and leave the type as @code{System.Address}, or
29563 leave the size as 32 bits and change the type to @code{System.Short_Address}.
29564 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
29565 required in any code setting or accessing the field; the compiler will
29566 automatically perform any needed conversions between address
29567 formats.
29568
29569 @node Access types and 32/64-bit allocation
29570 @subsubsection Access types and 32/64-bit allocation
29571 @cindex 32-bit allocation
29572 @cindex 64-bit allocation
29573
29574 @noindent
29575 By default, objects designated by access values are always allocated in
29576 the 64-bit address space, and access values themselves are represented
29577 in 64 bits. If these defaults are not appropriate, and 32-bit allocation
29578 is required (for example if the address of an allocated object is assigned
29579 to a @code{Short_Address} variable), then several alternatives are available:
29580
29581 @itemize @bullet
29582 @item
29583 A pool-specific access type (ie, an @w{Ada 83} access type, whose
29584 definition is @code{access T} versus @code{access all T} or
29585 @code{access constant T}), may be declared with a @code{'Size} representation
29586 clause that establishes the size as 32 bits.
29587 In such circumstances allocations for that type will
29588 be from the 32-bit heap. Such a clause is not permitted
29589 for a general access type (declared with @code{access all} or
29590 @code{access constant}) as values of such types must be able to refer
29591 to any object of the designated type, including objects residing outside
29592 the 32-bit address range. Existing @w{Ada 83} code will not contain such
29593 type definitions, however, since general access types were introduced
29594 in @w{Ada 95}.
29595
29596 @item
29597 Switches for @command{GNAT BIND} control whether the internal GNAT
29598 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
29599 @cindex @code{__gnat_malloc}
29600 The switches are respectively @option{-H64} (the default) and
29601 @option{-H32}.
29602 @cindex @option{-H32} (@command{gnatbind})
29603 @cindex @option{-H64} (@command{gnatbind})
29604
29605 @item
29606 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
29607 @cindex @code{GNAT$NO_MALLOC_64} environment variable
29608 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
29609 If this variable is left
29610 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
29611 then the default (64-bit) allocation is used.
29612 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
29613 then 32-bit allocation is used. The gnatbind qualifiers described above
29614 override this logical name.
29615
29616 @item
29617 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
29618 @cindex @option{-mno-malloc64} (^gcc^gcc^)
29619 at a low level to convert explicit calls to @code{malloc} and related
29620 functions from the C run-time library so that they perform allocations
29621 in the 32-bit heap.
29622 Since all internal allocations from GNAT use @code{__gnat_malloc},
29623 this switch is not required unless the program makes explicit calls on
29624 @code{malloc} (or related functions) from interfaced C code.
29625 @end itemize
29626
29627
29628 @node Unchecked conversions
29629 @subsubsection Unchecked conversions
29630
29631 @noindent
29632 In the case of an @code{Unchecked_Conversion} where the source type is a
29633 64-bit access type or the type @code{System.Address}, and the target
29634 type is a 32-bit type, the compiler will generate a warning.
29635 Even though the generated code will still perform the required
29636 conversions, it is highly recommended in these cases to use
29637 respectively a 32-bit access type or @code{System.Short_Address}
29638 as the source type.
29639
29640 @node Predefined constants
29641 @subsubsection Predefined constants
29642
29643 @noindent
29644 The following table shows the correspondence between pre-2006 versions of
29645 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
29646 (``New''):
29647
29648 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
29649 @item @b{Constant} @tab @b{Old} @tab @b{New}
29650 @item @code{System.Word_Size} @tab 32 @tab 64
29651 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
29652 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
29653 @item @code{System.Address_Size} @tab 32 @tab 64
29654 @end multitable
29655
29656 @noindent
29657 If you need to refer to the specific
29658 memory size of a 32-bit implementation, instead of the
29659 actual memory size, use @code{System.Short_Memory_Size}
29660 rather than @code{System.Memory_Size}.
29661 Similarly, references to @code{System.Address_Size} may need
29662 to be replaced by @code{System.Short_Address'Size}.
29663 The program @command{gnatfind} may be useful for locating
29664 references to the above constants, so that you can verify that they
29665 are still correct.
29666
29667 @node Interfacing with C
29668 @subsubsection Interfacing with C
29669
29670 @noindent
29671 In order to minimize the impact of the transition to 64-bit addresses on
29672 legacy programs, some fundamental types in the @code{Interfaces.C}
29673 package hierarchy continue to be represented in 32 bits.
29674 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
29675 This eases integration with the default HP C layout choices, for example
29676 as found in the system routines in @code{DECC$SHR.EXE}.
29677 Because of this implementation choice, the type fully compatible with
29678 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
29679 Depending on the context the compiler will issue a
29680 warning or an error when type @code{Address} is used, alerting the user to a
29681 potential problem. Otherwise 32-bit programs that use
29682 @code{Interfaces.C} should normally not require code modifications
29683
29684 The other issue arising with C interfacing concerns pragma @code{Convention}.
29685 For VMS 64-bit systems, there is an issue of the appropriate default size
29686 of C convention pointers in the absence of an explicit size clause. The HP
29687 C compiler can choose either 32 or 64 bits depending on compiler options.
29688 GNAT chooses 32-bits rather than 64-bits in the default case where no size
29689 clause is given. This proves a better choice for porting 32-bit legacy
29690 applications. In order to have a 64-bit representation, it is necessary to
29691 specify a size representation clause. For example:
29692
29693 @smallexample @c ada
29694 type int_star is access Interfaces.C.int;
29695 pragma Convention(C, int_star);
29696 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
29697 @end smallexample
29698
29699 @node 32/64-bit descriptors
29700 @subsubsection 32/64-bit descriptors
29701
29702 @noindent
29703 By default, GNAT uses a 64-bit descriptor mechanism. For an imported
29704 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
29705 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
29706 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
29707 @cindex @code{Short_Descriptor} mechanism for imported subprograms
29708
29709 If the configuration pragma @code{Short_Descriptors} is supplied, then
29710 all descriptors will be 32 bits.
29711 @cindex pragma @code{Short_Descriptors}
29712
29713 @node Experience with source compatibility
29714 @subsubsection Experience with source compatibility
29715
29716 @noindent
29717 The Security Server and STARLET on I64 provide an interesting ``test case''
29718 for source compatibility issues, since it is in such system code
29719 where assumptions about @code{Address} size might be expected to occur.
29720 Indeed, there were a small number of occasions in the Security Server
29721 file @file{jibdef.ads}
29722 where a representation clause for a record type specified
29723 32 bits for a component of type @code{Address}.
29724 All of these errors were detected by the compiler.
29725 The repair was obvious and immediate; to simply replace @code{Address} by
29726 @code{Short_Address}.
29727
29728 In the case of STARLET, there were several record types that should
29729 have had representation clauses but did not. In these record types
29730 there was an implicit assumption that an @code{Address} value occupied
29731 32 bits.
29732 These compiled without error, but their usage resulted in run-time error
29733 returns from STARLET system calls.
29734 Future GNAT technology enhancements may include a tool that detects and flags
29735 these sorts of potential source code porting problems.
29736
29737 @c ****************************************
29738 @node Taking advantage of 64 bit addressing
29739 @subsection Taking advantage of 64-bit addressing
29740
29741 @menu
29742 * Making code 64 bit clean::
29743 * Allocating memory from the 64 bit storage pool::
29744 * Restrictions on use of 64 bit objects::
29745 * STARLET and other predefined libraries::
29746 @end menu
29747
29748 @node Making code 64 bit clean
29749 @subsubsection Making code 64-bit clean
29750
29751 @noindent
29752 In order to prevent problems that may occur when (parts of) a
29753 system start using memory outside the 32-bit address range,
29754 we recommend some additional guidelines:
29755
29756 @itemize @bullet
29757 @item
29758 For imported subprograms that take parameters of the
29759 type @code{System.Address}, ensure that these subprograms can
29760 indeed handle 64-bit addresses. If not, or when in doubt,
29761 change the subprogram declaration to specify
29762 @code{System.Short_Address} instead.
29763
29764 @item
29765 Resolve all warnings related to size mismatches in
29766 unchecked conversions. Failing to do so causes
29767 erroneous execution if the source object is outside
29768 the 32-bit address space.
29769
29770 @item
29771 (optional) Explicitly use the 32-bit storage pool
29772 for access types used in a 32-bit context, or use
29773 generic access types where possible
29774 (@pxref{Restrictions on use of 64 bit objects}).
29775 @end itemize
29776
29777 @noindent
29778 If these rules are followed, the compiler will automatically insert
29779 any necessary checks to ensure that no addresses or access values
29780 passed to 32-bit code ever refer to objects outside the 32-bit
29781 address range.
29782 Any attempt to do this will raise @code{Constraint_Error}.
29783
29784 @node Allocating memory from the 64 bit storage pool
29785 @subsubsection Allocating memory from the 64-bit storage pool
29786
29787 @noindent
29788 By default, all allocations -- for both pool-specific and general
29789 access types -- use the 64-bit storage pool. To override
29790 this default, for an individual access type or globally, see
29791 @ref{Access types and 32/64-bit allocation}.
29792
29793 @node Restrictions on use of 64 bit objects
29794 @subsubsection Restrictions on use of 64-bit objects
29795
29796 @noindent
29797 Taking the address of an object allocated from a 64-bit storage pool,
29798 and then passing this address to a subprogram expecting
29799 @code{System.Short_Address},
29800 or assigning it to a variable of type @code{Short_Address}, will cause
29801 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
29802 (@pxref{Making code 64 bit clean}), or checks are suppressed,
29803 no exception is raised and execution
29804 will become erroneous.
29805
29806 @node STARLET and other predefined libraries
29807 @subsubsection STARLET and other predefined libraries
29808
29809 @noindent
29810 All code that comes as part of GNAT is 64-bit clean, but the
29811 restrictions given in @ref{Restrictions on use of 64 bit objects},
29812 still apply. Look at the package
29813 specs to see in which contexts objects allocated
29814 in 64-bit address space are acceptable.
29815
29816 @node Technical details
29817 @subsection Technical details
29818
29819 @noindent
29820 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
29821 Ada standard with respect to the type of @code{System.Address}. Previous
29822 versions of @value{EDITION} have defined this type as private and implemented it as a
29823 modular type.
29824
29825 In order to allow defining @code{System.Short_Address} as a proper subtype,
29826 and to match the implicit sign extension in parameter passing,
29827 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
29828 visible (i.e., non-private) integer type.
29829 Standard operations on the type, such as the binary operators ``+'', ``-'',
29830 etc., that take @code{Address} operands and return an @code{Address} result,
29831 have been hidden by declaring these
29832 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
29833 ambiguities that would otherwise result from overloading.
29834 (Note that, although @code{Address} is a visible integer type,
29835 good programming practice dictates against exploiting the type's
29836 integer properties such as literals, since this will compromise
29837 code portability.)
29838
29839 Defining @code{Address} as a visible integer type helps achieve
29840 maximum compatibility for existing Ada code,
29841 without sacrificing the capabilities of the 64-bit architecture.
29842 @end ifset
29843
29844 @c ************************************************
29845 @node Microsoft Windows Topics
29846 @appendix Microsoft Windows Topics
29847 @cindex Windows NT
29848 @cindex Windows 95
29849 @cindex Windows 98
29850
29851 @noindent
29852 This chapter describes topics that are specific to the Microsoft Windows
29853 platforms (NT, 2000, and XP Professional).
29854
29855 @menu
29856 @ifclear FSFEDITION
29857 * Installing from the Command Line::
29858 @end ifclear
29859 * Using GNAT on Windows::
29860 * Using a network installation of GNAT::
29861 * CONSOLE and WINDOWS subsystems::
29862 * Temporary Files::
29863 * Mixed-Language Programming on Windows::
29864 * Windows Calling Conventions::
29865 * Introduction to Dynamic Link Libraries (DLLs)::
29866 * Using DLLs with GNAT::
29867 * Building DLLs with GNAT Project files::
29868 * Building DLLs with GNAT::
29869 * Building DLLs with gnatdll::
29870 * GNAT and Windows Resources::
29871 * Debugging a DLL::
29872 * Setting Stack Size from gnatlink::
29873 * Setting Heap Size from gnatlink::
29874 @end menu
29875
29876 @ifclear FSFEDITION
29877 @node Installing from the Command Line
29878 @section Installing from the Command Line
29879 @cindex Batch installation
29880 @cindex Silent installation
29881 @cindex Unassisted installation
29882
29883 @noindent
29884 By default the @value{EDITION} installers display a GUI that prompts the user
29885 to enter installation path and similar information, and guide him through the
29886 installation process. It is also possible to perform silent installations
29887 using the command-line interface.
29888
29889 In order to install one of the @value{EDITION} installers from the command
29890 line you should pass parameter @code{/S} (and, optionally,
29891 @code{/D=<directory>}) as command-line arguments.
29892
29893 @ifset PROEDITION
29894 For example, for an unattended installation of
29895 @value{EDITION} 7.0.2 into the default directory
29896 @code{C:\GNATPRO\7.0.2} you would run:
29897
29898 @smallexample
29899 gnatpro-7.0.2-i686-pc-mingw32-bin.exe /S
29900 @end smallexample
29901
29902 To install into a custom directory, say, @code{C:\TOOLS\GNATPRO\7.0.2}:
29903
29904 @smallexample
29905 gnatpro-7.0.2-i686-pc-mingw32-bin /S /D=C:\TOOLS\GNATPRO\7.0.2
29906 @end smallexample
29907 @end ifset
29908
29909 @ifset GPLEDITION
29910 For example, for an unattended installation of
29911 @value{EDITION} 2012 into @code{C:\GNAT\2012}:
29912
29913 @smallexample
29914 gnat-gpl-2012-i686-pc-mingw32-bin /S /D=C:\GNAT\2012
29915 @end smallexample
29916 @end ifset
29917
29918 You can use the same syntax for all installers.
29919
29920 Note that unattended installations don't modify system path, nor create file
29921 associations, so such activities need to be done by hand.
29922 @end ifclear
29923
29924 @node Using GNAT on Windows
29925 @section Using GNAT on Windows
29926
29927 @noindent
29928 One of the strengths of the GNAT technology is that its tool set
29929 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
29930 @code{gdb} debugger, etc.) is used in the same way regardless of the
29931 platform.
29932
29933 On Windows this tool set is complemented by a number of Microsoft-specific
29934 tools that have been provided to facilitate interoperability with Windows
29935 when this is required. With these tools:
29936
29937 @itemize @bullet
29938
29939 @item
29940 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
29941 subsystems.
29942
29943 @item
29944 You can use any Dynamically Linked Library (DLL) in your Ada code (both
29945 relocatable and non-relocatable DLLs are supported).
29946
29947 @item
29948 You can build Ada DLLs for use in other applications. These applications
29949 can be written in a language other than Ada (e.g., C, C++, etc). Again both
29950 relocatable and non-relocatable Ada DLLs are supported.
29951
29952 @item
29953 You can include Windows resources in your Ada application.
29954
29955 @item
29956 You can use or create COM/DCOM objects.
29957 @end itemize
29958
29959 @noindent
29960 Immediately below are listed all known general GNAT-for-Windows restrictions.
29961 Other restrictions about specific features like Windows Resources and DLLs
29962 are listed in separate sections below.
29963
29964 @itemize @bullet
29965
29966 @item
29967 It is not possible to use @code{GetLastError} and @code{SetLastError}
29968 when tasking, protected records, or exceptions are used. In these
29969 cases, in order to implement Ada semantics, the GNAT run-time system
29970 calls certain Win32 routines that set the last error variable to 0 upon
29971 success. It should be possible to use @code{GetLastError} and
29972 @code{SetLastError} when tasking, protected record, and exception
29973 features are not used, but it is not guaranteed to work.
29974
29975 @item
29976 It is not possible to link against Microsoft C++ libraries except for
29977 import libraries. Interfacing must be done by the mean of DLLs.
29978
29979 @item
29980 It is possible to link against Microsoft C libraries. Yet the preferred
29981 solution is to use C/C++ compiler that comes with @value{EDITION}, since it
29982 doesn't require having two different development environments and makes the
29983 inter-language debugging experience smoother.
29984
29985 @item
29986 When the compilation environment is located on FAT32 drives, users may
29987 experience recompilations of the source files that have not changed if
29988 Daylight Saving Time (DST) state has changed since the last time files
29989 were compiled. NTFS drives do not have this problem.
29990
29991 @item
29992 No components of the GNAT toolset use any entries in the Windows
29993 registry. The only entries that can be created are file associations and
29994 PATH settings, provided the user has chosen to create them at installation
29995 time, as well as some minimal book-keeping information needed to correctly
29996 uninstall or integrate different GNAT products.
29997 @end itemize
29998
29999 @node Using a network installation of GNAT
30000 @section Using a network installation of GNAT
30001
30002 @noindent
30003 Make sure the system on which GNAT is installed is accessible from the
30004 current machine, i.e., the install location is shared over the network.
30005 Shared resources are accessed on Windows by means of UNC paths, which
30006 have the format @code{\\server\sharename\path}
30007
30008 In order to use such a network installation, simply add the UNC path of the
30009 @file{bin} directory of your GNAT installation in front of your PATH. For
30010 example, if GNAT is installed in @file{\GNAT} directory of a share location
30011 called @file{c-drive} on a machine @file{LOKI}, the following command will
30012 make it available:
30013
30014 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
30015
30016 Be aware that every compilation using the network installation results in the
30017 transfer of large amounts of data across the network and will likely cause
30018 serious performance penalty.
30019
30020 @node CONSOLE and WINDOWS subsystems
30021 @section CONSOLE and WINDOWS subsystems
30022 @cindex CONSOLE Subsystem
30023 @cindex WINDOWS Subsystem
30024 @cindex -mwindows
30025
30026 @noindent
30027 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
30028 (which is the default subsystem) will always create a console when
30029 launching the application. This is not something desirable when the
30030 application has a Windows GUI. To get rid of this console the
30031 application must be using the @code{WINDOWS} subsystem. To do so
30032 the @option{-mwindows} linker option must be specified.
30033
30034 @smallexample
30035 $ gnatmake winprog -largs -mwindows
30036 @end smallexample
30037
30038 @node Temporary Files
30039 @section Temporary Files
30040 @cindex Temporary files
30041
30042 @noindent
30043 It is possible to control where temporary files gets created by setting
30044 the @env{TMP} environment variable. The file will be created:
30045
30046 @itemize
30047 @item Under the directory pointed to by the @env{TMP} environment variable if
30048 this directory exists.
30049
30050 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
30051 set (or not pointing to a directory) and if this directory exists.
30052
30053 @item Under the current working directory otherwise.
30054 @end itemize
30055
30056 @noindent
30057 This allows you to determine exactly where the temporary
30058 file will be created. This is particularly useful in networked
30059 environments where you may not have write access to some
30060 directories.
30061
30062 @node Mixed-Language Programming on Windows
30063 @section Mixed-Language Programming on Windows
30064
30065 @noindent
30066 Developing pure Ada applications on Windows is no different than on
30067 other GNAT-supported platforms. However, when developing or porting an
30068 application that contains a mix of Ada and C/C++, the choice of your
30069 Windows C/C++ development environment conditions your overall
30070 interoperability strategy.
30071
30072 If you use @command{gcc} or Microsoft C to compile the non-Ada part of
30073 your application, there are no Windows-specific restrictions that
30074 affect the overall interoperability with your Ada code. If you do want
30075 to use the Microsoft tools for your C++ code, you have two choices:
30076
30077 @enumerate
30078 @item
30079 Encapsulate your C++ code in a DLL to be linked with your Ada
30080 application. In this case, use the Microsoft or whatever environment to
30081 build the DLL and use GNAT to build your executable
30082 (@pxref{Using DLLs with GNAT}).
30083
30084 @item
30085 Or you can encapsulate your Ada code in a DLL to be linked with the
30086 other part of your application. In this case, use GNAT to build the DLL
30087 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
30088 or whatever environment to build your executable.
30089 @end enumerate
30090
30091 In addition to the description about C main in
30092 @pxref{Mixed Language Programming} section, if the C main uses a
30093 stand-alone library it is required on x86-windows to
30094 setup the SEH context. For this the C main must looks like this:
30095
30096 @smallexample
30097 /* main.c */
30098 extern void adainit (void);
30099 extern void adafinal (void);
30100 extern void __gnat_initialize(void*);
30101 extern void call_to_ada (void);
30102
30103 int main (int argc, char *argv[])
30104 @{
30105 int SEH [2];
30106
30107 /* Initialize the SEH context */
30108 __gnat_initialize (&SEH);
30109
30110 adainit();
30111
30112 /* Then call Ada services in the stand-alone library */
30113
30114 call_to_ada();
30115
30116 adafinal();
30117 @}
30118 @end smallexample
30119
30120 Note that this is not needed on x86_64-windows where the Windows
30121 native SEH support is used.
30122
30123 @node Windows Calling Conventions
30124 @section Windows Calling Conventions
30125 @findex Stdcall
30126 @findex APIENTRY
30127
30128 This section pertain only to Win32. On Win64 there is a single native
30129 calling convention. All convention specifiers are ignored on this
30130 platform.
30131
30132 @menu
30133 * C Calling Convention::
30134 * Stdcall Calling Convention::
30135 * Win32 Calling Convention::
30136 * DLL Calling Convention::
30137 @end menu
30138
30139 @noindent
30140 When a subprogram @code{F} (caller) calls a subprogram @code{G}
30141 (callee), there are several ways to push @code{G}'s parameters on the
30142 stack and there are several possible scenarios to clean up the stack
30143 upon @code{G}'s return. A calling convention is an agreed upon software
30144 protocol whereby the responsibilities between the caller (@code{F}) and
30145 the callee (@code{G}) are clearly defined. Several calling conventions
30146 are available for Windows:
30147
30148 @itemize @bullet
30149 @item
30150 @code{C} (Microsoft defined)
30151
30152 @item
30153 @code{Stdcall} (Microsoft defined)
30154
30155 @item
30156 @code{Win32} (GNAT specific)
30157
30158 @item
30159 @code{DLL} (GNAT specific)
30160 @end itemize
30161
30162 @node C Calling Convention
30163 @subsection @code{C} Calling Convention
30164
30165 @noindent
30166 This is the default calling convention used when interfacing to C/C++
30167 routines compiled with either @command{gcc} or Microsoft Visual C++.
30168
30169 In the @code{C} calling convention subprogram parameters are pushed on the
30170 stack by the caller from right to left. The caller itself is in charge of
30171 cleaning up the stack after the call. In addition, the name of a routine
30172 with @code{C} calling convention is mangled by adding a leading underscore.
30173
30174 The name to use on the Ada side when importing (or exporting) a routine
30175 with @code{C} calling convention is the name of the routine. For
30176 instance the C function:
30177
30178 @smallexample
30179 int get_val (long);
30180 @end smallexample
30181
30182 @noindent
30183 should be imported from Ada as follows:
30184
30185 @smallexample @c ada
30186 @group
30187 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30188 pragma Import (C, Get_Val, External_Name => "get_val");
30189 @end group
30190 @end smallexample
30191
30192 @noindent
30193 Note that in this particular case the @code{External_Name} parameter could
30194 have been omitted since, when missing, this parameter is taken to be the
30195 name of the Ada entity in lower case. When the @code{Link_Name} parameter
30196 is missing, as in the above example, this parameter is set to be the
30197 @code{External_Name} with a leading underscore.
30198
30199 When importing a variable defined in C, you should always use the @code{C}
30200 calling convention unless the object containing the variable is part of a
30201 DLL (in which case you should use the @code{Stdcall} calling
30202 convention, @pxref{Stdcall Calling Convention}).
30203
30204 @node Stdcall Calling Convention
30205 @subsection @code{Stdcall} Calling Convention
30206
30207 @noindent
30208 This convention, which was the calling convention used for Pascal
30209 programs, is used by Microsoft for all the routines in the Win32 API for
30210 efficiency reasons. It must be used to import any routine for which this
30211 convention was specified.
30212
30213 In the @code{Stdcall} calling convention subprogram parameters are pushed
30214 on the stack by the caller from right to left. The callee (and not the
30215 caller) is in charge of cleaning the stack on routine exit. In addition,
30216 the name of a routine with @code{Stdcall} calling convention is mangled by
30217 adding a leading underscore (as for the @code{C} calling convention) and a
30218 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
30219 bytes) of the parameters passed to the routine.
30220
30221 The name to use on the Ada side when importing a C routine with a
30222 @code{Stdcall} calling convention is the name of the C routine. The leading
30223 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
30224 the compiler. For instance the Win32 function:
30225
30226 @smallexample
30227 @b{APIENTRY} int get_val (long);
30228 @end smallexample
30229
30230 @noindent
30231 should be imported from Ada as follows:
30232
30233 @smallexample @c ada
30234 @group
30235 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30236 pragma Import (Stdcall, Get_Val);
30237 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
30238 @end group
30239 @end smallexample
30240
30241 @noindent
30242 As for the @code{C} calling convention, when the @code{External_Name}
30243 parameter is missing, it is taken to be the name of the Ada entity in lower
30244 case. If instead of writing the above import pragma you write:
30245
30246 @smallexample @c ada
30247 @group
30248 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30249 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
30250 @end group
30251 @end smallexample
30252
30253 @noindent
30254 then the imported routine is @code{_retrieve_val@@4}. However, if instead
30255 of specifying the @code{External_Name} parameter you specify the
30256 @code{Link_Name} as in the following example:
30257
30258 @smallexample @c ada
30259 @group
30260 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30261 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
30262 @end group
30263 @end smallexample
30264
30265 @noindent
30266 then the imported routine is @code{retrieve_val}, that is, there is no
30267 decoration at all. No leading underscore and no Stdcall suffix
30268 @code{@@}@code{@var{nn}}.
30269
30270 @noindent
30271 This is especially important as in some special cases a DLL's entry
30272 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
30273 name generated for a call has it.
30274
30275 @noindent
30276 It is also possible to import variables defined in a DLL by using an
30277 import pragma for a variable. As an example, if a DLL contains a
30278 variable defined as:
30279
30280 @smallexample
30281 int my_var;
30282 @end smallexample
30283
30284 @noindent
30285 then, to access this variable from Ada you should write:
30286
30287 @smallexample @c ada
30288 @group
30289 My_Var : Interfaces.C.int;
30290 pragma Import (Stdcall, My_Var);
30291 @end group
30292 @end smallexample
30293
30294 @noindent
30295 Note that to ease building cross-platform bindings this convention
30296 will be handled as a @code{C} calling convention on non-Windows platforms.
30297
30298 @node Win32 Calling Convention
30299 @subsection @code{Win32} Calling Convention
30300
30301 @noindent
30302 This convention, which is GNAT-specific is fully equivalent to the
30303 @code{Stdcall} calling convention described above.
30304
30305 @node DLL Calling Convention
30306 @subsection @code{DLL} Calling Convention
30307
30308 @noindent
30309 This convention, which is GNAT-specific is fully equivalent to the
30310 @code{Stdcall} calling convention described above.
30311
30312 @node Introduction to Dynamic Link Libraries (DLLs)
30313 @section Introduction to Dynamic Link Libraries (DLLs)
30314 @findex DLL
30315
30316 @noindent
30317 A Dynamically Linked Library (DLL) is a library that can be shared by
30318 several applications running under Windows. A DLL can contain any number of
30319 routines and variables.
30320
30321 One advantage of DLLs is that you can change and enhance them without
30322 forcing all the applications that depend on them to be relinked or
30323 recompiled. However, you should be aware than all calls to DLL routines are
30324 slower since, as you will understand below, such calls are indirect.
30325
30326 To illustrate the remainder of this section, suppose that an application
30327 wants to use the services of a DLL @file{API.dll}. To use the services
30328 provided by @file{API.dll} you must statically link against the DLL or
30329 an import library which contains a jump table with an entry for each
30330 routine and variable exported by the DLL. In the Microsoft world this
30331 import library is called @file{API.lib}. When using GNAT this import
30332 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
30333 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
30334
30335 After you have linked your application with the DLL or the import library
30336 and you run your application, here is what happens:
30337
30338 @enumerate
30339 @item
30340 Your application is loaded into memory.
30341
30342 @item
30343 The DLL @file{API.dll} is mapped into the address space of your
30344 application. This means that:
30345
30346 @itemize @bullet
30347 @item
30348 The DLL will use the stack of the calling thread.
30349
30350 @item
30351 The DLL will use the virtual address space of the calling process.
30352
30353 @item
30354 The DLL will allocate memory from the virtual address space of the calling
30355 process.
30356
30357 @item
30358 Handles (pointers) can be safely exchanged between routines in the DLL
30359 routines and routines in the application using the DLL.
30360 @end itemize
30361
30362 @item
30363 The entries in the jump table (from the import library @file{libAPI.dll.a}
30364 or @file{API.lib} or automatically created when linking against a DLL)
30365 which is part of your application are initialized with the addresses
30366 of the routines and variables in @file{API.dll}.
30367
30368 @item
30369 If present in @file{API.dll}, routines @code{DllMain} or
30370 @code{DllMainCRTStartup} are invoked. These routines typically contain
30371 the initialization code needed for the well-being of the routines and
30372 variables exported by the DLL.
30373 @end enumerate
30374
30375 @noindent
30376 There is an additional point which is worth mentioning. In the Windows
30377 world there are two kind of DLLs: relocatable and non-relocatable
30378 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
30379 in the target application address space. If the addresses of two
30380 non-relocatable DLLs overlap and these happen to be used by the same
30381 application, a conflict will occur and the application will run
30382 incorrectly. Hence, when possible, it is always preferable to use and
30383 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
30384 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
30385 User's Guide) removes the debugging symbols from the DLL but the DLL can
30386 still be relocated.
30387
30388 As a side note, an interesting difference between Microsoft DLLs and
30389 Unix shared libraries, is the fact that on most Unix systems all public
30390 routines are exported by default in a Unix shared library, while under
30391 Windows it is possible (but not required) to list exported routines in
30392 a definition file (@pxref{The Definition File}).
30393
30394 @node Using DLLs with GNAT
30395 @section Using DLLs with GNAT
30396
30397 @menu
30398 * Creating an Ada Spec for the DLL Services::
30399 * Creating an Import Library::
30400 @end menu
30401
30402 @noindent
30403 To use the services of a DLL, say @file{API.dll}, in your Ada application
30404 you must have:
30405
30406 @enumerate
30407 @item
30408 The Ada spec for the routines and/or variables you want to access in
30409 @file{API.dll}. If not available this Ada spec must be built from the C/C++
30410 header files provided with the DLL.
30411
30412 @item
30413 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
30414 mentioned an import library is a statically linked library containing the
30415 import table which will be filled at load time to point to the actual
30416 @file{API.dll} routines. Sometimes you don't have an import library for the
30417 DLL you want to use. The following sections will explain how to build
30418 one. Note that this is optional.
30419
30420 @item
30421 The actual DLL, @file{API.dll}.
30422 @end enumerate
30423
30424 @noindent
30425 Once you have all the above, to compile an Ada application that uses the
30426 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
30427 you simply issue the command
30428
30429 @smallexample
30430 $ gnatmake my_ada_app -largs -lAPI
30431 @end smallexample
30432
30433 @noindent
30434 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
30435 tells the GNAT linker to look for an import library. The linker will
30436 look for a library name in this specific order:
30437
30438 @enumerate
30439 @item @file{libAPI.dll.a}
30440 @item @file{API.dll.a}
30441 @item @file{libAPI.a}
30442 @item @file{API.lib}
30443 @item @file{libAPI.dll}
30444 @item @file{API.dll}
30445 @end enumerate
30446
30447 The first three are the GNU style import libraries. The third is the
30448 Microsoft style import libraries. The last two are the actual DLL names.
30449
30450 Note that if the Ada package spec for @file{API.dll} contains the
30451 following pragma
30452
30453 @smallexample @c ada
30454 pragma Linker_Options ("-lAPI");
30455 @end smallexample
30456
30457 @noindent
30458 you do not have to add @option{-largs -lAPI} at the end of the
30459 @command{gnatmake} command.
30460
30461 If any one of the items above is missing you will have to create it
30462 yourself. The following sections explain how to do so using as an
30463 example a fictitious DLL called @file{API.dll}.
30464
30465 @node Creating an Ada Spec for the DLL Services
30466 @subsection Creating an Ada Spec for the DLL Services
30467
30468 @noindent
30469 A DLL typically comes with a C/C++ header file which provides the
30470 definitions of the routines and variables exported by the DLL. The Ada
30471 equivalent of this header file is a package spec that contains definitions
30472 for the imported entities. If the DLL you intend to use does not come with
30473 an Ada spec you have to generate one such spec yourself. For example if
30474 the header file of @file{API.dll} is a file @file{api.h} containing the
30475 following two definitions:
30476
30477 @smallexample
30478 @group
30479 @cartouche
30480 int some_var;
30481 int get (char *);
30482 @end cartouche
30483 @end group
30484 @end smallexample
30485
30486 @noindent
30487 then the equivalent Ada spec could be:
30488
30489 @smallexample @c ada
30490 @group
30491 @cartouche
30492 with Interfaces.C.Strings;
30493 package API is
30494 use Interfaces;
30495
30496 Some_Var : C.int;
30497 function Get (Str : C.Strings.Chars_Ptr) return C.int;
30498
30499 private
30500 pragma Import (C, Get);
30501 pragma Import (DLL, Some_Var);
30502 end API;
30503 @end cartouche
30504 @end group
30505 @end smallexample
30506
30507 @node Creating an Import Library
30508 @subsection Creating an Import Library
30509 @cindex Import library
30510
30511 @menu
30512 * The Definition File::
30513 * GNAT-Style Import Library::
30514 * Microsoft-Style Import Library::
30515 @end menu
30516
30517 @noindent
30518 If a Microsoft-style import library @file{API.lib} or a GNAT-style
30519 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
30520 with @file{API.dll} you can skip this section. You can also skip this
30521 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
30522 as in this case it is possible to link directly against the
30523 DLL. Otherwise read on.
30524
30525 @node The Definition File
30526 @subsubsection The Definition File
30527 @cindex Definition file
30528 @findex .def
30529
30530 @noindent
30531 As previously mentioned, and unlike Unix systems, the list of symbols
30532 that are exported from a DLL must be provided explicitly in Windows.
30533 The main goal of a definition file is precisely that: list the symbols
30534 exported by a DLL. A definition file (usually a file with a @code{.def}
30535 suffix) has the following structure:
30536
30537 @smallexample
30538 @group
30539 @cartouche
30540 @r{[}LIBRARY @var{name}@r{]}
30541 @r{[}DESCRIPTION @var{string}@r{]}
30542 EXPORTS
30543 @var{symbol1}
30544 @var{symbol2}
30545 @dots{}
30546 @end cartouche
30547 @end group
30548 @end smallexample
30549
30550 @table @code
30551 @item LIBRARY @var{name}
30552 This section, which is optional, gives the name of the DLL.
30553
30554 @item DESCRIPTION @var{string}
30555 This section, which is optional, gives a description string that will be
30556 embedded in the import library.
30557
30558 @item EXPORTS
30559 This section gives the list of exported symbols (procedures, functions or
30560 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
30561 section of @file{API.def} looks like:
30562
30563 @smallexample
30564 @group
30565 @cartouche
30566 EXPORTS
30567 some_var
30568 get
30569 @end cartouche
30570 @end group
30571 @end smallexample
30572 @end table
30573
30574 @noindent
30575 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
30576 (@pxref{Windows Calling Conventions}) for a Stdcall
30577 calling convention function in the exported symbols list.
30578
30579 @noindent
30580 There can actually be other sections in a definition file, but these
30581 sections are not relevant to the discussion at hand.
30582
30583 @node GNAT-Style Import Library
30584 @subsubsection GNAT-Style Import Library
30585
30586 @noindent
30587 To create a static import library from @file{API.dll} with the GNAT tools
30588 you should proceed as follows:
30589
30590 @enumerate
30591 @item
30592 Create the definition file @file{API.def} (@pxref{The Definition File}).
30593 For that use the @code{dll2def} tool as follows:
30594
30595 @smallexample
30596 $ dll2def API.dll > API.def
30597 @end smallexample
30598
30599 @noindent
30600 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
30601 to standard output the list of entry points in the DLL. Note that if
30602 some routines in the DLL have the @code{Stdcall} convention
30603 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
30604 suffix then you'll have to edit @file{api.def} to add it, and specify
30605 @option{-k} to @command{gnatdll} when creating the import library.
30606
30607 @noindent
30608 Here are some hints to find the right @code{@@}@var{nn} suffix.
30609
30610 @enumerate
30611 @item
30612 If you have the Microsoft import library (.lib), it is possible to get
30613 the right symbols by using Microsoft @code{dumpbin} tool (see the
30614 corresponding Microsoft documentation for further details).
30615
30616 @smallexample
30617 $ dumpbin /exports api.lib
30618 @end smallexample
30619
30620 @item
30621 If you have a message about a missing symbol at link time the compiler
30622 tells you what symbol is expected. You just have to go back to the
30623 definition file and add the right suffix.
30624 @end enumerate
30625
30626 @item
30627 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
30628 (@pxref{Using gnatdll}) as follows:
30629
30630 @smallexample
30631 $ gnatdll -e API.def -d API.dll
30632 @end smallexample
30633
30634 @noindent
30635 @code{gnatdll} takes as input a definition file @file{API.def} and the
30636 name of the DLL containing the services listed in the definition file
30637 @file{API.dll}. The name of the static import library generated is
30638 computed from the name of the definition file as follows: if the
30639 definition file name is @var{xyz}@code{.def}, the import library name will
30640 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
30641 @option{-e} could have been removed because the name of the definition
30642 file (before the ``@code{.def}'' suffix) is the same as the name of the
30643 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
30644 @end enumerate
30645
30646 @node Microsoft-Style Import Library
30647 @subsubsection Microsoft-Style Import Library
30648
30649 @noindent
30650 With GNAT you can either use a GNAT-style or Microsoft-style import
30651 library. A Microsoft import library is needed only if you plan to make an
30652 Ada DLL available to applications developed with Microsoft
30653 tools (@pxref{Mixed-Language Programming on Windows}).
30654
30655 To create a Microsoft-style import library for @file{API.dll} you
30656 should proceed as follows:
30657
30658 @enumerate
30659 @item
30660 Create the definition file @file{API.def} from the DLL. For this use either
30661 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
30662 tool (see the corresponding Microsoft documentation for further details).
30663
30664 @item
30665 Build the actual import library using Microsoft's @code{lib} utility:
30666
30667 @smallexample
30668 $ lib -machine:IX86 -def:API.def -out:API.lib
30669 @end smallexample
30670
30671 @noindent
30672 If you use the above command the definition file @file{API.def} must
30673 contain a line giving the name of the DLL:
30674
30675 @smallexample
30676 LIBRARY "API"
30677 @end smallexample
30678
30679 @noindent
30680 See the Microsoft documentation for further details about the usage of
30681 @code{lib}.
30682 @end enumerate
30683
30684 @node Building DLLs with GNAT Project files
30685 @section Building DLLs with GNAT Project files
30686 @cindex DLLs, building
30687
30688 @noindent
30689 There is nothing specific to Windows in the build process.
30690 @pxref{Library Projects}.
30691
30692 @noindent
30693 Due to a system limitation, it is not possible under Windows to create threads
30694 when inside the @code{DllMain} routine which is used for auto-initialization
30695 of shared libraries, so it is not possible to have library level tasks in SALs.
30696
30697 @node Building DLLs with GNAT
30698 @section Building DLLs with GNAT
30699 @cindex DLLs, building
30700
30701 @noindent
30702 This section explain how to build DLLs using the GNAT built-in DLL
30703 support. With the following procedure it is straight forward to build
30704 and use DLLs with GNAT.
30705
30706 @enumerate
30707
30708 @item building object files
30709
30710 The first step is to build all objects files that are to be included
30711 into the DLL. This is done by using the standard @command{gnatmake} tool.
30712
30713 @item building the DLL
30714
30715 To build the DLL you must use @command{gcc}'s @option{-shared} and
30716 @option{-shared-libgcc} options. It is quite simple to use this method:
30717
30718 @smallexample
30719 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
30720 @end smallexample
30721
30722 It is important to note that in this case all symbols found in the
30723 object files are automatically exported. It is possible to restrict
30724 the set of symbols to export by passing to @command{gcc} a definition
30725 file, @pxref{The Definition File}. For example:
30726
30727 @smallexample
30728 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
30729 @end smallexample
30730
30731 If you use a definition file you must export the elaboration procedures
30732 for every package that required one. Elaboration procedures are named
30733 using the package name followed by "_E".
30734
30735 @item preparing DLL to be used
30736
30737 For the DLL to be used by client programs the bodies must be hidden
30738 from it and the .ali set with read-only attribute. This is very important
30739 otherwise GNAT will recompile all packages and will not actually use
30740 the code in the DLL. For example:
30741
30742 @smallexample
30743 $ mkdir apilib
30744 $ copy *.ads *.ali api.dll apilib
30745 $ attrib +R apilib\*.ali
30746 @end smallexample
30747
30748 @end enumerate
30749
30750 At this point it is possible to use the DLL by directly linking
30751 against it. Note that you must use the GNAT shared runtime when using
30752 GNAT shared libraries. This is achieved by using @option{-shared} binder's
30753 option.
30754
30755 @smallexample
30756 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
30757 @end smallexample
30758
30759 @node Building DLLs with gnatdll
30760 @section Building DLLs with gnatdll
30761 @cindex DLLs, building
30762
30763 @menu
30764 * Limitations When Using Ada DLLs from Ada::
30765 * Exporting Ada Entities::
30766 * Ada DLLs and Elaboration::
30767 * Ada DLLs and Finalization::
30768 * Creating a Spec for Ada DLLs::
30769 * Creating the Definition File::
30770 * Using gnatdll::
30771 @end menu
30772
30773 @noindent
30774 Note that it is preferred to use GNAT Project files
30775 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
30776 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
30777
30778 This section explains how to build DLLs containing Ada code using
30779 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
30780 remainder of this section.
30781
30782 The steps required to build an Ada DLL that is to be used by Ada as well as
30783 non-Ada applications are as follows:
30784
30785 @enumerate
30786 @item
30787 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
30788 @code{Stdcall} calling convention to avoid any Ada name mangling for the
30789 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
30790 skip this step if you plan to use the Ada DLL only from Ada applications.
30791
30792 @item
30793 Your Ada code must export an initialization routine which calls the routine
30794 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
30795 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
30796 routine exported by the Ada DLL must be invoked by the clients of the DLL
30797 to initialize the DLL.
30798
30799 @item
30800 When useful, the DLL should also export a finalization routine which calls
30801 routine @code{adafinal} generated by @command{gnatbind} to perform the
30802 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
30803 The finalization routine exported by the Ada DLL must be invoked by the
30804 clients of the DLL when the DLL services are no further needed.
30805
30806 @item
30807 You must provide a spec for the services exported by the Ada DLL in each
30808 of the programming languages to which you plan to make the DLL available.
30809
30810 @item
30811 You must provide a definition file listing the exported entities
30812 (@pxref{The Definition File}).
30813
30814 @item
30815 Finally you must use @code{gnatdll} to produce the DLL and the import
30816 library (@pxref{Using gnatdll}).
30817 @end enumerate
30818
30819 @noindent
30820 Note that a relocatable DLL stripped using the @code{strip}
30821 binutils tool will not be relocatable anymore. To build a DLL without
30822 debug information pass @code{-largs -s} to @code{gnatdll}. This
30823 restriction does not apply to a DLL built using a Library Project.
30824 @pxref{Library Projects}.
30825
30826 @node Limitations When Using Ada DLLs from Ada
30827 @subsection Limitations When Using Ada DLLs from Ada
30828
30829 @noindent
30830 When using Ada DLLs from Ada applications there is a limitation users
30831 should be aware of. Because on Windows the GNAT run time is not in a DLL of
30832 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
30833 each Ada DLL includes the services of the GNAT run time that are necessary
30834 to the Ada code inside the DLL. As a result, when an Ada program uses an
30835 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
30836 one in the main program.
30837
30838 It is therefore not possible to exchange GNAT run-time objects between the
30839 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
30840 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
30841 types, etc.
30842
30843 It is completely safe to exchange plain elementary, array or record types,
30844 Windows object handles, etc.
30845
30846 @node Exporting Ada Entities
30847 @subsection Exporting Ada Entities
30848 @cindex Export table
30849
30850 @noindent
30851 Building a DLL is a way to encapsulate a set of services usable from any
30852 application. As a result, the Ada entities exported by a DLL should be
30853 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
30854 any Ada name mangling. As an example here is an Ada package
30855 @code{API}, spec and body, exporting two procedures, a function, and a
30856 variable:
30857
30858 @smallexample @c ada
30859 @group
30860 @cartouche
30861 with Interfaces.C; use Interfaces;
30862 package API is
30863 Count : C.int := 0;
30864 function Factorial (Val : C.int) return C.int;
30865
30866 procedure Initialize_API;
30867 procedure Finalize_API;
30868 -- Initialization & Finalization routines. More in the next section.
30869 private
30870 pragma Export (C, Initialize_API);
30871 pragma Export (C, Finalize_API);
30872 pragma Export (C, Count);
30873 pragma Export (C, Factorial);
30874 end API;
30875 @end cartouche
30876 @end group
30877 @end smallexample
30878
30879 @smallexample @c ada
30880 @group
30881 @cartouche
30882 package body API is
30883 function Factorial (Val : C.int) return C.int is
30884 Fact : C.int := 1;
30885 begin
30886 Count := Count + 1;
30887 for K in 1 .. Val loop
30888 Fact := Fact * K;
30889 end loop;
30890 return Fact;
30891 end Factorial;
30892
30893 procedure Initialize_API is
30894 procedure Adainit;
30895 pragma Import (C, Adainit);
30896 begin
30897 Adainit;
30898 end Initialize_API;
30899
30900 procedure Finalize_API is
30901 procedure Adafinal;
30902 pragma Import (C, Adafinal);
30903 begin
30904 Adafinal;
30905 end Finalize_API;
30906 end API;
30907 @end cartouche
30908 @end group
30909 @end smallexample
30910
30911 @noindent
30912 If the Ada DLL you are building will only be used by Ada applications
30913 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
30914 convention. As an example, the previous package could be written as
30915 follows:
30916
30917 @smallexample @c ada
30918 @group
30919 @cartouche
30920 package API is
30921 Count : Integer := 0;
30922 function Factorial (Val : Integer) return Integer;
30923
30924 procedure Initialize_API;
30925 procedure Finalize_API;
30926 -- Initialization and Finalization routines.
30927 end API;
30928 @end cartouche
30929 @end group
30930 @end smallexample
30931
30932 @smallexample @c ada
30933 @group
30934 @cartouche
30935 package body API is
30936 function Factorial (Val : Integer) return Integer is
30937 Fact : Integer := 1;
30938 begin
30939 Count := Count + 1;
30940 for K in 1 .. Val loop
30941 Fact := Fact * K;
30942 end loop;
30943 return Fact;
30944 end Factorial;
30945
30946 @dots{}
30947 -- The remainder of this package body is unchanged.
30948 end API;
30949 @end cartouche
30950 @end group
30951 @end smallexample
30952
30953 @noindent
30954 Note that if you do not export the Ada entities with a @code{C} or
30955 @code{Stdcall} convention you will have to provide the mangled Ada names
30956 in the definition file of the Ada DLL
30957 (@pxref{Creating the Definition File}).
30958
30959 @node Ada DLLs and Elaboration
30960 @subsection Ada DLLs and Elaboration
30961 @cindex DLLs and elaboration
30962
30963 @noindent
30964 The DLL that you are building contains your Ada code as well as all the
30965 routines in the Ada library that are needed by it. The first thing a
30966 user of your DLL must do is elaborate the Ada code
30967 (@pxref{Elaboration Order Handling in GNAT}).
30968
30969 To achieve this you must export an initialization routine
30970 (@code{Initialize_API} in the previous example), which must be invoked
30971 before using any of the DLL services. This elaboration routine must call
30972 the Ada elaboration routine @code{adainit} generated by the GNAT binder
30973 (@pxref{Binding with Non-Ada Main Programs}). See the body of
30974 @code{Initialize_Api} for an example. Note that the GNAT binder is
30975 automatically invoked during the DLL build process by the @code{gnatdll}
30976 tool (@pxref{Using gnatdll}).
30977
30978 When a DLL is loaded, Windows systematically invokes a routine called
30979 @code{DllMain}. It would therefore be possible to call @code{adainit}
30980 directly from @code{DllMain} without having to provide an explicit
30981 initialization routine. Unfortunately, it is not possible to call
30982 @code{adainit} from the @code{DllMain} if your program has library level
30983 tasks because access to the @code{DllMain} entry point is serialized by
30984 the system (that is, only a single thread can execute ``through'' it at a
30985 time), which means that the GNAT run time will deadlock waiting for the
30986 newly created task to complete its initialization.
30987
30988 @node Ada DLLs and Finalization
30989 @subsection Ada DLLs and Finalization
30990 @cindex DLLs and finalization
30991
30992 @noindent
30993 When the services of an Ada DLL are no longer needed, the client code should
30994 invoke the DLL finalization routine, if available. The DLL finalization
30995 routine is in charge of releasing all resources acquired by the DLL. In the
30996 case of the Ada code contained in the DLL, this is achieved by calling
30997 routine @code{adafinal} generated by the GNAT binder
30998 (@pxref{Binding with Non-Ada Main Programs}).
30999 See the body of @code{Finalize_Api} for an
31000 example. As already pointed out the GNAT binder is automatically invoked
31001 during the DLL build process by the @code{gnatdll} tool
31002 (@pxref{Using gnatdll}).
31003
31004 @node Creating a Spec for Ada DLLs
31005 @subsection Creating a Spec for Ada DLLs
31006
31007 @noindent
31008 To use the services exported by the Ada DLL from another programming
31009 language (e.g.@: C), you have to translate the specs of the exported Ada
31010 entities in that language. For instance in the case of @code{API.dll},
31011 the corresponding C header file could look like:
31012
31013 @smallexample
31014 @group
31015 @cartouche
31016 extern int *_imp__count;
31017 #define count (*_imp__count)
31018 int factorial (int);
31019 @end cartouche
31020 @end group
31021 @end smallexample
31022
31023 @noindent
31024 It is important to understand that when building an Ada DLL to be used by
31025 other Ada applications, you need two different specs for the packages
31026 contained in the DLL: one for building the DLL and the other for using
31027 the DLL. This is because the @code{DLL} calling convention is needed to
31028 use a variable defined in a DLL, but when building the DLL, the variable
31029 must have either the @code{Ada} or @code{C} calling convention. As an
31030 example consider a DLL comprising the following package @code{API}:
31031
31032 @smallexample @c ada
31033 @group
31034 @cartouche
31035 package API is
31036 Count : Integer := 0;
31037 @dots{}
31038 -- Remainder of the package omitted.
31039 end API;
31040 @end cartouche
31041 @end group
31042 @end smallexample
31043
31044 @noindent
31045 After producing a DLL containing package @code{API}, the spec that
31046 must be used to import @code{API.Count} from Ada code outside of the
31047 DLL is:
31048
31049 @smallexample @c ada
31050 @group
31051 @cartouche
31052 package API is
31053 Count : Integer;
31054 pragma Import (DLL, Count);
31055 end API;
31056 @end cartouche
31057 @end group
31058 @end smallexample
31059
31060 @node Creating the Definition File
31061 @subsection Creating the Definition File
31062
31063 @noindent
31064 The definition file is the last file needed to build the DLL. It lists
31065 the exported symbols. As an example, the definition file for a DLL
31066 containing only package @code{API} (where all the entities are exported
31067 with a @code{C} calling convention) is:
31068
31069 @smallexample
31070 @group
31071 @cartouche
31072 EXPORTS
31073 count
31074 factorial
31075 finalize_api
31076 initialize_api
31077 @end cartouche
31078 @end group
31079 @end smallexample
31080
31081 @noindent
31082 If the @code{C} calling convention is missing from package @code{API},
31083 then the definition file contains the mangled Ada names of the above
31084 entities, which in this case are:
31085
31086 @smallexample
31087 @group
31088 @cartouche
31089 EXPORTS
31090 api__count
31091 api__factorial
31092 api__finalize_api
31093 api__initialize_api
31094 @end cartouche
31095 @end group
31096 @end smallexample
31097
31098 @node Using gnatdll
31099 @subsection Using @code{gnatdll}
31100 @findex gnatdll
31101
31102 @menu
31103 * gnatdll Example::
31104 * gnatdll behind the Scenes::
31105 * Using dlltool::
31106 @end menu
31107
31108 @noindent
31109 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
31110 and non-Ada sources that make up your DLL have been compiled.
31111 @code{gnatdll} is actually in charge of two distinct tasks: build the
31112 static import library for the DLL and the actual DLL. The form of the
31113 @code{gnatdll} command is
31114
31115 @smallexample
31116 @cartouche
31117 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
31118 @c Expanding @ovar macro inline (explanation in macro def comments)
31119 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
31120 @end cartouche
31121 @end smallexample
31122
31123 @noindent
31124 where @var{list-of-files} is a list of ALI and object files. The object
31125 file list must be the exact list of objects corresponding to the non-Ada
31126 sources whose services are to be included in the DLL. The ALI file list
31127 must be the exact list of ALI files for the corresponding Ada sources
31128 whose services are to be included in the DLL. If @var{list-of-files} is
31129 missing, only the static import library is generated.
31130
31131 @noindent
31132 You may specify any of the following switches to @code{gnatdll}:
31133
31134 @table @code
31135 @c @item -a@ovar{address}
31136 @c Expanding @ovar macro inline (explanation in macro def comments)
31137 @item -a@r{[}@var{address}@r{]}
31138 @cindex @option{-a} (@code{gnatdll})
31139 Build a non-relocatable DLL at @var{address}. If @var{address} is not
31140 specified the default address @var{0x11000000} will be used. By default,
31141 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
31142 advise the reader to build relocatable DLL.
31143
31144 @item -b @var{address}
31145 @cindex @option{-b} (@code{gnatdll})
31146 Set the relocatable DLL base address. By default the address is
31147 @code{0x11000000}.
31148
31149 @item -bargs @var{opts}
31150 @cindex @option{-bargs} (@code{gnatdll})
31151 Binder options. Pass @var{opts} to the binder.
31152
31153 @item -d @var{dllfile}
31154 @cindex @option{-d} (@code{gnatdll})
31155 @var{dllfile} is the name of the DLL. This switch must be present for
31156 @code{gnatdll} to do anything. The name of the generated import library is
31157 obtained algorithmically from @var{dllfile} as shown in the following
31158 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
31159 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
31160 by option @option{-e}) is obtained algorithmically from @var{dllfile}
31161 as shown in the following example:
31162 if @var{dllfile} is @code{xyz.dll}, the definition
31163 file used is @code{xyz.def}.
31164
31165 @item -e @var{deffile}
31166 @cindex @option{-e} (@code{gnatdll})
31167 @var{deffile} is the name of the definition file.
31168
31169 @item -g
31170 @cindex @option{-g} (@code{gnatdll})
31171 Generate debugging information. This information is stored in the object
31172 file and copied from there to the final DLL file by the linker,
31173 where it can be read by the debugger. You must use the
31174 @option{-g} switch if you plan on using the debugger or the symbolic
31175 stack traceback.
31176
31177 @item -h
31178 @cindex @option{-h} (@code{gnatdll})
31179 Help mode. Displays @code{gnatdll} switch usage information.
31180
31181 @item -Idir
31182 @cindex @option{-I} (@code{gnatdll})
31183 Direct @code{gnatdll} to search the @var{dir} directory for source and
31184 object files needed to build the DLL.
31185 (@pxref{Search Paths and the Run-Time Library (RTL)}).
31186
31187 @item -k
31188 @cindex @option{-k} (@code{gnatdll})
31189 Removes the @code{@@}@var{nn} suffix from the import library's exported
31190 names, but keeps them for the link names. You must specify this
31191 option if you want to use a @code{Stdcall} function in a DLL for which
31192 the @code{@@}@var{nn} suffix has been removed. This is the case for most
31193 of the Windows NT DLL for example. This option has no effect when
31194 @option{-n} option is specified.
31195
31196 @item -l @var{file}
31197 @cindex @option{-l} (@code{gnatdll})
31198 The list of ALI and object files used to build the DLL are listed in
31199 @var{file}, instead of being given in the command line. Each line in
31200 @var{file} contains the name of an ALI or object file.
31201
31202 @item -n
31203 @cindex @option{-n} (@code{gnatdll})
31204 No Import. Do not create the import library.
31205
31206 @item -q
31207 @cindex @option{-q} (@code{gnatdll})
31208 Quiet mode. Do not display unnecessary messages.
31209
31210 @item -v
31211 @cindex @option{-v} (@code{gnatdll})
31212 Verbose mode. Display extra information.
31213
31214 @item -largs @var{opts}
31215 @cindex @option{-largs} (@code{gnatdll})
31216 Linker options. Pass @var{opts} to the linker.
31217 @end table
31218
31219 @node gnatdll Example
31220 @subsubsection @code{gnatdll} Example
31221
31222 @noindent
31223 As an example the command to build a relocatable DLL from @file{api.adb}
31224 once @file{api.adb} has been compiled and @file{api.def} created is
31225
31226 @smallexample
31227 $ gnatdll -d api.dll api.ali
31228 @end smallexample
31229
31230 @noindent
31231 The above command creates two files: @file{libapi.dll.a} (the import
31232 library) and @file{api.dll} (the actual DLL). If you want to create
31233 only the DLL, just type:
31234
31235 @smallexample
31236 $ gnatdll -d api.dll -n api.ali
31237 @end smallexample
31238
31239 @noindent
31240 Alternatively if you want to create just the import library, type:
31241
31242 @smallexample
31243 $ gnatdll -d api.dll
31244 @end smallexample
31245
31246 @node gnatdll behind the Scenes
31247 @subsubsection @code{gnatdll} behind the Scenes
31248
31249 @noindent
31250 This section details the steps involved in creating a DLL. @code{gnatdll}
31251 does these steps for you. Unless you are interested in understanding what
31252 goes on behind the scenes, you should skip this section.
31253
31254 We use the previous example of a DLL containing the Ada package @code{API},
31255 to illustrate the steps necessary to build a DLL. The starting point is a
31256 set of objects that will make up the DLL and the corresponding ALI
31257 files. In the case of this example this means that @file{api.o} and
31258 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
31259 the following:
31260
31261 @enumerate
31262 @item
31263 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
31264 the information necessary to generate relocation information for the
31265 DLL.
31266
31267 @smallexample
31268 @group
31269 $ gnatbind -n api
31270 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
31271 @end group
31272 @end smallexample
31273
31274 @noindent
31275 In addition to the base file, the @command{gnatlink} command generates an
31276 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
31277 asks @command{gnatlink} to generate the routines @code{DllMain} and
31278 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
31279 is loaded into memory.
31280
31281 @item
31282 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
31283 export table (@file{api.exp}). The export table contains the relocation
31284 information in a form which can be used during the final link to ensure
31285 that the Windows loader is able to place the DLL anywhere in memory.
31286
31287 @smallexample
31288 @group
31289 $ dlltool --dllname api.dll --def api.def --base-file api.base \
31290 --output-exp api.exp
31291 @end group
31292 @end smallexample
31293
31294 @item
31295 @code{gnatdll} builds the base file using the new export table. Note that
31296 @command{gnatbind} must be called once again since the binder generated file
31297 has been deleted during the previous call to @command{gnatlink}.
31298
31299 @smallexample
31300 @group
31301 $ gnatbind -n api
31302 $ gnatlink api -o api.jnk api.exp -mdll
31303 -Wl,--base-file,api.base
31304 @end group
31305 @end smallexample
31306
31307 @item
31308 @code{gnatdll} builds the new export table using the new base file and
31309 generates the DLL import library @file{libAPI.dll.a}.
31310
31311 @smallexample
31312 @group
31313 $ dlltool --dllname api.dll --def api.def --base-file api.base \
31314 --output-exp api.exp --output-lib libAPI.a
31315 @end group
31316 @end smallexample
31317
31318 @item
31319 Finally @code{gnatdll} builds the relocatable DLL using the final export
31320 table.
31321
31322 @smallexample
31323 @group
31324 $ gnatbind -n api
31325 $ gnatlink api api.exp -o api.dll -mdll
31326 @end group
31327 @end smallexample
31328 @end enumerate
31329
31330 @node Using dlltool
31331 @subsubsection Using @code{dlltool}
31332
31333 @noindent
31334 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
31335 DLLs and static import libraries. This section summarizes the most
31336 common @code{dlltool} switches. The form of the @code{dlltool} command
31337 is
31338
31339 @smallexample
31340 @c $ dlltool @ovar{switches}
31341 @c Expanding @ovar macro inline (explanation in macro def comments)
31342 $ dlltool @r{[}@var{switches}@r{]}
31343 @end smallexample
31344
31345 @noindent
31346 @code{dlltool} switches include:
31347
31348 @table @option
31349 @item --base-file @var{basefile}
31350 @cindex @option{--base-file} (@command{dlltool})
31351 Read the base file @var{basefile} generated by the linker. This switch
31352 is used to create a relocatable DLL.
31353
31354 @item --def @var{deffile}
31355 @cindex @option{--def} (@command{dlltool})
31356 Read the definition file.
31357
31358 @item --dllname @var{name}
31359 @cindex @option{--dllname} (@command{dlltool})
31360 Gives the name of the DLL. This switch is used to embed the name of the
31361 DLL in the static import library generated by @code{dlltool} with switch
31362 @option{--output-lib}.
31363
31364 @item -k
31365 @cindex @option{-k} (@command{dlltool})
31366 Kill @code{@@}@var{nn} from exported names
31367 (@pxref{Windows Calling Conventions}
31368 for a discussion about @code{Stdcall}-style symbols.
31369
31370 @item --help
31371 @cindex @option{--help} (@command{dlltool})
31372 Prints the @code{dlltool} switches with a concise description.
31373
31374 @item --output-exp @var{exportfile}
31375 @cindex @option{--output-exp} (@command{dlltool})
31376 Generate an export file @var{exportfile}. The export file contains the
31377 export table (list of symbols in the DLL) and is used to create the DLL.
31378
31379 @item --output-lib @var{libfile}
31380 @cindex @option{--output-lib} (@command{dlltool})
31381 Generate a static import library @var{libfile}.
31382
31383 @item -v
31384 @cindex @option{-v} (@command{dlltool})
31385 Verbose mode.
31386
31387 @item --as @var{assembler-name}
31388 @cindex @option{--as} (@command{dlltool})
31389 Use @var{assembler-name} as the assembler. The default is @code{as}.
31390 @end table
31391
31392 @node GNAT and Windows Resources
31393 @section GNAT and Windows Resources
31394 @cindex Resources, windows
31395
31396 @menu
31397 * Building Resources::
31398 * Compiling Resources::
31399 * Using Resources::
31400 @end menu
31401
31402 @noindent
31403 Resources are an easy way to add Windows specific objects to your
31404 application. The objects that can be added as resources include:
31405
31406 @itemize @bullet
31407 @item menus
31408
31409 @item accelerators
31410
31411 @item dialog boxes
31412
31413 @item string tables
31414
31415 @item bitmaps
31416
31417 @item cursors
31418
31419 @item icons
31420
31421 @item fonts
31422
31423 @item version information
31424 @end itemize
31425
31426 For example, a version information resource can be defined as follow and
31427 embedded into an executable or DLL:
31428
31429 A version information resource can be used to embed information into an
31430 executable or a DLL. These information can be viewed using the file properties
31431 from the Windows Explorer. Here is an example of a version information
31432 resource:
31433
31434 @smallexample
31435 @group
31436 1 VERSIONINFO
31437 FILEVERSION 1,0,0,0
31438 PRODUCTVERSION 1,0,0,0
31439 BEGIN
31440 BLOCK "StringFileInfo"
31441 BEGIN
31442 BLOCK "080904E4"
31443 BEGIN
31444 VALUE "CompanyName", "My Company Name"
31445 VALUE "FileDescription", "My application"
31446 VALUE "FileVersion", "1.0"
31447 VALUE "InternalName", "my_app"
31448 VALUE "LegalCopyright", "My Name"
31449 VALUE "OriginalFilename", "my_app.exe"
31450 VALUE "ProductName", "My App"
31451 VALUE "ProductVersion", "1.0"
31452 END
31453 END
31454
31455 BLOCK "VarFileInfo"
31456 BEGIN
31457 VALUE "Translation", 0x809, 1252
31458 END
31459 END
31460 @end group
31461 @end smallexample
31462
31463 The value @code{0809} (langID) is for the U.K English language and
31464 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
31465 multilingual.
31466
31467 @noindent
31468 This section explains how to build, compile and use resources. Note that this
31469 section does not cover all resource objects, for a complete description see
31470 the corresponding Microsoft documentation.
31471
31472 @node Building Resources
31473 @subsection Building Resources
31474 @cindex Resources, building
31475
31476 @noindent
31477 A resource file is an ASCII file. By convention resource files have an
31478 @file{.rc} extension.
31479 The easiest way to build a resource file is to use Microsoft tools
31480 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
31481 @code{dlgedit.exe} to build dialogs.
31482 It is always possible to build an @file{.rc} file yourself by writing a
31483 resource script.
31484
31485 It is not our objective to explain how to write a resource file. A
31486 complete description of the resource script language can be found in the
31487 Microsoft documentation.
31488
31489 @node Compiling Resources
31490 @subsection Compiling Resources
31491 @findex rc
31492 @findex windres
31493 @cindex Resources, compiling
31494
31495 @noindent
31496 This section describes how to build a GNAT-compatible (COFF) object file
31497 containing the resources. This is done using the Resource Compiler
31498 @code{windres} as follows:
31499
31500 @smallexample
31501 $ windres -i myres.rc -o myres.o
31502 @end smallexample
31503
31504 @noindent
31505 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
31506 file. You can specify an alternate preprocessor (usually named
31507 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
31508 parameter. A list of all possible options may be obtained by entering
31509 the command @code{windres} @option{--help}.
31510
31511 It is also possible to use the Microsoft resource compiler @code{rc.exe}
31512 to produce a @file{.res} file (binary resource file). See the
31513 corresponding Microsoft documentation for further details. In this case
31514 you need to use @code{windres} to translate the @file{.res} file to a
31515 GNAT-compatible object file as follows:
31516
31517 @smallexample
31518 $ windres -i myres.res -o myres.o
31519 @end smallexample
31520
31521 @node Using Resources
31522 @subsection Using Resources
31523 @cindex Resources, using
31524
31525 @noindent
31526 To include the resource file in your program just add the
31527 GNAT-compatible object file for the resource(s) to the linker
31528 arguments. With @command{gnatmake} this is done by using the @option{-largs}
31529 option:
31530
31531 @smallexample
31532 $ gnatmake myprog -largs myres.o
31533 @end smallexample
31534
31535 @node Debugging a DLL
31536 @section Debugging a DLL
31537 @cindex DLL debugging
31538
31539 @menu
31540 * Program and DLL Both Built with GCC/GNAT::
31541 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
31542 @end menu
31543
31544 @noindent
31545 Debugging a DLL is similar to debugging a standard program. But
31546 we have to deal with two different executable parts: the DLL and the
31547 program that uses it. We have the following four possibilities:
31548
31549 @enumerate 1
31550 @item
31551 The program and the DLL are built with @code{GCC/GNAT}.
31552 @item
31553 The program is built with foreign tools and the DLL is built with
31554 @code{GCC/GNAT}.
31555 @item
31556 The program is built with @code{GCC/GNAT} and the DLL is built with
31557 foreign tools.
31558 @end enumerate
31559
31560 @noindent
31561 In this section we address only cases one and two above.
31562 There is no point in trying to debug
31563 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
31564 information in it. To do so you must use a debugger compatible with the
31565 tools suite used to build the DLL.
31566
31567 @node Program and DLL Both Built with GCC/GNAT
31568 @subsection Program and DLL Both Built with GCC/GNAT
31569
31570 @noindent
31571 This is the simplest case. Both the DLL and the program have @code{GDB}
31572 compatible debugging information. It is then possible to break anywhere in
31573 the process. Let's suppose here that the main procedure is named
31574 @code{ada_main} and that in the DLL there is an entry point named
31575 @code{ada_dll}.
31576
31577 @noindent
31578 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
31579 program must have been built with the debugging information (see GNAT -g
31580 switch). Here are the step-by-step instructions for debugging it:
31581
31582 @enumerate 1
31583 @item Launch @code{GDB} on the main program.
31584
31585 @smallexample
31586 $ gdb -nw ada_main
31587 @end smallexample
31588
31589 @item Start the program and stop at the beginning of the main procedure
31590
31591 @smallexample
31592 (gdb) start
31593 @end smallexample
31594
31595 @noindent
31596 This step is required to be able to set a breakpoint inside the DLL. As long
31597 as the program is not run, the DLL is not loaded. This has the
31598 consequence that the DLL debugging information is also not loaded, so it is not
31599 possible to set a breakpoint in the DLL.
31600
31601 @item Set a breakpoint inside the DLL
31602
31603 @smallexample
31604 (gdb) break ada_dll
31605 (gdb) cont
31606 @end smallexample
31607
31608 @end enumerate
31609
31610 @noindent
31611 At this stage a breakpoint is set inside the DLL. From there on
31612 you can use the standard approach to debug the whole program
31613 (@pxref{Running and Debugging Ada Programs}).
31614
31615 @ignore
31616 @c This used to work, probably because the DLLs were non-relocatable
31617 @c keep this section around until the problem is sorted out.
31618
31619 To break on the @code{DllMain} routine it is not possible to follow
31620 the procedure above. At the time the program stop on @code{ada_main}
31621 the @code{DllMain} routine as already been called. Either you can use
31622 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
31623
31624 @enumerate 1
31625 @item Launch @code{GDB} on the main program.
31626
31627 @smallexample
31628 $ gdb ada_main
31629 @end smallexample
31630
31631 @item Load DLL symbols
31632
31633 @smallexample
31634 (gdb) add-sym api.dll
31635 @end smallexample
31636
31637 @item Set a breakpoint inside the DLL
31638
31639 @smallexample
31640 (gdb) break ada_dll.adb:45
31641 @end smallexample
31642
31643 Note that at this point it is not possible to break using the routine symbol
31644 directly as the program is not yet running. The solution is to break
31645 on the proper line (break in @file{ada_dll.adb} line 45).
31646
31647 @item Start the program
31648
31649 @smallexample
31650 (gdb) run
31651 @end smallexample
31652
31653 @end enumerate
31654 @end ignore
31655
31656 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
31657 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
31658
31659 @menu
31660 * Debugging the DLL Directly::
31661 * Attaching to a Running Process::
31662 @end menu
31663
31664 @noindent
31665 In this case things are slightly more complex because it is not possible to
31666 start the main program and then break at the beginning to load the DLL and the
31667 associated DLL debugging information. It is not possible to break at the
31668 beginning of the program because there is no @code{GDB} debugging information,
31669 and therefore there is no direct way of getting initial control. This
31670 section addresses this issue by describing some methods that can be used
31671 to break somewhere in the DLL to debug it.
31672
31673 @noindent
31674 First suppose that the main procedure is named @code{main} (this is for
31675 example some C code built with Microsoft Visual C) and that there is a
31676 DLL named @code{test.dll} containing an Ada entry point named
31677 @code{ada_dll}.
31678
31679 @noindent
31680 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
31681 been built with debugging information (see GNAT -g option).
31682
31683 @node Debugging the DLL Directly
31684 @subsubsection Debugging the DLL Directly
31685
31686 @enumerate 1
31687 @item
31688 Find out the executable starting address
31689
31690 @smallexample
31691 $ objdump --file-header main.exe
31692 @end smallexample
31693
31694 The starting address is reported on the last line. For example:
31695
31696 @smallexample
31697 main.exe: file format pei-i386
31698 architecture: i386, flags 0x0000010a:
31699 EXEC_P, HAS_DEBUG, D_PAGED
31700 start address 0x00401010
31701 @end smallexample
31702
31703 @item
31704 Launch the debugger on the executable.
31705
31706 @smallexample
31707 $ gdb main.exe
31708 @end smallexample
31709
31710 @item
31711 Set a breakpoint at the starting address, and launch the program.
31712
31713 @smallexample
31714 $ (gdb) break *0x00401010
31715 $ (gdb) run
31716 @end smallexample
31717
31718 The program will stop at the given address.
31719
31720 @item
31721 Set a breakpoint on a DLL subroutine.
31722
31723 @smallexample
31724 (gdb) break ada_dll.adb:45
31725 @end smallexample
31726
31727 Or if you want to break using a symbol on the DLL, you need first to
31728 select the Ada language (language used by the DLL).
31729
31730 @smallexample
31731 (gdb) set language ada
31732 (gdb) break ada_dll
31733 @end smallexample
31734
31735 @item
31736 Continue the program.
31737
31738 @smallexample
31739 (gdb) cont
31740 @end smallexample
31741
31742 @noindent
31743 This will run the program until it reaches the breakpoint that has been
31744 set. From that point you can use the standard way to debug a program
31745 as described in (@pxref{Running and Debugging Ada Programs}).
31746
31747 @end enumerate
31748
31749 @noindent
31750 It is also possible to debug the DLL by attaching to a running process.
31751
31752 @node Attaching to a Running Process
31753 @subsubsection Attaching to a Running Process
31754 @cindex DLL debugging, attach to process
31755
31756 @noindent
31757 With @code{GDB} it is always possible to debug a running process by
31758 attaching to it. It is possible to debug a DLL this way. The limitation
31759 of this approach is that the DLL must run long enough to perform the
31760 attach operation. It may be useful for instance to insert a time wasting
31761 loop in the code of the DLL to meet this criterion.
31762
31763 @enumerate 1
31764
31765 @item Launch the main program @file{main.exe}.
31766
31767 @smallexample
31768 $ main
31769 @end smallexample
31770
31771 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
31772 that the process PID for @file{main.exe} is 208.
31773
31774 @item Launch gdb.
31775
31776 @smallexample
31777 $ gdb
31778 @end smallexample
31779
31780 @item Attach to the running process to be debugged.
31781
31782 @smallexample
31783 (gdb) attach 208
31784 @end smallexample
31785
31786 @item Load the process debugging information.
31787
31788 @smallexample
31789 (gdb) symbol-file main.exe
31790 @end smallexample
31791
31792 @item Break somewhere in the DLL.
31793
31794 @smallexample
31795 (gdb) break ada_dll
31796 @end smallexample
31797
31798 @item Continue process execution.
31799
31800 @smallexample
31801 (gdb) cont
31802 @end smallexample
31803
31804 @end enumerate
31805
31806 @noindent
31807 This last step will resume the process execution, and stop at
31808 the breakpoint we have set. From there you can use the standard
31809 approach to debug a program as described in
31810 (@pxref{Running and Debugging Ada Programs}).
31811
31812 @node Setting Stack Size from gnatlink
31813 @section Setting Stack Size from @command{gnatlink}
31814
31815 @noindent
31816 It is possible to specify the program stack size at link time. On modern
31817 versions of Windows, starting with XP, this is mostly useful to set the size of
31818 the main stack (environment task). The other task stacks are set with pragma
31819 Storage_Size or with the @command{gnatbind -d} command.
31820
31821 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
31822 reserve size of individual tasks, the link-time stack size applies to all
31823 tasks, and pragma Storage_Size has no effect.
31824 In particular, Stack Overflow checks are made against this
31825 link-time specified size.
31826
31827 This setting can be done with
31828 @command{gnatlink} using either:
31829
31830 @itemize @bullet
31831
31832 @item using @option{-Xlinker} linker option
31833
31834 @smallexample
31835 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
31836 @end smallexample
31837
31838 This sets the stack reserve size to 0x10000 bytes and the stack commit
31839 size to 0x1000 bytes.
31840
31841 @item using @option{-Wl} linker option
31842
31843 @smallexample
31844 $ gnatlink hello -Wl,--stack=0x1000000
31845 @end smallexample
31846
31847 This sets the stack reserve size to 0x1000000 bytes. Note that with
31848 @option{-Wl} option it is not possible to set the stack commit size
31849 because the coma is a separator for this option.
31850
31851 @end itemize
31852
31853 @node Setting Heap Size from gnatlink
31854 @section Setting Heap Size from @command{gnatlink}
31855
31856 @noindent
31857 Under Windows systems, it is possible to specify the program heap size from
31858 @command{gnatlink} using either:
31859
31860 @itemize @bullet
31861
31862 @item using @option{-Xlinker} linker option
31863
31864 @smallexample
31865 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
31866 @end smallexample
31867
31868 This sets the heap reserve size to 0x10000 bytes and the heap commit
31869 size to 0x1000 bytes.
31870
31871 @item using @option{-Wl} linker option
31872
31873 @smallexample
31874 $ gnatlink hello -Wl,--heap=0x1000000
31875 @end smallexample
31876
31877 This sets the heap reserve size to 0x1000000 bytes. Note that with
31878 @option{-Wl} option it is not possible to set the heap commit size
31879 because the coma is a separator for this option.
31880
31881 @end itemize
31882
31883 @node Mac OS Topics
31884 @appendix Mac OS Topics
31885 @cindex OS X
31886
31887 @noindent
31888 This chapter describes topics that are specific to Apple's OS X
31889 platform.
31890
31891 @menu
31892 * Codesigning the Debugger::
31893 @end menu
31894
31895 @node Codesigning the Debugger
31896 @section Codesigning the Debugger
31897
31898 @noindent
31899 The Darwin Kernel requires the debugger to have special permissions
31900 before it is allowed to control other processes. These permissions
31901 are granted by codesigning the GDB executable. Without these
31902 permissions, the debugger will report error messages such as:
31903
31904 @smallexample
31905 Starting program: /x/y/foo
31906 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
31907 (please check gdb is codesigned - see taskgated(8))
31908 @end smallexample
31909
31910 Codesigning requires a certificate. The following procedure explains
31911 how to create one:
31912
31913 @itemize @bullet
31914 @item Start the Keychain Access application (in
31915 /Applications/Utilities/Keychain Access.app)
31916
31917 @item Select the Keychain Access -> Certificate Assistant ->
31918 Create a Certificate... menu
31919
31920 @item Then:
31921
31922 @itemize @bullet
31923 @item Choose a name for the new certificate (this procedure will use
31924 "gdb-cert" as an example)
31925
31926 @item Set "Identity Type" to "Self Signed Root"
31927
31928 @item Set "Certificate Type" to "Code Signing"
31929
31930 @item Activate the "Let me override defaults" option
31931
31932 @end itemize
31933
31934 @item Click several times on "Continue" until the "Specify a Location
31935 For The Certificate" screen appears, then set "Keychain" to "System"
31936
31937 @item Click on "Continue" until the certificate is created
31938
31939 @item Finally, in the view, double-click on the new certificate,
31940 and set "When using this certificate" to "Always Trust"
31941
31942 @item Exit the Keychain Access application and restart the computer
31943 (this is unfortunately required)
31944
31945 @end itemize
31946
31947 Once a certificate has been created, the debugger can be codesigned
31948 as follow. In a Terminal, run the following command...
31949
31950 @smallexample
31951 codesign -f -s "gdb-cert" <gnat_install_prefix>/bin/gdb
31952 @end smallexample
31953
31954 ... where "gdb-cert" should be replaced by the actual certificate
31955 name chosen above, and <gnat_install_prefix> should be replaced by
31956 the location where you installed GNAT.
31957
31958 @c **********************************
31959 @c * GNU Free Documentation License *
31960 @c **********************************
31961 @include fdl.texi
31962 @c GNU Free Documentation License
31963
31964 @node Index
31965 @unnumbered Index
31966
31967 @printindex cp
31968
31969 @contents
31970 @c Put table of contents at end, otherwise it precedes the "title page" in
31971 @c the .txt version
31972 @c Edit the pdf file to move the contents to the beginning, after the title
31973 @c page
31974
31975 @bye