[multiple changes]
[gcc.git] / gcc / ada / gnat_ugn.texi
1 \input texinfo @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c o
6 @c GNAT DOCUMENTATION o
7 @c o
8 @c G N A T _ U G N o
9 @c o
10 @c Copyright (C) 1992-2013, Free Software Foundation, Inc. o
11 @c o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
13
14 @setfilename gnat_ugn.info
15
16 @copying
17 Copyright @copyright{} 1995-2009 Free Software Foundation,
18 Inc.
19
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.3 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24 Texts. A copy of the license is included in the section entitled
25 ``GNU Free Documentation License''.
26 @end copying
27
28 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
29 @c
30 @c GNAT_UGN Style Guide
31 @c
32 @c 1. Always put a @noindent on the line before the first paragraph
33 @c after any of these commands:
34 @c
35 @c @chapter
36 @c @section
37 @c @subsection
38 @c @subsubsection
39 @c @subsubsubsection
40 @c
41 @c @end smallexample
42 @c @end itemize
43 @c @end enumerate
44 @c
45 @c 2. DO NOT use @example. Use @smallexample instead.
46 @c a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
47 @c context. These can interfere with the readability of the texi
48 @c source file. Instead, use one of the following annotated
49 @c @smallexample commands, and preprocess the texi file with the
50 @c ada2texi tool (which generates appropriate highlighting):
51 @c @smallexample @c ada
52 @c @smallexample @c adanocomment
53 @c @smallexample @c projectfile
54 @c b) The "@c ada" markup will result in boldface for reserved words
55 @c and italics for comments
56 @c c) The "@c adanocomment" markup will result only in boldface for
57 @c reserved words (comments are left alone)
58 @c d) The "@c projectfile" markup is like "@c ada" except that the set
59 @c of reserved words include the new reserved words for project files
60 @c
61 @c 3. Each @chapter, @section, @subsection, @subsubsection, etc.
62 @c command must be preceded by two empty lines
63 @c
64 @c 4. The @item command should be on a line of its own if it is in an
65 @c @itemize or @enumerate command.
66 @c
67 @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
68 @c or "ali".
69 @c
70 @c 6. DO NOT put trailing spaces at the end of a line. Such spaces will
71 @c cause the document build to fail.
72 @c
73 @c 7. DO NOT use @cartouche for examples that are longer than around 10 lines.
74 @c This command inhibits page breaks, so long examples in a @cartouche can
75 @c lead to large, ugly patches of empty space on a page.
76 @c
77 @c NOTE: This file should be submitted to xgnatugn with either the vms flag
78 @c or the unw flag set. The unw flag covers topics for both Unix and
79 @c Windows.
80 @c
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
82
83 @set NOW January 2007
84 @c This flag is used where the text refers to conditions that exist when the
85 @c text was entered into the document but which may change over time.
86 @c Update the setting for the flag, and (if necessary) the text surrounding,
87 @c the references to the flag, on future doc revisions:
88 @c search for @value{NOW}.
89
90 @set FSFEDITION
91 @set EDITION GNAT
92
93 @ifset unw
94 @set PLATFORM
95 @set TITLESUFFIX
96 @end ifset
97
98 @ifset vms
99 @set PLATFORM OpenVMS
100 @set TITLESUFFIX for OpenVMS
101 @end ifset
102
103 @c @ovar(ARG)
104 @c ----------
105 @c The ARG is an optional argument. To be used for macro arguments in
106 @c their documentation (@defmac).
107 @macro ovar{varname}
108 @r{[}@var{\varname\}@r{]}@c
109 @end macro
110 @c Status as of November 2009:
111 @c Unfortunately texi2pdf and texi2html treat the trailing "@c"
112 @c differently, and faulty output is produced by one or the other
113 @c depending on whether the "@c" is present or absent.
114 @c As a result, the @ovar macro is not used, and all invocations
115 @c of the @ovar macro have been expanded inline.
116
117
118 @settitle @value{EDITION} User's Guide @value{TITLESUFFIX}
119 @dircategory GNU Ada tools
120 @direntry
121 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
122 @end direntry
123
124 @include gcc-common.texi
125
126 @setchapternewpage odd
127 @syncodeindex fn cp
128 @c %**end of header
129
130 @titlepage
131 @title @value{EDITION} User's Guide
132 @ifset vms
133 @sp 1
134 @flushright
135 @titlefont{@i{@value{PLATFORM}}}
136 @end flushright
137 @end ifset
138
139 @sp 2
140
141 @subtitle GNAT, The GNU Ada Compiler
142 @versionsubtitle
143 @author AdaCore
144
145 @page
146 @vskip 0pt plus 1filll
147
148 @insertcopying
149
150 @end titlepage
151
152 @ifnottex
153 @node Top, About This Guide, (dir), (dir)
154 @top @value{EDITION} User's Guide
155
156 @noindent
157 @value{EDITION} User's Guide @value{PLATFORM}
158
159 @noindent
160 GNAT, The GNU Ada Compiler@*
161 GCC version @value{version-GCC}@*
162
163 @noindent
164 AdaCore@*
165
166 @menu
167 * About This Guide::
168 * Getting Started with GNAT::
169 * The GNAT Compilation Model::
170 * Compiling with gcc::
171 * Binding with gnatbind::
172 * Linking with gnatlink::
173 * The GNAT Make Program gnatmake::
174 * Improving Performance::
175 * Renaming Files with gnatchop::
176 * Configuration Pragmas::
177 * Handling Arbitrary File Naming Conventions with gnatname::
178 * GNAT Project Manager::
179 * Tools Supporting Project Files::
180 * The Cross-Referencing Tools gnatxref and gnatfind::
181 * The GNAT Pretty-Printer gnatpp::
182 @ifclear vms
183 * The Ada-to-XML converter gnat2xml::
184 @end ifclear
185 * The GNAT Metrics Tool gnatmetric::
186 * File Name Krunching with gnatkr::
187 * Preprocessing with gnatprep::
188 * The GNAT Library Browser gnatls::
189 * Cleaning Up with gnatclean::
190 @ifclear vms
191 * GNAT and Libraries::
192 * Using the GNU make Utility::
193 @end ifclear
194 * Memory Management Issues::
195 * Stack Related Facilities::
196 * Verifying Properties with gnatcheck::
197 * Creating Sample Bodies with gnatstub::
198 * Creating Unit Tests with gnattest::
199 * Performing Dimensionality Analysis in GNAT::
200 * Generating Ada Bindings for C and C++ headers::
201 * Other Utility Programs::
202 @ifclear vms
203 * Code Coverage and Profiling::
204 @end ifclear
205 * Running and Debugging Ada Programs::
206 @ifset vms
207 * Compatibility with HP Ada::
208 @end ifset
209 * Platform-Specific Information for the Run-Time Libraries::
210 * Example of Binder Output File::
211 * Elaboration Order Handling in GNAT::
212 * Overflow Check Handling in GNAT::
213 * Conditional Compilation::
214 * Inline Assembler::
215 * Compatibility and Porting Guide::
216 * Microsoft Windows Topics::
217 * Mac OS Topics::
218 * GNU Free Documentation License::
219 * Index::
220 @end menu
221 @end ifnottex
222
223 @node About This Guide
224 @unnumbered About This Guide
225
226 @noindent
227 @ifset vms
228 This guide describes the use of @value{EDITION},
229 a compiler and software development toolset for the full Ada
230 programming language, implemented on OpenVMS for HP's Alpha and
231 Integrity server (I64) platforms.
232 @end ifset
233 @ifclear vms
234 This guide describes the use of @value{EDITION},
235 a compiler and software development
236 toolset for the full Ada programming language.
237 @end ifclear
238 It documents the features of the compiler and tools, and explains
239 how to use them to build Ada applications.
240
241 @value{EDITION} implements Ada 95, Ada 2005 and Ada 2012, and it may also be
242 invoked in Ada 83 compatibility mode.
243 By default, @value{EDITION} assumes Ada 2012, but you can override with a
244 compiler switch (@pxref{Compiling Different Versions of Ada})
245 to explicitly specify the language version.
246 Throughout this manual, references to ``Ada'' without a year suffix
247 apply to all Ada 95/2005/2012 versions of the language.
248
249 @ifclear FSFEDITION
250 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
251 ``GNAT'' in the remainder of this document.
252 @end ifclear
253
254
255 @menu
256 * What This Guide Contains::
257 * What You Should Know before Reading This Guide::
258 * Related Information::
259 * Conventions::
260 @end menu
261
262 @node What This Guide Contains
263 @unnumberedsec What This Guide Contains
264
265 @noindent
266 This guide contains the following chapters:
267 @itemize @bullet
268
269 @item
270 @ref{Getting Started with GNAT}, describes how to get started compiling
271 and running Ada programs with the GNAT Ada programming environment.
272 @item
273 @ref{The GNAT Compilation Model}, describes the compilation model used
274 by GNAT.
275
276 @item
277 @ref{Compiling with gcc}, describes how to compile
278 Ada programs with @command{gcc}, the Ada compiler.
279
280 @item
281 @ref{Binding with gnatbind}, describes how to
282 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
283 utility.
284
285 @item
286 @ref{Linking with gnatlink},
287 describes @command{gnatlink}, a
288 program that provides for linking using the GNAT run-time library to
289 construct a program. @command{gnatlink} can also incorporate foreign language
290 object units into the executable.
291
292 @item
293 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
294 utility that automatically determines the set of sources
295 needed by an Ada compilation unit, and executes the necessary compilations
296 binding and link.
297
298 @item
299 @ref{Improving Performance}, shows various techniques for making your
300 Ada program run faster or take less space.
301 It discusses the effect of the compiler's optimization switch and
302 also describes the @command{gnatelim} tool and unused subprogram/data
303 elimination.
304
305 @item
306 @ref{Renaming Files with gnatchop}, describes
307 @code{gnatchop}, a utility that allows you to preprocess a file that
308 contains Ada source code, and split it into one or more new files, one
309 for each compilation unit.
310
311 @item
312 @ref{Configuration Pragmas}, describes the configuration pragmas
313 handled by GNAT.
314
315 @item
316 @ref{Handling Arbitrary File Naming Conventions with gnatname},
317 shows how to override the default GNAT file naming conventions,
318 either for an individual unit or globally.
319
320 @item
321 @ref{GNAT Project Manager}, describes how to use project files
322 to organize large projects.
323
324 @item
325 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
326 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
327 way to navigate through sources.
328
329 @item
330 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
331 version of an Ada source file with control over casing, indentation,
332 comment placement, and other elements of program presentation style.
333
334 @ifclear vms
335 @item
336 @ref{The Ada-to-XML converter gnat2xml}, shows how to convert Ada
337 source code into XML.
338 @end ifclear
339
340 @item
341 @ref{The GNAT Metrics Tool gnatmetric}, shows how to compute various
342 metrics for an Ada source file, such as the number of types and subprograms,
343 and assorted complexity measures.
344
345 @item
346 @ref{File Name Krunching with gnatkr}, describes the @code{gnatkr}
347 file name krunching utility, used to handle shortened
348 file names on operating systems with a limit on the length of names.
349
350 @item
351 @ref{Preprocessing with gnatprep}, describes @code{gnatprep}, a
352 preprocessor utility that allows a single source file to be used to
353 generate multiple or parameterized source files by means of macro
354 substitution.
355
356 @item
357 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
358 utility that displays information about compiled units, including dependences
359 on the corresponding sources files, and consistency of compilations.
360
361 @item
362 @ref{Cleaning Up with gnatclean}, describes @code{gnatclean}, a utility
363 to delete files that are produced by the compiler, binder and linker.
364
365 @ifclear vms
366 @item
367 @ref{GNAT and Libraries}, describes the process of creating and using
368 Libraries with GNAT. It also describes how to recompile the GNAT run-time
369 library.
370
371 @item
372 @ref{Using the GNU make Utility}, describes some techniques for using
373 the GNAT toolset in Makefiles.
374 @end ifclear
375
376 @item
377 @ref{Memory Management Issues}, describes some useful predefined storage pools
378 and in particular the GNAT Debug Pool facility, which helps detect incorrect
379 memory references.
380 @ifclear vms
381 It also describes @command{gnatmem}, a utility that monitors dynamic
382 allocation and deallocation and helps detect ``memory leaks''.
383 @end ifclear
384
385 @item
386 @ref{Stack Related Facilities}, describes some useful tools associated with
387 stack checking and analysis.
388
389 @item
390 @ref{Verifying Properties with gnatcheck}, discusses @code{gnatcheck},
391 a utility that checks Ada code against a set of rules.
392
393 @item
394 @ref{Creating Sample Bodies with gnatstub}, discusses @code{gnatstub},
395 a utility that generates empty but compilable bodies for library units.
396
397 @item
398 @ref{Creating Unit Tests with gnattest}, discusses @code{gnattest},
399 a utility that generates unit testing templates for library units.
400
401 @item
402 @ref{Performing Dimensionality Analysis in GNAT}, describes the Ada 2012
403 facilities used in GNAT to declare dimensioned objects, and to verify that
404 uses of these objects are consistent with their given physical dimensions
405 (so that meters cannot be assigned to kilograms, and so on).
406
407 @item
408 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
409 generate automatically Ada bindings from C and C++ headers.
410
411 @item
412 @ref{Other Utility Programs}, discusses several other GNAT utilities,
413 including @code{gnathtml}.
414
415 @ifclear vms
416 @item
417 @ref{Code Coverage and Profiling}, describes how to perform a structural
418 coverage and profile the execution of Ada programs.
419 @end ifclear
420
421 @item
422 @ref{Running and Debugging Ada Programs}, describes how to run and debug
423 Ada programs.
424
425 @ifset vms
426 @item
427 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
428 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
429 developed by Digital Equipment Corporation and currently supported by HP.}
430 for OpenVMS Alpha. This product was formerly known as DEC Ada,
431 @cindex DEC Ada
432 and for
433 historical compatibility reasons, the relevant libraries still use the
434 DEC prefix.
435 @end ifset
436
437 @item
438 @ref{Platform-Specific Information for the Run-Time Libraries},
439 describes the various run-time
440 libraries supported by GNAT on various platforms and explains how to
441 choose a particular library.
442
443 @item
444 @ref{Example of Binder Output File}, shows the source code for the binder
445 output file for a sample program.
446
447 @item
448 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
449 you deal with elaboration order issues.
450
451 @item
452 @ref{Overflow Check Handling in GNAT}, describes how GNAT helps
453 you deal with arithmetic overflow issues.
454
455 @item
456 @ref{Conditional Compilation}, describes how to model conditional compilation,
457 both with Ada in general and with GNAT facilities in particular.
458
459 @item
460 @ref{Inline Assembler}, shows how to use the inline assembly facility
461 in an Ada program.
462
463 @item
464 @ref{Compatibility and Porting Guide}, contains sections on compatibility
465 of GNAT with other Ada development environments (including Ada 83 systems),
466 to assist in porting code from those environments.
467
468 @ifset unw
469 @item
470 @ref{Microsoft Windows Topics}, presents information relevant to the
471 Microsoft Windows platform.
472
473 @item
474 @ref{Mac OS Topics}, presents information relevant to Apple's OS X
475 platform.
476 @end ifset
477 @end itemize
478
479 @c *************************************************
480 @node What You Should Know before Reading This Guide
481 @c *************************************************
482 @unnumberedsec What You Should Know before Reading This Guide
483
484 @cindex Ada 95 Language Reference Manual
485 @cindex Ada 2005 Language Reference Manual
486 @noindent
487 This guide assumes a basic familiarity with the Ada 95 language, as
488 described in the International Standard ANSI/ISO/IEC-8652:1995, January
489 1995.
490 It does not require knowledge of the new features introduced by Ada 2005,
491 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
492 and Amendment 1).
493 Both reference manuals are included in the GNAT documentation
494 package.
495
496 @node Related Information
497 @unnumberedsec Related Information
498
499 @noindent
500 For further information about related tools, refer to the following
501 documents:
502
503 @itemize @bullet
504 @item
505 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
506 Reference Manual}, which contains all reference material for the GNAT
507 implementation of Ada.
508
509 @ifset unw
510 @item
511 @cite{Using the GNAT Programming Studio}, which describes the GPS
512 Integrated Development Environment.
513
514 @item
515 @cite{GNAT Programming Studio Tutorial}, which introduces the
516 main GPS features through examples.
517 @end ifset
518
519 @item
520 @cite{Ada 95 Reference Manual}, which contains reference
521 material for the Ada 95 programming language.
522
523 @item
524 @cite{Ada 2005 Reference Manual}, which contains reference
525 material for the Ada 2005 programming language.
526
527 @item
528 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
529 @ifset vms
530 in the GNU:[DOCS] directory,
531 @end ifset
532 for all details on the use of the GNU source-level debugger.
533
534 @item
535 @xref{Top,, The extensible self-documenting text editor, emacs,
536 GNU Emacs Manual},
537 @ifset vms
538 located in the GNU:[DOCS] directory if the EMACS kit is installed,
539 @end ifset
540 for full information on the extensible editor and programming
541 environment Emacs.
542
543 @end itemize
544
545 @c **************
546 @node Conventions
547 @unnumberedsec Conventions
548 @cindex Conventions
549 @cindex Typographical conventions
550
551 @noindent
552 Following are examples of the typographical and graphic conventions used
553 in this guide:
554
555 @itemize @bullet
556 @item
557 @code{Functions}, @command{utility program names}, @code{standard names},
558 and @code{classes}.
559
560 @item
561 @option{Option flags}
562
563 @item
564 @file{File names}, @samp{button names}, and @samp{field names}.
565
566 @item
567 @code{Variables}, @env{environment variables}, and @var{metasyntactic
568 variables}.
569
570 @item
571 @emph{Emphasis}.
572
573 @item
574 @r{[}optional information or parameters@r{]}
575
576 @item
577 Examples are described by text
578 @smallexample
579 and then shown this way.
580 @end smallexample
581 @end itemize
582
583 @noindent
584 Commands that are entered by the user are preceded in this manual by the
585 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
586 uses this sequence as a prompt, then the commands will appear exactly as
587 you see them in the manual. If your system uses some other prompt, then
588 the command will appear with the @code{$} replaced by whatever prompt
589 character you are using.
590
591 @ifset unw
592 Full file names are shown with the ``@code{/}'' character
593 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
594 If you are using GNAT on a Windows platform, please note that
595 the ``@code{\}'' character should be used instead.
596 @end ifset
597
598 @c ****************************
599 @node Getting Started with GNAT
600 @chapter Getting Started with GNAT
601
602 @noindent
603 This chapter describes some simple ways of using GNAT to build
604 executable Ada programs.
605 @ifset unw
606 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
607 show how to use the command line environment.
608 @ref{Introduction to GPS}, provides a brief
609 introduction to the GNAT Programming Studio, a visually-oriented
610 Integrated Development Environment for GNAT.
611 GPS offers a graphical ``look and feel'', support for development in
612 other programming languages, comprehensive browsing features, and
613 many other capabilities.
614 For information on GPS please refer to
615 @cite{Using the GNAT Programming Studio}.
616 @end ifset
617
618 @menu
619 * Running GNAT::
620 * Running a Simple Ada Program::
621 * Running a Program with Multiple Units::
622 * Using the gnatmake Utility::
623 @ifset vms
624 * Editing with Emacs::
625 @end ifset
626 @ifclear vms
627 * Introduction to GPS::
628 @end ifclear
629 @end menu
630
631 @node Running GNAT
632 @section Running GNAT
633
634 @noindent
635 Three steps are needed to create an executable file from an Ada source
636 file:
637
638 @enumerate
639 @item
640 The source file(s) must be compiled.
641 @item
642 The file(s) must be bound using the GNAT binder.
643 @item
644 All appropriate object files must be linked to produce an executable.
645 @end enumerate
646
647 @noindent
648 All three steps are most commonly handled by using the @command{gnatmake}
649 utility program that, given the name of the main program, automatically
650 performs the necessary compilation, binding and linking steps.
651
652 @node Running a Simple Ada Program
653 @section Running a Simple Ada Program
654
655 @noindent
656 Any text editor may be used to prepare an Ada program.
657 (If @code{Emacs} is
658 used, the optional Ada mode may be helpful in laying out the program.)
659 The
660 program text is a normal text file. We will assume in our initial
661 example that you have used your editor to prepare the following
662 standard format text file:
663
664 @smallexample @c ada
665 @cartouche
666 with Ada.Text_IO; use Ada.Text_IO;
667 procedure Hello is
668 begin
669 Put_Line ("Hello WORLD!");
670 end Hello;
671 @end cartouche
672 @end smallexample
673
674 @noindent
675 This file should be named @file{hello.adb}.
676 With the normal default file naming conventions, GNAT requires
677 that each file
678 contain a single compilation unit whose file name is the
679 unit name,
680 with periods replaced by hyphens; the
681 extension is @file{ads} for a
682 spec and @file{adb} for a body.
683 You can override this default file naming convention by use of the
684 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
685 Alternatively, if you want to rename your files according to this default
686 convention, which is probably more convenient if you will be using GNAT
687 for all your compilations, then the @code{gnatchop} utility
688 can be used to generate correctly-named source files
689 (@pxref{Renaming Files with gnatchop}).
690
691 You can compile the program using the following command (@code{$} is used
692 as the command prompt in the examples in this document):
693
694 @smallexample
695 $ gcc -c hello.adb
696 @end smallexample
697
698 @noindent
699 @command{gcc} is the command used to run the compiler. This compiler is
700 capable of compiling programs in several languages, including Ada and
701 C. It assumes that you have given it an Ada program if the file extension is
702 either @file{.ads} or @file{.adb}, and it will then call
703 the GNAT compiler to compile the specified file.
704
705 @ifclear vms
706 The @option{-c} switch is required. It tells @command{gcc} to only do a
707 compilation. (For C programs, @command{gcc} can also do linking, but this
708 capability is not used directly for Ada programs, so the @option{-c}
709 switch must always be present.)
710 @end ifclear
711
712 This compile command generates a file
713 @file{hello.o}, which is the object
714 file corresponding to your Ada program. It also generates
715 an ``Ada Library Information'' file @file{hello.ali},
716 which contains additional information used to check
717 that an Ada program is consistent.
718 To build an executable file,
719 use @code{gnatbind} to bind the program
720 and @command{gnatlink} to link it. The
721 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
722 @file{ALI} file, but the default extension of @file{.ali} can
723 be omitted. This means that in the most common case, the argument
724 is simply the name of the main program:
725
726 @smallexample
727 $ gnatbind hello
728 $ gnatlink hello
729 @end smallexample
730
731 @noindent
732 A simpler method of carrying out these steps is to use
733 @command{gnatmake},
734 a master program that invokes all the required
735 compilation, binding and linking tools in the correct order. In particular,
736 @command{gnatmake} automatically recompiles any sources that have been
737 modified since they were last compiled, or sources that depend
738 on such modified sources, so that ``version skew'' is avoided.
739 @cindex Version skew (avoided by @command{gnatmake})
740
741 @smallexample
742 $ gnatmake hello.adb
743 @end smallexample
744
745 @noindent
746 The result is an executable program called @file{hello}, which can be
747 run by entering:
748
749 @smallexample
750 $ ^hello^RUN HELLO^
751 @end smallexample
752
753 @noindent
754 assuming that the current directory is on the search path
755 for executable programs.
756
757 @noindent
758 and, if all has gone well, you will see
759
760 @smallexample
761 Hello WORLD!
762 @end smallexample
763
764 @noindent
765 appear in response to this command.
766
767 @c ****************************************
768 @node Running a Program with Multiple Units
769 @section Running a Program with Multiple Units
770
771 @noindent
772 Consider a slightly more complicated example that has three files: a
773 main program, and the spec and body of a package:
774
775 @smallexample @c ada
776 @cartouche
777 @group
778 package Greetings is
779 procedure Hello;
780 procedure Goodbye;
781 end Greetings;
782
783 with Ada.Text_IO; use Ada.Text_IO;
784 package body Greetings is
785 procedure Hello is
786 begin
787 Put_Line ("Hello WORLD!");
788 end Hello;
789
790 procedure Goodbye is
791 begin
792 Put_Line ("Goodbye WORLD!");
793 end Goodbye;
794 end Greetings;
795 @end group
796
797 @group
798 with Greetings;
799 procedure Gmain is
800 begin
801 Greetings.Hello;
802 Greetings.Goodbye;
803 end Gmain;
804 @end group
805 @end cartouche
806 @end smallexample
807
808 @noindent
809 Following the one-unit-per-file rule, place this program in the
810 following three separate files:
811
812 @table @file
813 @item greetings.ads
814 spec of package @code{Greetings}
815
816 @item greetings.adb
817 body of package @code{Greetings}
818
819 @item gmain.adb
820 body of main program
821 @end table
822
823 @noindent
824 To build an executable version of
825 this program, we could use four separate steps to compile, bind, and link
826 the program, as follows:
827
828 @smallexample
829 $ gcc -c gmain.adb
830 $ gcc -c greetings.adb
831 $ gnatbind gmain
832 $ gnatlink gmain
833 @end smallexample
834
835 @noindent
836 Note that there is no required order of compilation when using GNAT.
837 In particular it is perfectly fine to compile the main program first.
838 Also, it is not necessary to compile package specs in the case where
839 there is an accompanying body; you only need to compile the body. If you want
840 to submit these files to the compiler for semantic checking and not code
841 generation, then use the
842 @option{-gnatc} switch:
843
844 @smallexample
845 $ gcc -c greetings.ads -gnatc
846 @end smallexample
847
848 @noindent
849 Although the compilation can be done in separate steps as in the
850 above example, in practice it is almost always more convenient
851 to use the @command{gnatmake} tool. All you need to know in this case
852 is the name of the main program's source file. The effect of the above four
853 commands can be achieved with a single one:
854
855 @smallexample
856 $ gnatmake gmain.adb
857 @end smallexample
858
859 @noindent
860 In the next section we discuss the advantages of using @command{gnatmake} in
861 more detail.
862
863 @c *****************************
864 @node Using the gnatmake Utility
865 @section Using the @command{gnatmake} Utility
866
867 @noindent
868 If you work on a program by compiling single components at a time using
869 @command{gcc}, you typically keep track of the units you modify. In order to
870 build a consistent system, you compile not only these units, but also any
871 units that depend on the units you have modified.
872 For example, in the preceding case,
873 if you edit @file{gmain.adb}, you only need to recompile that file. But if
874 you edit @file{greetings.ads}, you must recompile both
875 @file{greetings.adb} and @file{gmain.adb}, because both files contain
876 units that depend on @file{greetings.ads}.
877
878 @code{gnatbind} will warn you if you forget one of these compilation
879 steps, so that it is impossible to generate an inconsistent program as a
880 result of forgetting to do a compilation. Nevertheless it is tedious and
881 error-prone to keep track of dependencies among units.
882 One approach to handle the dependency-bookkeeping is to use a
883 makefile. However, makefiles present maintenance problems of their own:
884 if the dependencies change as you change the program, you must make
885 sure that the makefile is kept up-to-date manually, which is also an
886 error-prone process.
887
888 The @command{gnatmake} utility takes care of these details automatically.
889 Invoke it using either one of the following forms:
890
891 @smallexample
892 $ gnatmake gmain.adb
893 $ gnatmake ^gmain^GMAIN^
894 @end smallexample
895
896 @noindent
897 The argument is the name of the file containing the main program;
898 you may omit the extension. @command{gnatmake}
899 examines the environment, automatically recompiles any files that need
900 recompiling, and binds and links the resulting set of object files,
901 generating the executable file, @file{^gmain^GMAIN.EXE^}.
902 In a large program, it
903 can be extremely helpful to use @command{gnatmake}, because working out by hand
904 what needs to be recompiled can be difficult.
905
906 Note that @command{gnatmake}
907 takes into account all the Ada rules that
908 establish dependencies among units. These include dependencies that result
909 from inlining subprogram bodies, and from
910 generic instantiation. Unlike some other
911 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
912 found by the compiler on a previous compilation, which may possibly
913 be wrong when sources change. @command{gnatmake} determines the exact set of
914 dependencies from scratch each time it is run.
915
916 @ifset vms
917 @node Editing with Emacs
918 @section Editing with Emacs
919 @cindex Emacs
920
921 @noindent
922 Emacs is an extensible self-documenting text editor that is available in a
923 separate VMSINSTAL kit.
924
925 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
926 click on the Emacs Help menu and run the Emacs Tutorial.
927 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
928 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
929
930 Documentation on Emacs and other tools is available in Emacs under the
931 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
932 use the middle mouse button to select a topic (e.g.@: Emacs).
933
934 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
935 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
936 get to the Emacs manual.
937 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
938 prompt.
939
940 The tutorial is highly recommended in order to learn the intricacies of Emacs,
941 which is sufficiently extensible to provide for a complete programming
942 environment and shell for the sophisticated user.
943 @end ifset
944
945 @ifclear vms
946 @node Introduction to GPS
947 @section Introduction to GPS
948 @cindex GPS (GNAT Programming Studio)
949 @cindex GNAT Programming Studio (GPS)
950 @noindent
951 Although the command line interface (@command{gnatmake}, etc.) alone
952 is sufficient, a graphical Interactive Development
953 Environment can make it easier for you to compose, navigate, and debug
954 programs. This section describes the main features of GPS
955 (``GNAT Programming Studio''), the GNAT graphical IDE.
956 You will see how to use GPS to build and debug an executable, and
957 you will also learn some of the basics of the GNAT ``project'' facility.
958
959 GPS enables you to do much more than is presented here;
960 e.g., you can produce a call graph, interface to a third-party
961 Version Control System, and inspect the generated assembly language
962 for a program.
963 Indeed, GPS also supports languages other than Ada.
964 Such additional information, and an explanation of all of the GPS menu
965 items. may be found in the on-line help, which includes
966 a user's guide and a tutorial (these are also accessible from the GNAT
967 startup menu).
968
969 @menu
970 * Building a New Program with GPS::
971 * Simple Debugging with GPS::
972 @end menu
973
974 @node Building a New Program with GPS
975 @subsection Building a New Program with GPS
976 @noindent
977 GPS invokes the GNAT compilation tools using information
978 contained in a @emph{project} (also known as a @emph{project file}):
979 a collection of properties such
980 as source directories, identities of main subprograms, tool switches, etc.,
981 and their associated values.
982 See @ref{GNAT Project Manager} for details.
983 In order to run GPS, you will need to either create a new project
984 or else open an existing one.
985
986 This section will explain how you can use GPS to create a project,
987 to associate Ada source files with a project, and to build and run
988 programs.
989
990 @enumerate
991 @item @emph{Creating a project}
992
993 Invoke GPS, either from the command line or the platform's IDE.
994 After it starts, GPS will display a ``Welcome'' screen with three
995 radio buttons:
996
997 @itemize @bullet
998 @item
999 @code{Start with default project in directory}
1000
1001 @item
1002 @code{Create new project with wizard}
1003
1004 @item
1005 @code{Open existing project}
1006 @end itemize
1007
1008 @noindent
1009 Select @code{Create new project with wizard} and press @code{OK}.
1010 A new window will appear. In the text box labeled with
1011 @code{Enter the name of the project to create}, type @file{sample}
1012 as the project name.
1013 In the next box, browse to choose the directory in which you
1014 would like to create the project file.
1015 After selecting an appropriate directory, press @code{Forward}.
1016
1017 A window will appear with the title
1018 @code{Version Control System Configuration}.
1019 Simply press @code{Forward}.
1020
1021 A window will appear with the title
1022 @code{Please select the source directories for this project}.
1023 The directory that you specified for the project file will be selected
1024 by default as the one to use for sources; simply press @code{Forward}.
1025
1026 A window will appear with the title
1027 @code{Please select the build directory for this project}.
1028 The directory that you specified for the project file will be selected
1029 by default for object files and executables;
1030 simply press @code{Forward}.
1031
1032 A window will appear with the title
1033 @code{Please select the main units for this project}.
1034 You will supply this information later, after creating the source file.
1035 Simply press @code{Forward} for now.
1036
1037 A window will appear with the title
1038 @code{Please select the switches to build the project}.
1039 Press @code{Apply}. This will create a project file named
1040 @file{sample.prj} in the directory that you had specified.
1041
1042 @item @emph{Creating and saving the source file}
1043
1044 After you create the new project, a GPS window will appear, which is
1045 partitioned into two main sections:
1046
1047 @itemize @bullet
1048 @item
1049 A @emph{Workspace area}, initially greyed out, which you will use for
1050 creating and editing source files
1051
1052 @item
1053 Directly below, a @emph{Messages area}, which initially displays a
1054 ``Welcome'' message.
1055 (If the Messages area is not visible, drag its border upward to expand it.)
1056 @end itemize
1057
1058 @noindent
1059 Select @code{File} on the menu bar, and then the @code{New} command.
1060 The Workspace area will become white, and you can now
1061 enter the source program explicitly.
1062 Type the following text
1063
1064 @smallexample @c ada
1065 @group
1066 with Ada.Text_IO; use Ada.Text_IO;
1067 procedure Hello is
1068 begin
1069 Put_Line("Hello from GPS!");
1070 end Hello;
1071 @end group
1072 @end smallexample
1073
1074 @noindent
1075 Select @code{File}, then @code{Save As}, and enter the source file name
1076 @file{hello.adb}.
1077 The file will be saved in the same directory you specified as the
1078 location of the default project file.
1079
1080 @item @emph{Updating the project file}
1081
1082 You need to add the new source file to the project.
1083 To do this, select
1084 the @code{Project} menu and then @code{Edit project properties}.
1085 Click the @code{Main files} tab on the left, and then the
1086 @code{Add} button.
1087 Choose @file{hello.adb} from the list, and press @code{Open}.
1088 The project settings window will reflect this action.
1089 Click @code{OK}.
1090
1091 @item @emph{Building and running the program}
1092
1093 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1094 and select @file{hello.adb}.
1095 The Messages window will display the resulting invocations of @command{gcc},
1096 @command{gnatbind}, and @command{gnatlink}
1097 (reflecting the default switch settings from the
1098 project file that you created) and then a ``successful compilation/build''
1099 message.
1100
1101 To run the program, choose the @code{Build} menu, then @code{Run}, and
1102 select @command{hello}.
1103 An @emph{Arguments Selection} window will appear.
1104 There are no command line arguments, so just click @code{OK}.
1105
1106 The Messages window will now display the program's output (the string
1107 @code{Hello from GPS}), and at the bottom of the GPS window a status
1108 update is displayed (@code{Run: hello}).
1109 Close the GPS window (or select @code{File}, then @code{Exit}) to
1110 terminate this GPS session.
1111 @end enumerate
1112
1113 @node Simple Debugging with GPS
1114 @subsection Simple Debugging with GPS
1115 @noindent
1116 This section illustrates basic debugging techniques (setting breakpoints,
1117 examining/modifying variables, single stepping).
1118
1119 @enumerate
1120 @item @emph{Opening a project}
1121
1122 Start GPS and select @code{Open existing project}; browse to
1123 specify the project file @file{sample.prj} that you had created in the
1124 earlier example.
1125
1126 @item @emph{Creating a source file}
1127
1128 Select @code{File}, then @code{New}, and type in the following program:
1129
1130 @smallexample @c ada
1131 @group
1132 with Ada.Text_IO; use Ada.Text_IO;
1133 procedure Example is
1134 Line : String (1..80);
1135 N : Natural;
1136 begin
1137 Put_Line("Type a line of text at each prompt; an empty line to exit");
1138 loop
1139 Put(": ");
1140 Get_Line (Line, N);
1141 Put_Line (Line (1..N) );
1142 exit when N=0;
1143 end loop;
1144 end Example;
1145 @end group
1146 @end smallexample
1147
1148 @noindent
1149 Select @code{File}, then @code{Save as}, and enter the file name
1150 @file{example.adb}.
1151
1152 @item @emph{Updating the project file}
1153
1154 Add @code{Example} as a new main unit for the project:
1155 @enumerate a
1156 @item
1157 Select @code{Project}, then @code{Edit Project Properties}.
1158
1159 @item
1160 Select the @code{Main files} tab, click @code{Add}, then
1161 select the file @file{example.adb} from the list, and
1162 click @code{Open}.
1163 You will see the file name appear in the list of main units
1164
1165 @item
1166 Click @code{OK}
1167 @end enumerate
1168
1169 @item @emph{Building/running the executable}
1170
1171 To build the executable
1172 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1173
1174 Run the program to see its effect (in the Messages area).
1175 Each line that you enter is displayed; an empty line will
1176 cause the loop to exit and the program to terminate.
1177
1178 @item @emph{Debugging the program}
1179
1180 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1181 which are required for debugging, are on by default when you create
1182 a new project.
1183 Thus unless you intentionally remove these settings, you will be able
1184 to debug any program that you develop using GPS.
1185
1186 @enumerate a
1187 @item @emph{Initializing}
1188
1189 Select @code{Debug}, then @code{Initialize}, then @file{example}
1190
1191 @item @emph{Setting a breakpoint}
1192
1193 After performing the initialization step, you will observe a small
1194 icon to the right of each line number.
1195 This serves as a toggle for breakpoints; clicking the icon will
1196 set a breakpoint at the corresponding line (the icon will change to
1197 a red circle with an ``x''), and clicking it again
1198 will remove the breakpoint / reset the icon.
1199
1200 For purposes of this example, set a breakpoint at line 10 (the
1201 statement @code{Put_Line@ (Line@ (1..N));}
1202
1203 @item @emph{Starting program execution}
1204
1205 Select @code{Debug}, then @code{Run}. When the
1206 @code{Program Arguments} window appears, click @code{OK}.
1207 A console window will appear; enter some line of text,
1208 e.g.@: @code{abcde}, at the prompt.
1209 The program will pause execution when it gets to the
1210 breakpoint, and the corresponding line is highlighted.
1211
1212 @item @emph{Examining a variable}
1213
1214 Move the mouse over one of the occurrences of the variable @code{N}.
1215 You will see the value (5) displayed, in ``tool tip'' fashion.
1216 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1217 You will see information about @code{N} appear in the @code{Debugger Data}
1218 pane, showing the value as 5.
1219
1220 @item @emph{Assigning a new value to a variable}
1221
1222 Right click on the @code{N} in the @code{Debugger Data} pane, and
1223 select @code{Set value of N}.
1224 When the input window appears, enter the value @code{4} and click
1225 @code{OK}.
1226 This value does not automatically appear in the @code{Debugger Data}
1227 pane; to see it, right click again on the @code{N} in the
1228 @code{Debugger Data} pane and select @code{Update value}.
1229 The new value, 4, will appear in red.
1230
1231 @item @emph{Single stepping}
1232
1233 Select @code{Debug}, then @code{Next}.
1234 This will cause the next statement to be executed, in this case the
1235 call of @code{Put_Line} with the string slice.
1236 Notice in the console window that the displayed string is simply
1237 @code{abcd} and not @code{abcde} which you had entered.
1238 This is because the upper bound of the slice is now 4 rather than 5.
1239
1240 @item @emph{Removing a breakpoint}
1241
1242 Toggle the breakpoint icon at line 10.
1243
1244 @item @emph{Resuming execution from a breakpoint}
1245
1246 Select @code{Debug}, then @code{Continue}.
1247 The program will reach the next iteration of the loop, and
1248 wait for input after displaying the prompt.
1249 This time, just hit the @kbd{Enter} key.
1250 The value of @code{N} will be 0, and the program will terminate.
1251 The console window will disappear.
1252 @end enumerate
1253 @end enumerate
1254 @end ifclear
1255
1256 @node The GNAT Compilation Model
1257 @chapter The GNAT Compilation Model
1258 @cindex GNAT compilation model
1259 @cindex Compilation model
1260
1261 @menu
1262 * Source Representation::
1263 * Foreign Language Representation::
1264 * File Naming Rules::
1265 * Using Other File Names::
1266 * Alternative File Naming Schemes::
1267 * Generating Object Files::
1268 * Source Dependencies::
1269 * The Ada Library Information Files::
1270 * Binding an Ada Program::
1271 * Mixed Language Programming::
1272 @ifclear vms
1273 * Building Mixed Ada & C++ Programs::
1274 * Comparison between GNAT and C/C++ Compilation Models::
1275 @end ifclear
1276 * Comparison between GNAT and Conventional Ada Library Models::
1277 @ifset vms
1278 * Placement of temporary files::
1279 @end ifset
1280 @end menu
1281
1282 @noindent
1283 This chapter describes the compilation model used by GNAT. Although
1284 similar to that used by other languages, such as C and C++, this model
1285 is substantially different from the traditional Ada compilation models,
1286 which are based on a library. The model is initially described without
1287 reference to the library-based model. If you have not previously used an
1288 Ada compiler, you need only read the first part of this chapter. The
1289 last section describes and discusses the differences between the GNAT
1290 model and the traditional Ada compiler models. If you have used other
1291 Ada compilers, this section will help you to understand those
1292 differences, and the advantages of the GNAT model.
1293
1294 @node Source Representation
1295 @section Source Representation
1296 @cindex Latin-1
1297
1298 @noindent
1299 Ada source programs are represented in standard text files, using
1300 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1301 7-bit ASCII set, plus additional characters used for
1302 representing foreign languages (@pxref{Foreign Language Representation}
1303 for support of non-USA character sets). The format effector characters
1304 are represented using their standard ASCII encodings, as follows:
1305
1306 @table @code
1307 @item VT
1308 @findex VT
1309 Vertical tab, @code{16#0B#}
1310
1311 @item HT
1312 @findex HT
1313 Horizontal tab, @code{16#09#}
1314
1315 @item CR
1316 @findex CR
1317 Carriage return, @code{16#0D#}
1318
1319 @item LF
1320 @findex LF
1321 Line feed, @code{16#0A#}
1322
1323 @item FF
1324 @findex FF
1325 Form feed, @code{16#0C#}
1326 @end table
1327
1328 @noindent
1329 Source files are in standard text file format. In addition, GNAT will
1330 recognize a wide variety of stream formats, in which the end of
1331 physical lines is marked by any of the following sequences:
1332 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1333 in accommodating files that are imported from other operating systems.
1334
1335 @cindex End of source file
1336 @cindex Source file, end
1337 @findex SUB
1338 The end of a source file is normally represented by the physical end of
1339 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1340 recognized as signalling the end of the source file. Again, this is
1341 provided for compatibility with other operating systems where this
1342 code is used to represent the end of file.
1343
1344 Each file contains a single Ada compilation unit, including any pragmas
1345 associated with the unit. For example, this means you must place a
1346 package declaration (a package @dfn{spec}) and the corresponding body in
1347 separate files. An Ada @dfn{compilation} (which is a sequence of
1348 compilation units) is represented using a sequence of files. Similarly,
1349 you will place each subunit or child unit in a separate file.
1350
1351 @node Foreign Language Representation
1352 @section Foreign Language Representation
1353
1354 @noindent
1355 GNAT supports the standard character sets defined in Ada as well as
1356 several other non-standard character sets for use in localized versions
1357 of the compiler (@pxref{Character Set Control}).
1358 @menu
1359 * Latin-1::
1360 * Other 8-Bit Codes::
1361 * Wide Character Encodings::
1362 @end menu
1363
1364 @node Latin-1
1365 @subsection Latin-1
1366 @cindex Latin-1
1367
1368 @noindent
1369 The basic character set is Latin-1. This character set is defined by ISO
1370 standard 8859, part 1. The lower half (character codes @code{16#00#}
1371 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1372 half is used to represent additional characters. These include extended letters
1373 used by European languages, such as French accents, the vowels with umlauts
1374 used in German, and the extra letter A-ring used in Swedish.
1375
1376 @findex Ada.Characters.Latin_1
1377 For a complete list of Latin-1 codes and their encodings, see the source
1378 file of library unit @code{Ada.Characters.Latin_1} in file
1379 @file{a-chlat1.ads}.
1380 You may use any of these extended characters freely in character or
1381 string literals. In addition, the extended characters that represent
1382 letters can be used in identifiers.
1383
1384 @node Other 8-Bit Codes
1385 @subsection Other 8-Bit Codes
1386
1387 @noindent
1388 GNAT also supports several other 8-bit coding schemes:
1389
1390 @table @asis
1391 @item ISO 8859-2 (Latin-2)
1392 @cindex Latin-2
1393 @cindex ISO 8859-2
1394 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1395 equivalence.
1396
1397 @item ISO 8859-3 (Latin-3)
1398 @cindex Latin-3
1399 @cindex ISO 8859-3
1400 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1401 equivalence.
1402
1403 @item ISO 8859-4 (Latin-4)
1404 @cindex Latin-4
1405 @cindex ISO 8859-4
1406 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1407 equivalence.
1408
1409 @item ISO 8859-5 (Cyrillic)
1410 @cindex ISO 8859-5
1411 @cindex Cyrillic
1412 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1413 lowercase equivalence.
1414
1415 @item ISO 8859-15 (Latin-9)
1416 @cindex ISO 8859-15
1417 @cindex Latin-9
1418 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1419 lowercase equivalence
1420
1421 @item IBM PC (code page 437)
1422 @cindex code page 437
1423 This code page is the normal default for PCs in the U.S. It corresponds
1424 to the original IBM PC character set. This set has some, but not all, of
1425 the extended Latin-1 letters, but these letters do not have the same
1426 encoding as Latin-1. In this mode, these letters are allowed in
1427 identifiers with uppercase and lowercase equivalence.
1428
1429 @item IBM PC (code page 850)
1430 @cindex code page 850
1431 This code page is a modification of 437 extended to include all the
1432 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1433 mode, all these letters are allowed in identifiers with uppercase and
1434 lowercase equivalence.
1435
1436 @item Full Upper 8-bit
1437 Any character in the range 80-FF allowed in identifiers, and all are
1438 considered distinct. In other words, there are no uppercase and lowercase
1439 equivalences in this range. This is useful in conjunction with
1440 certain encoding schemes used for some foreign character sets (e.g.,
1441 the typical method of representing Chinese characters on the PC).
1442
1443 @item No Upper-Half
1444 No upper-half characters in the range 80-FF are allowed in identifiers.
1445 This gives Ada 83 compatibility for identifier names.
1446 @end table
1447
1448 @noindent
1449 For precise data on the encodings permitted, and the uppercase and lowercase
1450 equivalences that are recognized, see the file @file{csets.adb} in
1451 the GNAT compiler sources. You will need to obtain a full source release
1452 of GNAT to obtain this file.
1453
1454 @node Wide Character Encodings
1455 @subsection Wide Character Encodings
1456
1457 @noindent
1458 GNAT allows wide character codes to appear in character and string
1459 literals, and also optionally in identifiers, by means of the following
1460 possible encoding schemes:
1461
1462 @table @asis
1463
1464 @item Hex Coding
1465 In this encoding, a wide character is represented by the following five
1466 character sequence:
1467
1468 @smallexample
1469 ESC a b c d
1470 @end smallexample
1471
1472 @noindent
1473 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1474 characters (using uppercase letters) of the wide character code. For
1475 example, ESC A345 is used to represent the wide character with code
1476 @code{16#A345#}.
1477 This scheme is compatible with use of the full Wide_Character set.
1478
1479 @item Upper-Half Coding
1480 @cindex Upper-Half Coding
1481 The wide character with encoding @code{16#abcd#} where the upper bit is on
1482 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1483 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1484 character, but is not required to be in the upper half. This method can
1485 be also used for shift-JIS or EUC, where the internal coding matches the
1486 external coding.
1487
1488 @item Shift JIS Coding
1489 @cindex Shift JIS Coding
1490 A wide character is represented by a two-character sequence,
1491 @code{16#ab#} and
1492 @code{16#cd#}, with the restrictions described for upper-half encoding as
1493 described above. The internal character code is the corresponding JIS
1494 character according to the standard algorithm for Shift-JIS
1495 conversion. Only characters defined in the JIS code set table can be
1496 used with this encoding method.
1497
1498 @item EUC Coding
1499 @cindex EUC Coding
1500 A wide character is represented by a two-character sequence
1501 @code{16#ab#} and
1502 @code{16#cd#}, with both characters being in the upper half. The internal
1503 character code is the corresponding JIS character according to the EUC
1504 encoding algorithm. Only characters defined in the JIS code set table
1505 can be used with this encoding method.
1506
1507 @item UTF-8 Coding
1508 A wide character is represented using
1509 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1510 10646-1/Am.2. Depending on the character value, the representation
1511 is a one, two, or three byte sequence:
1512 @smallexample
1513 @iftex
1514 @leftskip=.7cm
1515 @end iftex
1516 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1517 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1518 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1519
1520 @end smallexample
1521
1522 @noindent
1523 where the @var{xxx} bits correspond to the left-padded bits of the
1524 16-bit character value. Note that all lower half ASCII characters
1525 are represented as ASCII bytes and all upper half characters and
1526 other wide characters are represented as sequences of upper-half
1527 (The full UTF-8 scheme allows for encoding 31-bit characters as
1528 6-byte sequences, but in this implementation, all UTF-8 sequences
1529 of four or more bytes length will be treated as illegal).
1530 @item Brackets Coding
1531 In this encoding, a wide character is represented by the following eight
1532 character sequence:
1533
1534 @smallexample
1535 [ " a b c d " ]
1536 @end smallexample
1537
1538 @noindent
1539 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1540 characters (using uppercase letters) of the wide character code. For
1541 example, [``A345''] is used to represent the wide character with code
1542 @code{16#A345#}. It is also possible (though not required) to use the
1543 Brackets coding for upper half characters. For example, the code
1544 @code{16#A3#} can be represented as @code{[``A3'']}.
1545
1546 This scheme is compatible with use of the full Wide_Character set,
1547 and is also the method used for wide character encoding in the standard
1548 ACVC (Ada Compiler Validation Capability) test suite distributions.
1549
1550 @end table
1551
1552 @noindent
1553 Note: Some of these coding schemes do not permit the full use of the
1554 Ada character set. For example, neither Shift JIS, nor EUC allow the
1555 use of the upper half of the Latin-1 set.
1556
1557 @node File Naming Rules
1558 @section File Naming Rules
1559
1560 @noindent
1561 The default file name is determined by the name of the unit that the
1562 file contains. The name is formed by taking the full expanded name of
1563 the unit and replacing the separating dots with hyphens and using
1564 ^lowercase^uppercase^ for all letters.
1565
1566 An exception arises if the file name generated by the above rules starts
1567 with one of the characters
1568 @ifset vms
1569 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1570 @end ifset
1571 @ifclear vms
1572 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1573 @end ifclear
1574 and the second character is a
1575 minus. In this case, the character ^tilde^dollar sign^ is used in place
1576 of the minus. The reason for this special rule is to avoid clashes with
1577 the standard names for child units of the packages System, Ada,
1578 Interfaces, and GNAT, which use the prefixes
1579 @ifset vms
1580 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
1581 @end ifset
1582 @ifclear vms
1583 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
1584 @end ifclear
1585 respectively.
1586
1587 The file extension is @file{.ads} for a spec and
1588 @file{.adb} for a body. The following list shows some
1589 examples of these rules.
1590
1591 @table @file
1592 @item main.ads
1593 Main (spec)
1594 @item main.adb
1595 Main (body)
1596 @item arith_functions.ads
1597 Arith_Functions (package spec)
1598 @item arith_functions.adb
1599 Arith_Functions (package body)
1600 @item func-spec.ads
1601 Func.Spec (child package spec)
1602 @item func-spec.adb
1603 Func.Spec (child package body)
1604 @item main-sub.adb
1605 Sub (subunit of Main)
1606 @item ^a~bad.adb^A$BAD.ADB^
1607 A.Bad (child package body)
1608 @end table
1609
1610 @noindent
1611 Following these rules can result in excessively long
1612 file names if corresponding
1613 unit names are long (for example, if child units or subunits are
1614 heavily nested). An option is available to shorten such long file names
1615 (called file name ``krunching''). This may be particularly useful when
1616 programs being developed with GNAT are to be used on operating systems
1617 with limited file name lengths. @xref{Using gnatkr}.
1618
1619 Of course, no file shortening algorithm can guarantee uniqueness over
1620 all possible unit names; if file name krunching is used, it is your
1621 responsibility to ensure no name clashes occur. Alternatively you
1622 can specify the exact file names that you want used, as described
1623 in the next section. Finally, if your Ada programs are migrating from a
1624 compiler with a different naming convention, you can use the gnatchop
1625 utility to produce source files that follow the GNAT naming conventions.
1626 (For details @pxref{Renaming Files with gnatchop}.)
1627
1628 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
1629 systems, case is not significant. So for example on @code{Windows XP}
1630 if the canonical name is @code{main-sub.adb}, you can use the file name
1631 @code{Main-Sub.adb} instead. However, case is significant for other
1632 operating systems, so for example, if you want to use other than
1633 canonically cased file names on a Unix system, you need to follow
1634 the procedures described in the next section.
1635
1636 @node Using Other File Names
1637 @section Using Other File Names
1638 @cindex File names
1639
1640 @noindent
1641 In the previous section, we have described the default rules used by
1642 GNAT to determine the file name in which a given unit resides. It is
1643 often convenient to follow these default rules, and if you follow them,
1644 the compiler knows without being explicitly told where to find all
1645 the files it needs.
1646
1647 However, in some cases, particularly when a program is imported from
1648 another Ada compiler environment, it may be more convenient for the
1649 programmer to specify which file names contain which units. GNAT allows
1650 arbitrary file names to be used by means of the Source_File_Name pragma.
1651 The form of this pragma is as shown in the following examples:
1652 @cindex Source_File_Name pragma
1653
1654 @smallexample @c ada
1655 @cartouche
1656 pragma Source_File_Name (My_Utilities.Stacks,
1657 Spec_File_Name => "myutilst_a.ada");
1658 pragma Source_File_name (My_Utilities.Stacks,
1659 Body_File_Name => "myutilst.ada");
1660 @end cartouche
1661 @end smallexample
1662
1663 @noindent
1664 As shown in this example, the first argument for the pragma is the unit
1665 name (in this example a child unit). The second argument has the form
1666 of a named association. The identifier
1667 indicates whether the file name is for a spec or a body;
1668 the file name itself is given by a string literal.
1669
1670 The source file name pragma is a configuration pragma, which means that
1671 normally it will be placed in the @file{gnat.adc}
1672 file used to hold configuration
1673 pragmas that apply to a complete compilation environment.
1674 For more details on how the @file{gnat.adc} file is created and used
1675 see @ref{Handling of Configuration Pragmas}.
1676 @cindex @file{gnat.adc}
1677
1678 @ifclear vms
1679 GNAT allows completely arbitrary file names to be specified using the
1680 source file name pragma. However, if the file name specified has an
1681 extension other than @file{.ads} or @file{.adb} it is necessary to use
1682 a special syntax when compiling the file. The name in this case must be
1683 preceded by the special sequence @option{-x} followed by a space and the name
1684 of the language, here @code{ada}, as in:
1685
1686 @smallexample
1687 $ gcc -c -x ada peculiar_file_name.sim
1688 @end smallexample
1689 @end ifclear
1690
1691 @noindent
1692 @command{gnatmake} handles non-standard file names in the usual manner (the
1693 non-standard file name for the main program is simply used as the
1694 argument to gnatmake). Note that if the extension is also non-standard,
1695 then it must be included in the @command{gnatmake} command, it may not
1696 be omitted.
1697
1698 @node Alternative File Naming Schemes
1699 @section Alternative File Naming Schemes
1700 @cindex File naming schemes, alternative
1701 @cindex File names
1702
1703 In the previous section, we described the use of the @code{Source_File_Name}
1704 pragma to allow arbitrary names to be assigned to individual source files.
1705 However, this approach requires one pragma for each file, and especially in
1706 large systems can result in very long @file{gnat.adc} files, and also create
1707 a maintenance problem.
1708
1709 GNAT also provides a facility for specifying systematic file naming schemes
1710 other than the standard default naming scheme previously described. An
1711 alternative scheme for naming is specified by the use of
1712 @code{Source_File_Name} pragmas having the following format:
1713 @cindex Source_File_Name pragma
1714
1715 @smallexample @c ada
1716 pragma Source_File_Name (
1717 Spec_File_Name => FILE_NAME_PATTERN
1718 @r{[},Casing => CASING_SPEC@r{]}
1719 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1720
1721 pragma Source_File_Name (
1722 Body_File_Name => FILE_NAME_PATTERN
1723 @r{[},Casing => CASING_SPEC@r{]}
1724 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1725
1726 pragma Source_File_Name (
1727 Subunit_File_Name => FILE_NAME_PATTERN
1728 @r{[},Casing => CASING_SPEC@r{]}
1729 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1730
1731 FILE_NAME_PATTERN ::= STRING_LITERAL
1732 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1733 @end smallexample
1734
1735 @noindent
1736 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1737 It contains a single asterisk character, and the unit name is substituted
1738 systematically for this asterisk. The optional parameter
1739 @code{Casing} indicates
1740 whether the unit name is to be all upper-case letters, all lower-case letters,
1741 or mixed-case. If no
1742 @code{Casing} parameter is used, then the default is all
1743 ^lower-case^upper-case^.
1744
1745 The optional @code{Dot_Replacement} string is used to replace any periods
1746 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1747 argument is used then separating dots appear unchanged in the resulting
1748 file name.
1749 Although the above syntax indicates that the
1750 @code{Casing} argument must appear
1751 before the @code{Dot_Replacement} argument, but it
1752 is also permissible to write these arguments in the opposite order.
1753
1754 As indicated, it is possible to specify different naming schemes for
1755 bodies, specs, and subunits. Quite often the rule for subunits is the
1756 same as the rule for bodies, in which case, there is no need to give
1757 a separate @code{Subunit_File_Name} rule, and in this case the
1758 @code{Body_File_name} rule is used for subunits as well.
1759
1760 The separate rule for subunits can also be used to implement the rather
1761 unusual case of a compilation environment (e.g.@: a single directory) which
1762 contains a subunit and a child unit with the same unit name. Although
1763 both units cannot appear in the same partition, the Ada Reference Manual
1764 allows (but does not require) the possibility of the two units coexisting
1765 in the same environment.
1766
1767 The file name translation works in the following steps:
1768
1769 @itemize @bullet
1770
1771 @item
1772 If there is a specific @code{Source_File_Name} pragma for the given unit,
1773 then this is always used, and any general pattern rules are ignored.
1774
1775 @item
1776 If there is a pattern type @code{Source_File_Name} pragma that applies to
1777 the unit, then the resulting file name will be used if the file exists. If
1778 more than one pattern matches, the latest one will be tried first, and the
1779 first attempt resulting in a reference to a file that exists will be used.
1780
1781 @item
1782 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1783 for which the corresponding file exists, then the standard GNAT default
1784 naming rules are used.
1785
1786 @end itemize
1787
1788 @noindent
1789 As an example of the use of this mechanism, consider a commonly used scheme
1790 in which file names are all lower case, with separating periods copied
1791 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
1792 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
1793 two pragmas appear:
1794
1795 @smallexample @c ada
1796 pragma Source_File_Name
1797 (Spec_File_Name => "*.1.ada");
1798 pragma Source_File_Name
1799 (Body_File_Name => "*.2.ada");
1800 @end smallexample
1801
1802 @noindent
1803 The default GNAT scheme is actually implemented by providing the following
1804 default pragmas internally:
1805
1806 @smallexample @c ada
1807 pragma Source_File_Name
1808 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
1809 pragma Source_File_Name
1810 (Body_File_Name => "*.adb", Dot_Replacement => "-");
1811 @end smallexample
1812
1813 @noindent
1814 Our final example implements a scheme typically used with one of the
1815 Ada 83 compilers, where the separator character for subunits was ``__''
1816 (two underscores), specs were identified by adding @file{_.ADA}, bodies
1817 by adding @file{.ADA}, and subunits by
1818 adding @file{.SEP}. All file names were
1819 upper case. Child units were not present of course since this was an
1820 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1821 the same double underscore separator for child units.
1822
1823 @smallexample @c ada
1824 pragma Source_File_Name
1825 (Spec_File_Name => "*_.ADA",
1826 Dot_Replacement => "__",
1827 Casing = Uppercase);
1828 pragma Source_File_Name
1829 (Body_File_Name => "*.ADA",
1830 Dot_Replacement => "__",
1831 Casing = Uppercase);
1832 pragma Source_File_Name
1833 (Subunit_File_Name => "*.SEP",
1834 Dot_Replacement => "__",
1835 Casing = Uppercase);
1836 @end smallexample
1837
1838 @node Generating Object Files
1839 @section Generating Object Files
1840
1841 @noindent
1842 An Ada program consists of a set of source files, and the first step in
1843 compiling the program is to generate the corresponding object files.
1844 These are generated by compiling a subset of these source files.
1845 The files you need to compile are the following:
1846
1847 @itemize @bullet
1848 @item
1849 If a package spec has no body, compile the package spec to produce the
1850 object file for the package.
1851
1852 @item
1853 If a package has both a spec and a body, compile the body to produce the
1854 object file for the package. The source file for the package spec need
1855 not be compiled in this case because there is only one object file, which
1856 contains the code for both the spec and body of the package.
1857
1858 @item
1859 For a subprogram, compile the subprogram body to produce the object file
1860 for the subprogram. The spec, if one is present, is as usual in a
1861 separate file, and need not be compiled.
1862
1863 @item
1864 @cindex Subunits
1865 In the case of subunits, only compile the parent unit. A single object
1866 file is generated for the entire subunit tree, which includes all the
1867 subunits.
1868
1869 @item
1870 Compile child units independently of their parent units
1871 (though, of course, the spec of all the ancestor unit must be present in order
1872 to compile a child unit).
1873
1874 @item
1875 @cindex Generics
1876 Compile generic units in the same manner as any other units. The object
1877 files in this case are small dummy files that contain at most the
1878 flag used for elaboration checking. This is because GNAT always handles generic
1879 instantiation by means of macro expansion. However, it is still necessary to
1880 compile generic units, for dependency checking and elaboration purposes.
1881 @end itemize
1882
1883 @noindent
1884 The preceding rules describe the set of files that must be compiled to
1885 generate the object files for a program. Each object file has the same
1886 name as the corresponding source file, except that the extension is
1887 @file{.o} as usual.
1888
1889 You may wish to compile other files for the purpose of checking their
1890 syntactic and semantic correctness. For example, in the case where a
1891 package has a separate spec and body, you would not normally compile the
1892 spec. However, it is convenient in practice to compile the spec to make
1893 sure it is error-free before compiling clients of this spec, because such
1894 compilations will fail if there is an error in the spec.
1895
1896 GNAT provides an option for compiling such files purely for the
1897 purposes of checking correctness; such compilations are not required as
1898 part of the process of building a program. To compile a file in this
1899 checking mode, use the @option{-gnatc} switch.
1900
1901 @node Source Dependencies
1902 @section Source Dependencies
1903
1904 @noindent
1905 A given object file clearly depends on the source file which is compiled
1906 to produce it. Here we are using @dfn{depends} in the sense of a typical
1907 @code{make} utility; in other words, an object file depends on a source
1908 file if changes to the source file require the object file to be
1909 recompiled.
1910 In addition to this basic dependency, a given object may depend on
1911 additional source files as follows:
1912
1913 @itemize @bullet
1914 @item
1915 If a file being compiled @code{with}'s a unit @var{X}, the object file
1916 depends on the file containing the spec of unit @var{X}. This includes
1917 files that are @code{with}'ed implicitly either because they are parents
1918 of @code{with}'ed child units or they are run-time units required by the
1919 language constructs used in a particular unit.
1920
1921 @item
1922 If a file being compiled instantiates a library level generic unit, the
1923 object file depends on both the spec and body files for this generic
1924 unit.
1925
1926 @item
1927 If a file being compiled instantiates a generic unit defined within a
1928 package, the object file depends on the body file for the package as
1929 well as the spec file.
1930
1931 @item
1932 @findex Inline
1933 @cindex @option{-gnatn} switch
1934 If a file being compiled contains a call to a subprogram for which
1935 pragma @code{Inline} applies and inlining is activated with the
1936 @option{-gnatn} switch, the object file depends on the file containing the
1937 body of this subprogram as well as on the file containing the spec. Note
1938 that for inlining to actually occur as a result of the use of this switch,
1939 it is necessary to compile in optimizing mode.
1940
1941 @cindex @option{-gnatN} switch
1942 The use of @option{-gnatN} activates inlining optimization
1943 that is performed by the front end of the compiler. This inlining does
1944 not require that the code generation be optimized. Like @option{-gnatn},
1945 the use of this switch generates additional dependencies.
1946
1947 When using a gcc-based back end (in practice this means using any version
1948 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
1949 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
1950 Historically front end inlining was more extensive than the gcc back end
1951 inlining, but that is no longer the case.
1952
1953 @item
1954 If an object file @file{O} depends on the proper body of a subunit through
1955 inlining or instantiation, it depends on the parent unit of the subunit.
1956 This means that any modification of the parent unit or one of its subunits
1957 affects the compilation of @file{O}.
1958
1959 @item
1960 The object file for a parent unit depends on all its subunit body files.
1961
1962 @item
1963 The previous two rules meant that for purposes of computing dependencies and
1964 recompilation, a body and all its subunits are treated as an indivisible whole.
1965
1966 @noindent
1967 These rules are applied transitively: if unit @code{A} @code{with}'s
1968 unit @code{B}, whose elaboration calls an inlined procedure in package
1969 @code{C}, the object file for unit @code{A} will depend on the body of
1970 @code{C}, in file @file{c.adb}.
1971
1972 The set of dependent files described by these rules includes all the
1973 files on which the unit is semantically dependent, as dictated by the
1974 Ada language standard. However, it is a superset of what the
1975 standard describes, because it includes generic, inline, and subunit
1976 dependencies.
1977
1978 An object file must be recreated by recompiling the corresponding source
1979 file if any of the source files on which it depends are modified. For
1980 example, if the @code{make} utility is used to control compilation,
1981 the rule for an Ada object file must mention all the source files on
1982 which the object file depends, according to the above definition.
1983 The determination of the necessary
1984 recompilations is done automatically when one uses @command{gnatmake}.
1985 @end itemize
1986
1987 @node The Ada Library Information Files
1988 @section The Ada Library Information Files
1989 @cindex Ada Library Information files
1990 @cindex @file{ALI} files
1991
1992 @noindent
1993 Each compilation actually generates two output files. The first of these
1994 is the normal object file that has a @file{.o} extension. The second is a
1995 text file containing full dependency information. It has the same
1996 name as the source file, but an @file{.ali} extension.
1997 This file is known as the Ada Library Information (@file{ALI}) file.
1998 The following information is contained in the @file{ALI} file.
1999
2000 @itemize @bullet
2001 @item
2002 Version information (indicates which version of GNAT was used to compile
2003 the unit(s) in question)
2004
2005 @item
2006 Main program information (including priority and time slice settings,
2007 as well as the wide character encoding used during compilation).
2008
2009 @item
2010 List of arguments used in the @command{gcc} command for the compilation
2011
2012 @item
2013 Attributes of the unit, including configuration pragmas used, an indication
2014 of whether the compilation was successful, exception model used etc.
2015
2016 @item
2017 A list of relevant restrictions applying to the unit (used for consistency)
2018 checking.
2019
2020 @item
2021 Categorization information (e.g.@: use of pragma @code{Pure}).
2022
2023 @item
2024 Information on all @code{with}'ed units, including presence of
2025 @code{Elaborate} or @code{Elaborate_All} pragmas.
2026
2027 @item
2028 Information from any @code{Linker_Options} pragmas used in the unit
2029
2030 @item
2031 Information on the use of @code{Body_Version} or @code{Version}
2032 attributes in the unit.
2033
2034 @item
2035 Dependency information. This is a list of files, together with
2036 time stamp and checksum information. These are files on which
2037 the unit depends in the sense that recompilation is required
2038 if any of these units are modified.
2039
2040 @item
2041 Cross-reference data. Contains information on all entities referenced
2042 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2043 provide cross-reference information.
2044
2045 @end itemize
2046
2047 @noindent
2048 For a full detailed description of the format of the @file{ALI} file,
2049 see the source of the body of unit @code{Lib.Writ}, contained in file
2050 @file{lib-writ.adb} in the GNAT compiler sources.
2051
2052 @node Binding an Ada Program
2053 @section Binding an Ada Program
2054
2055 @noindent
2056 When using languages such as C and C++, once the source files have been
2057 compiled the only remaining step in building an executable program
2058 is linking the object modules together. This means that it is possible to
2059 link an inconsistent version of a program, in which two units have
2060 included different versions of the same header.
2061
2062 The rules of Ada do not permit such an inconsistent program to be built.
2063 For example, if two clients have different versions of the same package,
2064 it is illegal to build a program containing these two clients.
2065 These rules are enforced by the GNAT binder, which also determines an
2066 elaboration order consistent with the Ada rules.
2067
2068 The GNAT binder is run after all the object files for a program have
2069 been created. It is given the name of the main program unit, and from
2070 this it determines the set of units required by the program, by reading the
2071 corresponding ALI files. It generates error messages if the program is
2072 inconsistent or if no valid order of elaboration exists.
2073
2074 If no errors are detected, the binder produces a main program, in Ada by
2075 default, that contains calls to the elaboration procedures of those
2076 compilation unit that require them, followed by
2077 a call to the main program. This Ada program is compiled to generate the
2078 object file for the main program. The name of
2079 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2080 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2081 main program unit.
2082
2083 Finally, the linker is used to build the resulting executable program,
2084 using the object from the main program from the bind step as well as the
2085 object files for the Ada units of the program.
2086
2087 @node Mixed Language Programming
2088 @section Mixed Language Programming
2089 @cindex Mixed Language Programming
2090
2091 @noindent
2092 This section describes how to develop a mixed-language program,
2093 specifically one that comprises units in both Ada and C.
2094
2095 @menu
2096 * Interfacing to C::
2097 * Calling Conventions::
2098 @end menu
2099
2100 @node Interfacing to C
2101 @subsection Interfacing to C
2102 @noindent
2103 Interfacing Ada with a foreign language such as C involves using
2104 compiler directives to import and/or export entity definitions in each
2105 language---using @code{extern} statements in C, for instance, and the
2106 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2107 A full treatment of these topics is provided in Appendix B, section 1
2108 of the Ada Reference Manual.
2109
2110 There are two ways to build a program using GNAT that contains some Ada
2111 sources and some foreign language sources, depending on whether or not
2112 the main subprogram is written in Ada. Here is a source example with
2113 the main subprogram in Ada:
2114
2115 @smallexample
2116 /* file1.c */
2117 #include <stdio.h>
2118
2119 void print_num (int num)
2120 @{
2121 printf ("num is %d.\n", num);
2122 return;
2123 @}
2124
2125 /* file2.c */
2126
2127 /* num_from_Ada is declared in my_main.adb */
2128 extern int num_from_Ada;
2129
2130 int get_num (void)
2131 @{
2132 return num_from_Ada;
2133 @}
2134 @end smallexample
2135
2136 @smallexample @c ada
2137 -- my_main.adb
2138 procedure My_Main is
2139
2140 -- Declare then export an Integer entity called num_from_Ada
2141 My_Num : Integer := 10;
2142 pragma Export (C, My_Num, "num_from_Ada");
2143
2144 -- Declare an Ada function spec for Get_Num, then use
2145 -- C function get_num for the implementation.
2146 function Get_Num return Integer;
2147 pragma Import (C, Get_Num, "get_num");
2148
2149 -- Declare an Ada procedure spec for Print_Num, then use
2150 -- C function print_num for the implementation.
2151 procedure Print_Num (Num : Integer);
2152 pragma Import (C, Print_Num, "print_num");
2153
2154 begin
2155 Print_Num (Get_Num);
2156 end My_Main;
2157 @end smallexample
2158
2159 @enumerate
2160 @item
2161 To build this example, first compile the foreign language files to
2162 generate object files:
2163 @smallexample
2164 ^gcc -c file1.c^gcc -c FILE1.C^
2165 ^gcc -c file2.c^gcc -c FILE2.C^
2166 @end smallexample
2167
2168 @item
2169 Then, compile the Ada units to produce a set of object files and ALI
2170 files:
2171 @smallexample
2172 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2173 @end smallexample
2174
2175 @item
2176 Run the Ada binder on the Ada main program:
2177 @smallexample
2178 gnatbind my_main.ali
2179 @end smallexample
2180
2181 @item
2182 Link the Ada main program, the Ada objects and the other language
2183 objects:
2184 @smallexample
2185 gnatlink my_main.ali file1.o file2.o
2186 @end smallexample
2187 @end enumerate
2188
2189 The last three steps can be grouped in a single command:
2190 @smallexample
2191 gnatmake my_main.adb -largs file1.o file2.o
2192 @end smallexample
2193
2194 @cindex Binder output file
2195 @noindent
2196 If the main program is in a language other than Ada, then you may have
2197 more than one entry point into the Ada subsystem. You must use a special
2198 binder option to generate callable routines that initialize and
2199 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2200 Calls to the initialization and finalization routines must be inserted
2201 in the main program, or some other appropriate point in the code. The
2202 call to initialize the Ada units must occur before the first Ada
2203 subprogram is called, and the call to finalize the Ada units must occur
2204 after the last Ada subprogram returns. The binder will place the
2205 initialization and finalization subprograms into the
2206 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2207 sources. To illustrate, we have the following example:
2208
2209 @smallexample
2210 /* main.c */
2211 extern void adainit (void);
2212 extern void adafinal (void);
2213 extern int add (int, int);
2214 extern int sub (int, int);
2215
2216 int main (int argc, char *argv[])
2217 @{
2218 int a = 21, b = 7;
2219
2220 adainit();
2221
2222 /* Should print "21 + 7 = 28" */
2223 printf ("%d + %d = %d\n", a, b, add (a, b));
2224 /* Should print "21 - 7 = 14" */
2225 printf ("%d - %d = %d\n", a, b, sub (a, b));
2226
2227 adafinal();
2228 @}
2229 @end smallexample
2230
2231 @smallexample @c ada
2232 -- unit1.ads
2233 package Unit1 is
2234 function Add (A, B : Integer) return Integer;
2235 pragma Export (C, Add, "add");
2236 end Unit1;
2237
2238 -- unit1.adb
2239 package body Unit1 is
2240 function Add (A, B : Integer) return Integer is
2241 begin
2242 return A + B;
2243 end Add;
2244 end Unit1;
2245
2246 -- unit2.ads
2247 package Unit2 is
2248 function Sub (A, B : Integer) return Integer;
2249 pragma Export (C, Sub, "sub");
2250 end Unit2;
2251
2252 -- unit2.adb
2253 package body Unit2 is
2254 function Sub (A, B : Integer) return Integer is
2255 begin
2256 return A - B;
2257 end Sub;
2258 end Unit2;
2259 @end smallexample
2260
2261 @enumerate
2262 @item
2263 The build procedure for this application is similar to the last
2264 example's. First, compile the foreign language files to generate object
2265 files:
2266 @smallexample
2267 ^gcc -c main.c^gcc -c main.c^
2268 @end smallexample
2269
2270 @item
2271 Next, compile the Ada units to produce a set of object files and ALI
2272 files:
2273 @smallexample
2274 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2275 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2276 @end smallexample
2277
2278 @item
2279 Run the Ada binder on every generated ALI file. Make sure to use the
2280 @option{-n} option to specify a foreign main program:
2281 @smallexample
2282 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2283 @end smallexample
2284
2285 @item
2286 Link the Ada main program, the Ada objects and the foreign language
2287 objects. You need only list the last ALI file here:
2288 @smallexample
2289 gnatlink unit2.ali main.o -o exec_file
2290 @end smallexample
2291
2292 This procedure yields a binary executable called @file{exec_file}.
2293 @end enumerate
2294
2295 @noindent
2296 Depending on the circumstances (for example when your non-Ada main object
2297 does not provide symbol @code{main}), you may also need to instruct the
2298 GNAT linker not to include the standard startup objects by passing the
2299 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2300
2301 @node Calling Conventions
2302 @subsection Calling Conventions
2303 @cindex Foreign Languages
2304 @cindex Calling Conventions
2305 GNAT follows standard calling sequence conventions and will thus interface
2306 to any other language that also follows these conventions. The following
2307 Convention identifiers are recognized by GNAT:
2308
2309 @table @code
2310 @cindex Interfacing to Ada
2311 @cindex Other Ada compilers
2312 @cindex Convention Ada
2313 @item Ada
2314 This indicates that the standard Ada calling sequence will be
2315 used and all Ada data items may be passed without any limitations in the
2316 case where GNAT is used to generate both the caller and callee. It is also
2317 possible to mix GNAT generated code and code generated by another Ada
2318 compiler. In this case, the data types should be restricted to simple
2319 cases, including primitive types. Whether complex data types can be passed
2320 depends on the situation. Probably it is safe to pass simple arrays, such
2321 as arrays of integers or floats. Records may or may not work, depending
2322 on whether both compilers lay them out identically. Complex structures
2323 involving variant records, access parameters, tasks, or protected types,
2324 are unlikely to be able to be passed.
2325
2326 Note that in the case of GNAT running
2327 on a platform that supports HP Ada 83, a higher degree of compatibility
2328 can be guaranteed, and in particular records are laid out in an identical
2329 manner in the two compilers. Note also that if output from two different
2330 compilers is mixed, the program is responsible for dealing with elaboration
2331 issues. Probably the safest approach is to write the main program in the
2332 version of Ada other than GNAT, so that it takes care of its own elaboration
2333 requirements, and then call the GNAT-generated adainit procedure to ensure
2334 elaboration of the GNAT components. Consult the documentation of the other
2335 Ada compiler for further details on elaboration.
2336
2337 However, it is not possible to mix the tasking run time of GNAT and
2338 HP Ada 83, All the tasking operations must either be entirely within
2339 GNAT compiled sections of the program, or entirely within HP Ada 83
2340 compiled sections of the program.
2341
2342 @cindex Interfacing to Assembly
2343 @cindex Convention Assembler
2344 @item Assembler
2345 Specifies assembler as the convention. In practice this has the
2346 same effect as convention Ada (but is not equivalent in the sense of being
2347 considered the same convention).
2348
2349 @cindex Convention Asm
2350 @findex Asm
2351 @item Asm
2352 Equivalent to Assembler.
2353
2354 @cindex Interfacing to COBOL
2355 @cindex Convention COBOL
2356 @findex COBOL
2357 @item COBOL
2358 Data will be passed according to the conventions described
2359 in section B.4 of the Ada Reference Manual.
2360
2361 @findex C
2362 @cindex Interfacing to C
2363 @cindex Convention C
2364 @item C
2365 Data will be passed according to the conventions described
2366 in section B.3 of the Ada Reference Manual.
2367
2368 A note on interfacing to a C ``varargs'' function:
2369 @findex C varargs function
2370 @cindex Interfacing to C varargs function
2371 @cindex varargs function interfaces
2372
2373 @itemize @bullet
2374 @item
2375 In C, @code{varargs} allows a function to take a variable number of
2376 arguments. There is no direct equivalent in this to Ada. One
2377 approach that can be used is to create a C wrapper for each
2378 different profile and then interface to this C wrapper. For
2379 example, to print an @code{int} value using @code{printf},
2380 create a C function @code{printfi} that takes two arguments, a
2381 pointer to a string and an int, and calls @code{printf}.
2382 Then in the Ada program, use pragma @code{Import} to
2383 interface to @code{printfi}.
2384
2385 @item
2386 It may work on some platforms to directly interface to
2387 a @code{varargs} function by providing a specific Ada profile
2388 for a particular call. However, this does not work on
2389 all platforms, since there is no guarantee that the
2390 calling sequence for a two argument normal C function
2391 is the same as for calling a @code{varargs} C function with
2392 the same two arguments.
2393 @end itemize
2394
2395 @cindex Convention Default
2396 @findex Default
2397 @item Default
2398 Equivalent to C.
2399
2400 @cindex Convention External
2401 @findex External
2402 @item External
2403 Equivalent to C.
2404
2405 @ifclear vms
2406 @findex C++
2407 @cindex Interfacing to C++
2408 @cindex Convention C++
2409 @item C_Plus_Plus (or CPP)
2410 This stands for C++. For most purposes this is identical to C.
2411 See the separate description of the specialized GNAT pragmas relating to
2412 C++ interfacing for further details.
2413 @end ifclear
2414
2415 @findex Fortran
2416 @cindex Interfacing to Fortran
2417 @cindex Convention Fortran
2418 @item Fortran
2419 Data will be passed according to the conventions described
2420 in section B.5 of the Ada Reference Manual.
2421
2422 @item Intrinsic
2423 This applies to an intrinsic operation, as defined in the Ada
2424 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2425 this means that the body of the subprogram is provided by the compiler itself,
2426 usually by means of an efficient code sequence, and that the user does not
2427 supply an explicit body for it. In an application program, the pragma may
2428 be applied to the following sets of names:
2429
2430 @itemize @bullet
2431 @item
2432 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2433 Shift_Right_Arithmetic. The corresponding subprogram declaration must have
2434 two formal parameters. The
2435 first one must be a signed integer type or a modular type with a binary
2436 modulus, and the second parameter must be of type Natural.
2437 The return type must be the same as the type of the first argument. The size
2438 of this type can only be 8, 16, 32, or 64.
2439
2440 @item
2441 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2442 The corresponding operator declaration must have parameters and result type
2443 that have the same root numeric type (for example, all three are long_float
2444 types). This simplifies the definition of operations that use type checking
2445 to perform dimensional checks:
2446
2447 @smallexample @c ada
2448 type Distance is new Long_Float;
2449 type Time is new Long_Float;
2450 type Velocity is new Long_Float;
2451 function "/" (D : Distance; T : Time)
2452 return Velocity;
2453 pragma Import (Intrinsic, "/");
2454 @end smallexample
2455
2456 @noindent
2457 This common idiom is often programmed with a generic definition and an
2458 explicit body. The pragma makes it simpler to introduce such declarations.
2459 It incurs no overhead in compilation time or code size, because it is
2460 implemented as a single machine instruction.
2461
2462 @item
2463 General subprogram entities, to bind an Ada subprogram declaration to
2464 a compiler builtin by name with back-ends where such interfaces are
2465 available. A typical example is the set of ``__builtin'' functions
2466 exposed by the GCC back-end, as in the following example:
2467
2468 @smallexample @c ada
2469 function builtin_sqrt (F : Float) return Float;
2470 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2471 @end smallexample
2472
2473 Most of the GCC builtins are accessible this way, and as for other
2474 import conventions (e.g. C), it is the user's responsibility to ensure
2475 that the Ada subprogram profile matches the underlying builtin
2476 expectations.
2477 @end itemize
2478
2479 @noindent
2480
2481 @ifset unw
2482 @findex Stdcall
2483 @cindex Convention Stdcall
2484 @item Stdcall
2485 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2486 and specifies that the @code{Stdcall} calling sequence will be used,
2487 as defined by the NT API. Nevertheless, to ease building
2488 cross-platform bindings this convention will be handled as a @code{C} calling
2489 convention on non-Windows platforms.
2490
2491 @findex DLL
2492 @cindex Convention DLL
2493 @item DLL
2494 This is equivalent to @code{Stdcall}.
2495
2496 @findex Win32
2497 @cindex Convention Win32
2498 @item Win32
2499 This is equivalent to @code{Stdcall}.
2500 @end ifset
2501
2502 @findex Stubbed
2503 @cindex Convention Stubbed
2504 @item Stubbed
2505 This is a special convention that indicates that the compiler
2506 should provide a stub body that raises @code{Program_Error}.
2507 @end table
2508
2509 @noindent
2510 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2511 that can be used to parameterize conventions and allow additional synonyms
2512 to be specified. For example if you have legacy code in which the convention
2513 identifier Fortran77 was used for Fortran, you can use the configuration
2514 pragma:
2515
2516 @smallexample @c ada
2517 pragma Convention_Identifier (Fortran77, Fortran);
2518 @end smallexample
2519
2520 @noindent
2521 And from now on the identifier Fortran77 may be used as a convention
2522 identifier (for example in an @code{Import} pragma) with the same
2523 meaning as Fortran.
2524
2525 @ifclear vms
2526 @node Building Mixed Ada & C++ Programs
2527 @section Building Mixed Ada and C++ Programs
2528
2529 @noindent
2530 A programmer inexperienced with mixed-language development may find that
2531 building an application containing both Ada and C++ code can be a
2532 challenge. This section gives a few
2533 hints that should make this task easier. The first section addresses
2534 the differences between interfacing with C and interfacing with C++.
2535 The second section
2536 looks into the delicate problem of linking the complete application from
2537 its Ada and C++ parts. The last section gives some hints on how the GNAT
2538 run-time library can be adapted in order to allow inter-language dispatching
2539 with a new C++ compiler.
2540
2541 @menu
2542 * Interfacing to C++::
2543 * Linking a Mixed C++ & Ada Program::
2544 * A Simple Example::
2545 * Interfacing with C++ constructors::
2546 * Interfacing with C++ at the Class Level::
2547 @end menu
2548
2549 @node Interfacing to C++
2550 @subsection Interfacing to C++
2551
2552 @noindent
2553 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2554 generating code that is compatible with the G++ Application Binary
2555 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2556
2557 @noindent
2558 Interfacing can be done at 3 levels: simple data, subprograms, and
2559 classes. In the first two cases, GNAT offers a specific @code{Convention
2560 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2561 Usually, C++ mangles the names of subprograms. To generate proper mangled
2562 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2563 This problem can also be addressed manually in two ways:
2564
2565 @itemize @bullet
2566 @item
2567 by modifying the C++ code in order to force a C convention using
2568 the @code{extern "C"} syntax.
2569
2570 @item
2571 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2572 Link_Name argument of the pragma import.
2573 @end itemize
2574
2575 @noindent
2576 Interfacing at the class level can be achieved by using the GNAT specific
2577 pragmas such as @code{CPP_Constructor}. @xref{Interfacing to C++,,,
2578 gnat_rm, GNAT Reference Manual}, for additional information.
2579
2580 @node Linking a Mixed C++ & Ada Program
2581 @subsection Linking a Mixed C++ & Ada Program
2582
2583 @noindent
2584 Usually the linker of the C++ development system must be used to link
2585 mixed applications because most C++ systems will resolve elaboration
2586 issues (such as calling constructors on global class instances)
2587 transparently during the link phase. GNAT has been adapted to ease the
2588 use of a foreign linker for the last phase. Three cases can be
2589 considered:
2590 @enumerate
2591
2592 @item
2593 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
2594 The C++ linker can simply be called by using the C++ specific driver
2595 called @code{g++}.
2596
2597 Note that if the C++ code uses inline functions, you will need to
2598 compile your C++ code with the @code{-fkeep-inline-functions} switch in
2599 order to provide an existing function implementation that the Ada code can
2600 link with.
2601
2602 @smallexample
2603 $ g++ -c -fkeep-inline-functions file1.C
2604 $ g++ -c -fkeep-inline-functions file2.C
2605 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
2606 @end smallexample
2607
2608 @item
2609 Using GNAT and G++ from two different GCC installations: If both
2610 compilers are on the @env{PATH}, the previous method may be used. It is
2611 important to note that environment variables such as
2612 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
2613 @env{GCC_ROOT} will affect both compilers
2614 at the same time and may make one of the two compilers operate
2615 improperly if set during invocation of the wrong compiler. It is also
2616 very important that the linker uses the proper @file{libgcc.a} GCC
2617 library -- that is, the one from the C++ compiler installation. The
2618 implicit link command as suggested in the @command{gnatmake} command
2619 from the former example can be replaced by an explicit link command with
2620 the full-verbosity option in order to verify which library is used:
2621 @smallexample
2622 $ gnatbind ada_unit
2623 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2624 @end smallexample
2625 If there is a problem due to interfering environment variables, it can
2626 be worked around by using an intermediate script. The following example
2627 shows the proper script to use when GNAT has not been installed at its
2628 default location and g++ has been installed at its default location:
2629
2630 @smallexample
2631 $ cat ./my_script
2632 #!/bin/sh
2633 unset BINUTILS_ROOT
2634 unset GCC_ROOT
2635 c++ $*
2636 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2637 @end smallexample
2638
2639 @item
2640 Using a non-GNU C++ compiler: The commands previously described can be
2641 used to insure that the C++ linker is used. Nonetheless, you need to add
2642 a few more parameters to the link command line, depending on the exception
2643 mechanism used.
2644
2645 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
2646 to the libgcc libraries are required:
2647
2648 @smallexample
2649 $ cat ./my_script
2650 #!/bin/sh
2651 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
2652 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2653 @end smallexample
2654
2655 Where CC is the name of the non-GNU C++ compiler.
2656
2657 If the @code{zero cost} exception mechanism is used, and the platform
2658 supports automatic registration of exception tables (e.g.@: Solaris),
2659 paths to more objects are required:
2660
2661 @smallexample
2662 $ cat ./my_script
2663 #!/bin/sh
2664 CC `gcc -print-file-name=crtbegin.o` $* \
2665 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
2666 `gcc -print-file-name=crtend.o`
2667 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2668 @end smallexample
2669
2670 If the @code{zero cost} exception mechanism is used, and the platform
2671 doesn't support automatic registration of exception tables (e.g.@: HP-UX
2672 or AIX), the simple approach described above will not work and
2673 a pre-linking phase using GNAT will be necessary.
2674
2675 @end enumerate
2676
2677 Another alternative is to use the @command{gprbuild} multi-language builder
2678 which has a large knowledge base and knows how to link Ada and C++ code
2679 together automatically in most cases.
2680
2681 @node A Simple Example
2682 @subsection A Simple Example
2683 @noindent
2684 The following example, provided as part of the GNAT examples, shows how
2685 to achieve procedural interfacing between Ada and C++ in both
2686 directions. The C++ class A has two methods. The first method is exported
2687 to Ada by the means of an extern C wrapper function. The second method
2688 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
2689 a limited record with a layout comparable to the C++ class. The Ada
2690 subprogram, in turn, calls the C++ method. So, starting from the C++
2691 main program, the process passes back and forth between the two
2692 languages.
2693
2694 @noindent
2695 Here are the compilation commands:
2696 @smallexample
2697 $ gnatmake -c simple_cpp_interface
2698 $ g++ -c cpp_main.C
2699 $ g++ -c ex7.C
2700 $ gnatbind -n simple_cpp_interface
2701 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
2702 -lstdc++ ex7.o cpp_main.o
2703 @end smallexample
2704
2705 @noindent
2706 Here are the corresponding sources:
2707 @smallexample
2708
2709 //cpp_main.C
2710
2711 #include "ex7.h"
2712
2713 extern "C" @{
2714 void adainit (void);
2715 void adafinal (void);
2716 void method1 (A *t);
2717 @}
2718
2719 void method1 (A *t)
2720 @{
2721 t->method1 ();
2722 @}
2723
2724 int main ()
2725 @{
2726 A obj;
2727 adainit ();
2728 obj.method2 (3030);
2729 adafinal ();
2730 @}
2731
2732 //ex7.h
2733
2734 class Origin @{
2735 public:
2736 int o_value;
2737 @};
2738 class A : public Origin @{
2739 public:
2740 void method1 (void);
2741 void method2 (int v);
2742 A();
2743 int a_value;
2744 @};
2745
2746 //ex7.C
2747
2748 #include "ex7.h"
2749 #include <stdio.h>
2750
2751 extern "C" @{ void ada_method2 (A *t, int v);@}
2752
2753 void A::method1 (void)
2754 @{
2755 a_value = 2020;
2756 printf ("in A::method1, a_value = %d \n",a_value);
2757
2758 @}
2759
2760 void A::method2 (int v)
2761 @{
2762 ada_method2 (this, v);
2763 printf ("in A::method2, a_value = %d \n",a_value);
2764
2765 @}
2766
2767 A::A(void)
2768 @{
2769 a_value = 1010;
2770 printf ("in A::A, a_value = %d \n",a_value);
2771 @}
2772 @end smallexample
2773
2774 @smallexample @c ada
2775 -- Ada sources
2776 package body Simple_Cpp_Interface is
2777
2778 procedure Ada_Method2 (This : in out A; V : Integer) is
2779 begin
2780 Method1 (This);
2781 This.A_Value := V;
2782 end Ada_Method2;
2783
2784 end Simple_Cpp_Interface;
2785
2786 with System;
2787 package Simple_Cpp_Interface is
2788 type A is limited
2789 record
2790 Vptr : System.Address;
2791 O_Value : Integer;
2792 A_Value : Integer;
2793 end record;
2794 pragma Convention (C, A);
2795
2796 procedure Method1 (This : in out A);
2797 pragma Import (C, Method1);
2798
2799 procedure Ada_Method2 (This : in out A; V : Integer);
2800 pragma Export (C, Ada_Method2);
2801
2802 end Simple_Cpp_Interface;
2803 @end smallexample
2804
2805 @node Interfacing with C++ constructors
2806 @subsection Interfacing with C++ constructors
2807 @noindent
2808
2809 In order to interface with C++ constructors GNAT provides the
2810 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
2811 gnat_rm, GNAT Reference Manual}, for additional information).
2812 In this section we present some common uses of C++ constructors
2813 in mixed-languages programs in GNAT.
2814
2815 Let us assume that we need to interface with the following
2816 C++ class:
2817
2818 @smallexample
2819 @b{class} Root @{
2820 @b{public}:
2821 int a_value;
2822 int b_value;
2823 @b{virtual} int Get_Value ();
2824 Root(); // Default constructor
2825 Root(int v); // 1st non-default constructor
2826 Root(int v, int w); // 2nd non-default constructor
2827 @};
2828 @end smallexample
2829
2830 For this purpose we can write the following package spec (further
2831 information on how to build this spec is available in
2832 @ref{Interfacing with C++ at the Class Level} and
2833 @ref{Generating Ada Bindings for C and C++ headers}).
2834
2835 @smallexample @c ada
2836 with Interfaces.C; use Interfaces.C;
2837 package Pkg_Root is
2838 type Root is tagged limited record
2839 A_Value : int;
2840 B_Value : int;
2841 end record;
2842 pragma Import (CPP, Root);
2843
2844 function Get_Value (Obj : Root) return int;
2845 pragma Import (CPP, Get_Value);
2846
2847 function Constructor return Root;
2848 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
2849
2850 function Constructor (v : Integer) return Root;
2851 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
2852
2853 function Constructor (v, w : Integer) return Root;
2854 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
2855 end Pkg_Root;
2856 @end smallexample
2857
2858 On the Ada side the constructor is represented by a function (whose
2859 name is arbitrary) that returns the classwide type corresponding to
2860 the imported C++ class. Although the constructor is described as a
2861 function, it is typically a procedure with an extra implicit argument
2862 (the object being initialized) at the implementation level. GNAT
2863 issues the appropriate call, whatever it is, to get the object
2864 properly initialized.
2865
2866 Constructors can only appear in the following contexts:
2867
2868 @itemize @bullet
2869 @item
2870 On the right side of an initialization of an object of type @var{T}.
2871 @item
2872 On the right side of an initialization of a record component of type @var{T}.
2873 @item
2874 In an Ada 2005 limited aggregate.
2875 @item
2876 In an Ada 2005 nested limited aggregate.
2877 @item
2878 In an Ada 2005 limited aggregate that initializes an object built in
2879 place by an extended return statement.
2880 @end itemize
2881
2882 @noindent
2883 In a declaration of an object whose type is a class imported from C++,
2884 either the default C++ constructor is implicitly called by GNAT, or
2885 else the required C++ constructor must be explicitly called in the
2886 expression that initializes the object. For example:
2887
2888 @smallexample @c ada
2889 Obj1 : Root;
2890 Obj2 : Root := Constructor;
2891 Obj3 : Root := Constructor (v => 10);
2892 Obj4 : Root := Constructor (30, 40);
2893 @end smallexample
2894
2895 The first two declarations are equivalent: in both cases the default C++
2896 constructor is invoked (in the former case the call to the constructor is
2897 implicit, and in the latter case the call is explicit in the object
2898 declaration). @code{Obj3} is initialized by the C++ non-default constructor
2899 that takes an integer argument, and @code{Obj4} is initialized by the
2900 non-default C++ constructor that takes two integers.
2901
2902 Let us derive the imported C++ class in the Ada side. For example:
2903
2904 @smallexample @c ada
2905 type DT is new Root with record
2906 C_Value : Natural := 2009;
2907 end record;
2908 @end smallexample
2909
2910 In this case the components DT inherited from the C++ side must be
2911 initialized by a C++ constructor, and the additional Ada components
2912 of type DT are initialized by GNAT. The initialization of such an
2913 object is done either by default, or by means of a function returning
2914 an aggregate of type DT, or by means of an extension aggregate.
2915
2916 @smallexample @c ada
2917 Obj5 : DT;
2918 Obj6 : DT := Function_Returning_DT (50);
2919 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
2920 @end smallexample
2921
2922 The declaration of @code{Obj5} invokes the default constructors: the
2923 C++ default constructor of the parent type takes care of the initialization
2924 of the components inherited from Root, and GNAT takes care of the default
2925 initialization of the additional Ada components of type DT (that is,
2926 @code{C_Value} is initialized to value 2009). The order of invocation of
2927 the constructors is consistent with the order of elaboration required by
2928 Ada and C++. That is, the constructor of the parent type is always called
2929 before the constructor of the derived type.
2930
2931 Let us now consider a record that has components whose type is imported
2932 from C++. For example:
2933
2934 @smallexample @c ada
2935 type Rec1 is limited record
2936 Data1 : Root := Constructor (10);
2937 Value : Natural := 1000;
2938 end record;
2939
2940 type Rec2 (D : Integer := 20) is limited record
2941 Rec : Rec1;
2942 Data2 : Root := Constructor (D, 30);
2943 end record;
2944 @end smallexample
2945
2946 The initialization of an object of type @code{Rec2} will call the
2947 non-default C++ constructors specified for the imported components.
2948 For example:
2949
2950 @smallexample @c ada
2951 Obj8 : Rec2 (40);
2952 @end smallexample
2953
2954 Using Ada 2005 we can use limited aggregates to initialize an object
2955 invoking C++ constructors that differ from those specified in the type
2956 declarations. For example:
2957
2958 @smallexample @c ada
2959 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
2960 others => <>),
2961 others => <>);
2962 @end smallexample
2963
2964 The above declaration uses an Ada 2005 limited aggregate to
2965 initialize @code{Obj9}, and the C++ constructor that has two integer
2966 arguments is invoked to initialize the @code{Data1} component instead
2967 of the constructor specified in the declaration of type @code{Rec1}. In
2968 Ada 2005 the box in the aggregate indicates that unspecified components
2969 are initialized using the expression (if any) available in the component
2970 declaration. That is, in this case discriminant @code{D} is initialized
2971 to value @code{20}, @code{Value} is initialized to value 1000, and the
2972 non-default C++ constructor that handles two integers takes care of
2973 initializing component @code{Data2} with values @code{20,30}.
2974
2975 In Ada 2005 we can use the extended return statement to build the Ada
2976 equivalent to C++ non-default constructors. For example:
2977
2978 @smallexample @c ada
2979 function Constructor (V : Integer) return Rec2 is
2980 begin
2981 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20),
2982 others => <>),
2983 others => <>) do
2984 -- Further actions required for construction of
2985 -- objects of type Rec2
2986 ...
2987 end record;
2988 end Constructor;
2989 @end smallexample
2990
2991 In this example the extended return statement construct is used to
2992 build in place the returned object whose components are initialized
2993 by means of a limited aggregate. Any further action associated with
2994 the constructor can be placed inside the construct.
2995
2996 @node Interfacing with C++ at the Class Level
2997 @subsection Interfacing with C++ at the Class Level
2998 @noindent
2999 In this section we demonstrate the GNAT features for interfacing with
3000 C++ by means of an example making use of Ada 2005 abstract interface
3001 types. This example consists of a classification of animals; classes
3002 have been used to model our main classification of animals, and
3003 interfaces provide support for the management of secondary
3004 classifications. We first demonstrate a case in which the types and
3005 constructors are defined on the C++ side and imported from the Ada
3006 side, and latter the reverse case.
3007
3008 The root of our derivation will be the @code{Animal} class, with a
3009 single private attribute (the @code{Age} of the animal) and two public
3010 primitives to set and get the value of this attribute.
3011
3012 @smallexample
3013 @b{class} Animal @{
3014 @b{public}:
3015 @b{virtual} void Set_Age (int New_Age);
3016 @b{virtual} int Age ();
3017 @b{private}:
3018 int Age_Count;
3019 @};
3020 @end smallexample
3021
3022 Abstract interface types are defined in C++ by means of classes with pure
3023 virtual functions and no data members. In our example we will use two
3024 interfaces that provide support for the common management of @code{Carnivore}
3025 and @code{Domestic} animals:
3026
3027 @smallexample
3028 @b{class} Carnivore @{
3029 @b{public}:
3030 @b{virtual} int Number_Of_Teeth () = 0;
3031 @};
3032
3033 @b{class} Domestic @{
3034 @b{public}:
3035 @b{virtual void} Set_Owner (char* Name) = 0;
3036 @};
3037 @end smallexample
3038
3039 Using these declarations, we can now say that a @code{Dog} is an animal that is
3040 both Carnivore and Domestic, that is:
3041
3042 @smallexample
3043 @b{class} Dog : Animal, Carnivore, Domestic @{
3044 @b{public}:
3045 @b{virtual} int Number_Of_Teeth ();
3046 @b{virtual} void Set_Owner (char* Name);
3047
3048 Dog(); // Constructor
3049 @b{private}:
3050 int Tooth_Count;
3051 char *Owner;
3052 @};
3053 @end smallexample
3054
3055 In the following examples we will assume that the previous declarations are
3056 located in a file named @code{animals.h}. The following package demonstrates
3057 how to import these C++ declarations from the Ada side:
3058
3059 @smallexample @c ada
3060 with Interfaces.C.Strings; use Interfaces.C.Strings;
3061 package Animals is
3062 type Carnivore is interface;
3063 pragma Convention (C_Plus_Plus, Carnivore);
3064 function Number_Of_Teeth (X : Carnivore)
3065 return Natural is abstract;
3066
3067 type Domestic is interface;
3068 pragma Convention (C_Plus_Plus, Set_Owner);
3069 procedure Set_Owner
3070 (X : in out Domestic;
3071 Name : Chars_Ptr) is abstract;
3072
3073 type Animal is tagged record
3074 Age : Natural := 0;
3075 end record;
3076 pragma Import (C_Plus_Plus, Animal);
3077
3078 procedure Set_Age (X : in out Animal; Age : Integer);
3079 pragma Import (C_Plus_Plus, Set_Age);
3080
3081 function Age (X : Animal) return Integer;
3082 pragma Import (C_Plus_Plus, Age);
3083
3084 type Dog is new Animal and Carnivore and Domestic with record
3085 Tooth_Count : Natural;
3086 Owner : String (1 .. 30);
3087 end record;
3088 pragma Import (C_Plus_Plus, Dog);
3089
3090 function Number_Of_Teeth (A : Dog) return Integer;
3091 pragma Import (C_Plus_Plus, Number_Of_Teeth);
3092
3093 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3094 pragma Import (C_Plus_Plus, Set_Owner);
3095
3096 function New_Dog return Dog;
3097 pragma CPP_Constructor (New_Dog);
3098 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3099 end Animals;
3100 @end smallexample
3101
3102 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3103 interfacing with these C++ classes is easy. The only requirement is that all
3104 the primitives and components must be declared exactly in the same order in
3105 the two languages.
3106
3107 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3108 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3109 the arguments to the called primitives will be the same as for C++. For the
3110 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3111 to indicate that they have been defined on the C++ side; this is required
3112 because the dispatch table associated with these tagged types will be built
3113 in the C++ side and therefore will not contain the predefined Ada primitives
3114 which Ada would otherwise expect.
3115
3116 As the reader can see there is no need to indicate the C++ mangled names
3117 associated with each subprogram because it is assumed that all the calls to
3118 these primitives will be dispatching calls. The only exception is the
3119 constructor, which must be registered with the compiler by means of
3120 @code{pragma CPP_Constructor} and needs to provide its associated C++
3121 mangled name because the Ada compiler generates direct calls to it.
3122
3123 With the above packages we can now declare objects of type Dog on the Ada side
3124 and dispatch calls to the corresponding subprograms on the C++ side. We can
3125 also extend the tagged type Dog with further fields and primitives, and
3126 override some of its C++ primitives on the Ada side. For example, here we have
3127 a type derivation defined on the Ada side that inherits all the dispatching
3128 primitives of the ancestor from the C++ side.
3129
3130 @smallexample
3131 @b{with} Animals; @b{use} Animals;
3132 @b{package} Vaccinated_Animals @b{is}
3133 @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3134 @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3135 @b{end} Vaccinated_Animals;
3136 @end smallexample
3137
3138 It is important to note that, because of the ABI compatibility, the programmer
3139 does not need to add any further information to indicate either the object
3140 layout or the dispatch table entry associated with each dispatching operation.
3141
3142 Now let us define all the types and constructors on the Ada side and export
3143 them to C++, using the same hierarchy of our previous example:
3144
3145 @smallexample @c ada
3146 with Interfaces.C.Strings;
3147 use Interfaces.C.Strings;
3148 package Animals is
3149 type Carnivore is interface;
3150 pragma Convention (C_Plus_Plus, Carnivore);
3151 function Number_Of_Teeth (X : Carnivore)
3152 return Natural is abstract;
3153
3154 type Domestic is interface;
3155 pragma Convention (C_Plus_Plus, Set_Owner);
3156 procedure Set_Owner
3157 (X : in out Domestic;
3158 Name : Chars_Ptr) is abstract;
3159
3160 type Animal is tagged record
3161 Age : Natural := 0;
3162 end record;
3163 pragma Convention (C_Plus_Plus, Animal);
3164
3165 procedure Set_Age (X : in out Animal; Age : Integer);
3166 pragma Export (C_Plus_Plus, Set_Age);
3167
3168 function Age (X : Animal) return Integer;
3169 pragma Export (C_Plus_Plus, Age);
3170
3171 type Dog is new Animal and Carnivore and Domestic with record
3172 Tooth_Count : Natural;
3173 Owner : String (1 .. 30);
3174 end record;
3175 pragma Convention (C_Plus_Plus, Dog);
3176
3177 function Number_Of_Teeth (A : Dog) return Integer;
3178 pragma Export (C_Plus_Plus, Number_Of_Teeth);
3179
3180 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3181 pragma Export (C_Plus_Plus, Set_Owner);
3182
3183 function New_Dog return Dog'Class;
3184 pragma Export (C_Plus_Plus, New_Dog);
3185 end Animals;
3186 @end smallexample
3187
3188 Compared with our previous example the only difference is the use of
3189 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3190 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3191 nothing else to be done; as explained above, the only requirement is that all
3192 the primitives and components are declared in exactly the same order.
3193
3194 For completeness, let us see a brief C++ main program that uses the
3195 declarations available in @code{animals.h} (presented in our first example) to
3196 import and use the declarations from the Ada side, properly initializing and
3197 finalizing the Ada run-time system along the way:
3198
3199 @smallexample
3200 @b{#include} "animals.h"
3201 @b{#include} <iostream>
3202 @b{using namespace} std;
3203
3204 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3205 void Check_Domestic (Domestic *obj) @{@dots{}@}
3206 void Check_Animal (Animal *obj) @{@dots{}@}
3207 void Check_Dog (Dog *obj) @{@dots{}@}
3208
3209 @b{extern} "C" @{
3210 void adainit (void);
3211 void adafinal (void);
3212 Dog* new_dog ();
3213 @}
3214
3215 void test ()
3216 @{
3217 Dog *obj = new_dog(); // Ada constructor
3218 Check_Carnivore (obj); // Check secondary DT
3219 Check_Domestic (obj); // Check secondary DT
3220 Check_Animal (obj); // Check primary DT
3221 Check_Dog (obj); // Check primary DT
3222 @}
3223
3224 int main ()
3225 @{
3226 adainit (); test(); adafinal ();
3227 return 0;
3228 @}
3229 @end smallexample
3230
3231 @node Comparison between GNAT and C/C++ Compilation Models
3232 @section Comparison between GNAT and C/C++ Compilation Models
3233
3234 @noindent
3235 The GNAT model of compilation is close to the C and C++ models. You can
3236 think of Ada specs as corresponding to header files in C. As in C, you
3237 don't need to compile specs; they are compiled when they are used. The
3238 Ada @code{with} is similar in effect to the @code{#include} of a C
3239 header.
3240
3241 One notable difference is that, in Ada, you may compile specs separately
3242 to check them for semantic and syntactic accuracy. This is not always
3243 possible with C headers because they are fragments of programs that have
3244 less specific syntactic or semantic rules.
3245
3246 The other major difference is the requirement for running the binder,
3247 which performs two important functions. First, it checks for
3248 consistency. In C or C++, the only defense against assembling
3249 inconsistent programs lies outside the compiler, in a makefile, for
3250 example. The binder satisfies the Ada requirement that it be impossible
3251 to construct an inconsistent program when the compiler is used in normal
3252 mode.
3253
3254 @cindex Elaboration order control
3255 The other important function of the binder is to deal with elaboration
3256 issues. There are also elaboration issues in C++ that are handled
3257 automatically. This automatic handling has the advantage of being
3258 simpler to use, but the C++ programmer has no control over elaboration.
3259 Where @code{gnatbind} might complain there was no valid order of
3260 elaboration, a C++ compiler would simply construct a program that
3261 malfunctioned at run time.
3262 @end ifclear
3263
3264 @node Comparison between GNAT and Conventional Ada Library Models
3265 @section Comparison between GNAT and Conventional Ada Library Models
3266
3267 @noindent
3268 This section is intended for Ada programmers who have
3269 used an Ada compiler implementing the traditional Ada library
3270 model, as described in the Ada Reference Manual.
3271
3272 @cindex GNAT library
3273 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3274 source files themselves acts as the library. Compiling Ada programs does
3275 not generate any centralized information, but rather an object file and
3276 a ALI file, which are of interest only to the binder and linker.
3277 In a traditional system, the compiler reads information not only from
3278 the source file being compiled, but also from the centralized library.
3279 This means that the effect of a compilation depends on what has been
3280 previously compiled. In particular:
3281
3282 @itemize @bullet
3283 @item
3284 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3285 to the version of the unit most recently compiled into the library.
3286
3287 @item
3288 Inlining is effective only if the necessary body has already been
3289 compiled into the library.
3290
3291 @item
3292 Compiling a unit may obsolete other units in the library.
3293 @end itemize
3294
3295 @noindent
3296 In GNAT, compiling one unit never affects the compilation of any other
3297 units because the compiler reads only source files. Only changes to source
3298 files can affect the results of a compilation. In particular:
3299
3300 @itemize @bullet
3301 @item
3302 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3303 to the source version of the unit that is currently accessible to the
3304 compiler.
3305
3306 @item
3307 @cindex Inlining
3308 Inlining requires the appropriate source files for the package or
3309 subprogram bodies to be available to the compiler. Inlining is always
3310 effective, independent of the order in which units are complied.
3311
3312 @item
3313 Compiling a unit never affects any other compilations. The editing of
3314 sources may cause previous compilations to be out of date if they
3315 depended on the source file being modified.
3316 @end itemize
3317
3318 @noindent
3319 The most important result of these differences is that order of compilation
3320 is never significant in GNAT. There is no situation in which one is
3321 required to do one compilation before another. What shows up as order of
3322 compilation requirements in the traditional Ada library becomes, in
3323 GNAT, simple source dependencies; in other words, there is only a set
3324 of rules saying what source files must be present when a file is
3325 compiled.
3326
3327 @ifset vms
3328 @node Placement of temporary files
3329 @section Placement of temporary files
3330 @cindex Temporary files (user control over placement)
3331
3332 @noindent
3333 GNAT creates temporary files in the directory designated by the environment
3334 variable @env{TMPDIR}.
3335 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3336 for detailed information on how environment variables are resolved.
3337 For most users the easiest way to make use of this feature is to simply
3338 define @env{TMPDIR} as a job level logical name).
3339 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3340 for compiler temporary files, then you can include something like the
3341 following command in your @file{LOGIN.COM} file:
3342
3343 @smallexample
3344 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3345 @end smallexample
3346
3347 @noindent
3348 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3349 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3350 designated by @env{TEMP}.
3351 If none of these environment variables are defined then GNAT uses the
3352 directory designated by the logical name @code{SYS$SCRATCH:}
3353 (by default the user's home directory). If all else fails
3354 GNAT uses the current directory for temporary files.
3355 @end ifset
3356
3357 @c *************************
3358 @node Compiling with gcc
3359 @chapter Compiling with @command{gcc}
3360
3361 @noindent
3362 This chapter discusses how to compile Ada programs using the @command{gcc}
3363 command. It also describes the set of switches
3364 that can be used to control the behavior of the compiler.
3365 @menu
3366 * Compiling Programs::
3367 * Switches for gcc::
3368 * Search Paths and the Run-Time Library (RTL)::
3369 * Order of Compilation Issues::
3370 * Examples::
3371 @end menu
3372
3373 @node Compiling Programs
3374 @section Compiling Programs
3375
3376 @noindent
3377 The first step in creating an executable program is to compile the units
3378 of the program using the @command{gcc} command. You must compile the
3379 following files:
3380
3381 @itemize @bullet
3382 @item
3383 the body file (@file{.adb}) for a library level subprogram or generic
3384 subprogram
3385
3386 @item
3387 the spec file (@file{.ads}) for a library level package or generic
3388 package that has no body
3389
3390 @item
3391 the body file (@file{.adb}) for a library level package
3392 or generic package that has a body
3393
3394 @end itemize
3395
3396 @noindent
3397 You need @emph{not} compile the following files
3398
3399 @itemize @bullet
3400
3401 @item
3402 the spec of a library unit which has a body
3403
3404 @item
3405 subunits
3406 @end itemize
3407
3408 @noindent
3409 because they are compiled as part of compiling related units. GNAT
3410 package specs
3411 when the corresponding body is compiled, and subunits when the parent is
3412 compiled.
3413
3414 @cindex cannot generate code
3415 If you attempt to compile any of these files, you will get one of the
3416 following error messages (where @var{fff} is the name of the file you
3417 compiled):
3418
3419 @smallexample
3420 cannot generate code for file @var{fff} (package spec)
3421 to check package spec, use -gnatc
3422
3423 cannot generate code for file @var{fff} (missing subunits)
3424 to check parent unit, use -gnatc
3425
3426 cannot generate code for file @var{fff} (subprogram spec)
3427 to check subprogram spec, use -gnatc
3428
3429 cannot generate code for file @var{fff} (subunit)
3430 to check subunit, use -gnatc
3431 @end smallexample
3432
3433 @noindent
3434 As indicated by the above error messages, if you want to submit
3435 one of these files to the compiler to check for correct semantics
3436 without generating code, then use the @option{-gnatc} switch.
3437
3438 The basic command for compiling a file containing an Ada unit is
3439
3440 @smallexample
3441 @c $ gcc -c @ovar{switches} @file{file name}
3442 @c Expanding @ovar macro inline (explanation in macro def comments)
3443 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3444 @end smallexample
3445
3446 @noindent
3447 where @var{file name} is the name of the Ada file (usually
3448 having an extension
3449 @file{.ads} for a spec or @file{.adb} for a body).
3450 @ifclear vms
3451 You specify the
3452 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3453 @end ifclear
3454 The result of a successful compilation is an object file, which has the
3455 same name as the source file but an extension of @file{.o} and an Ada
3456 Library Information (ALI) file, which also has the same name as the
3457 source file, but with @file{.ali} as the extension. GNAT creates these
3458 two output files in the current directory, but you may specify a source
3459 file in any directory using an absolute or relative path specification
3460 containing the directory information.
3461
3462 @findex gnat1
3463 @command{gcc} is actually a driver program that looks at the extensions of
3464 the file arguments and loads the appropriate compiler. For example, the
3465 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3466 These programs are in directories known to the driver program (in some
3467 configurations via environment variables you set), but need not be in
3468 your path. The @command{gcc} driver also calls the assembler and any other
3469 utilities needed to complete the generation of the required object
3470 files.
3471
3472 It is possible to supply several file names on the same @command{gcc}
3473 command. This causes @command{gcc} to call the appropriate compiler for
3474 each file. For example, the following command lists two separate
3475 files to be compiled:
3476
3477 @smallexample
3478 $ gcc -c x.adb y.adb
3479 @end smallexample
3480
3481 @noindent
3482 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3483 @file{y.adb}.
3484 The compiler generates two object files @file{x.o} and @file{y.o}
3485 and the two ALI files @file{x.ali} and @file{y.ali}.
3486 Any switches apply to all the files ^listed,^listed.^
3487
3488 @node Switches for gcc
3489 @section Switches for @command{gcc}
3490
3491 @noindent
3492 The @command{gcc} command accepts switches that control the
3493 compilation process. These switches are fully described in this section.
3494 First we briefly list all the switches, in alphabetical order, then we
3495 describe the switches in more detail in functionally grouped sections.
3496
3497 More switches exist for GCC than those documented here, especially
3498 for specific targets. However, their use is not recommended as
3499 they may change code generation in ways that are incompatible with
3500 the Ada run-time library, or can cause inconsistencies between
3501 compilation units.
3502
3503 @menu
3504 * Output and Error Message Control::
3505 * Warning Message Control::
3506 * Debugging and Assertion Control::
3507 * Validity Checking::
3508 * Style Checking::
3509 * Run-Time Checks::
3510 * Using gcc for Syntax Checking::
3511 * Using gcc for Semantic Checking::
3512 * Compiling Different Versions of Ada::
3513 * Character Set Control::
3514 * File Naming Control::
3515 * Subprogram Inlining Control::
3516 * Auxiliary Output Control::
3517 * Debugging Control::
3518 * Exception Handling Control::
3519 * Units to Sources Mapping Files::
3520 * Integrated Preprocessing::
3521 * Code Generation Control::
3522 @ifset vms
3523 * Return Codes::
3524 @end ifset
3525 @end menu
3526
3527 @table @option
3528 @c !sort!
3529 @ifclear vms
3530 @cindex @option{-b} (@command{gcc})
3531 @item -b @var{target}
3532 Compile your program to run on @var{target}, which is the name of a
3533 system configuration. You must have a GNAT cross-compiler built if
3534 @var{target} is not the same as your host system.
3535
3536 @item -B@var{dir}
3537 @cindex @option{-B} (@command{gcc})
3538 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3539 from @var{dir} instead of the default location. Only use this switch
3540 when multiple versions of the GNAT compiler are available.
3541 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3542 GNU Compiler Collection (GCC)}, for further details. You would normally
3543 use the @option{-b} or @option{-V} switch instead.
3544
3545 @item -c
3546 @cindex @option{-c} (@command{gcc})
3547 Compile. Always use this switch when compiling Ada programs.
3548
3549 Note: for some other languages when using @command{gcc}, notably in
3550 the case of C and C++, it is possible to use
3551 use @command{gcc} without a @option{-c} switch to
3552 compile and link in one step. In the case of GNAT, you
3553 cannot use this approach, because the binder must be run
3554 and @command{gcc} cannot be used to run the GNAT binder.
3555 @end ifclear
3556
3557 @item -fcallgraph-info@r{[}=su,da@r{]}
3558 @cindex @option{-fcallgraph-info} (@command{gcc})
3559 Makes the compiler output callgraph information for the program, on a
3560 per-file basis. The information is generated in the VCG format. It can
3561 be decorated with additional, per-node and/or per-edge information, if a
3562 list of comma-separated markers is additionally specified. When the
3563 @var{su} marker is specified, the callgraph is decorated with stack usage information; it is equivalent to @option{-fstack-usage}. When the @var{da}
3564 marker is specified, the callgraph is decorated with information about
3565 dynamically allocated objects.
3566
3567 @item -fdump-scos
3568 @cindex @option{-fdump-scos} (@command{gcc})
3569 Generates SCO (Source Coverage Obligation) information in the ALI file.
3570 This information is used by advanced coverage tools. See unit @file{SCOs}
3571 in the compiler sources for details in files @file{scos.ads} and
3572 @file{scos.adb}.
3573
3574 @item -flto@r{[}=n@r{]}
3575 @cindex @option{-flto} (@command{gcc})
3576 Enables Link Time Optimization. This switch must be used in conjunction
3577 with the traditional @option{-Ox} switches and instructs the compiler to
3578 defer most optimizations until the link stage. The advantage of this
3579 approach is that the compiler can do a whole-program analysis and choose
3580 the best interprocedural optimization strategy based on a complete view
3581 of the program, instead of a fragmentary view with the usual approach.
3582 This can also speed up the compilation of huge programs and reduce the
3583 size of the final executable, compared with a per-unit compilation with
3584 full inlining across modules enabled with the @option{-gnatn2} switch.
3585 The drawback of this approach is that it may require much more memory.
3586 The switch, as well as the accompanying @option{-Ox} switches, must be
3587 specified both for the compilation and the link phases.
3588 If the @var{n} parameter is specified, the optimization and final code
3589 generation at link time are executed using @var{n} parallel jobs by
3590 means of an installed @command{make} program.
3591
3592 @item -fno-inline
3593 @cindex @option{-fno-inline} (@command{gcc})
3594 Suppresses all inlining, even if other optimization or inlining
3595 switches are set. This includes suppression of inlining that
3596 results from the use of the pragma @code{Inline_Always}.
3597 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3598 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3599 effects if this switch is present. Note that inlining can also
3600 be suppressed on a finer-grained basis with pragma @code{No_Inline}.
3601
3602 @item -fno-inline-functions
3603 @cindex @option{-fno-inline-functions} (@command{gcc})
3604 Suppresses automatic inlining of subprograms, which is enabled
3605 if @option{-O3} is used.
3606
3607 @item -fno-inline-small-functions
3608 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3609 Suppresses automatic inlining of small subprograms, which is enabled
3610 if @option{-O2} is used.
3611
3612 @item -fno-inline-functions-called-once
3613 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3614 Suppresses inlining of subprograms local to the unit and called once
3615 from within it, which is enabled if @option{-O1} is used.
3616
3617 @item -fno-ivopts
3618 @cindex @option{-fno-ivopts} (@command{gcc})
3619 Suppresses high-level loop induction variable optimizations, which are
3620 enabled if @option{-O1} is used. These optimizations are generally
3621 profitable but, for some specific cases of loops with numerous uses
3622 of the iteration variable that follow a common pattern, they may end
3623 up destroying the regularity that could be exploited at a lower level
3624 and thus producing inferior code.
3625
3626 @item -fno-strict-aliasing
3627 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3628 Causes the compiler to avoid assumptions regarding non-aliasing
3629 of objects of different types. See
3630 @ref{Optimization and Strict Aliasing} for details.
3631
3632 @item -fstack-check
3633 @cindex @option{-fstack-check} (@command{gcc})
3634 Activates stack checking.
3635 See @ref{Stack Overflow Checking} for details.
3636
3637 @item -fstack-usage
3638 @cindex @option{-fstack-usage} (@command{gcc})
3639 Makes the compiler output stack usage information for the program, on a
3640 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
3641
3642 @item ^-g^/DEBUG^
3643 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3644 Generate debugging information. This information is stored in the object
3645 file and copied from there to the final executable file by the linker,
3646 where it can be read by the debugger. You must use the
3647 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3648
3649 @item -gnat83
3650 @cindex @option{-gnat83} (@command{gcc})
3651 Enforce Ada 83 restrictions.
3652
3653 @item -gnat95
3654 @cindex @option{-gnat95} (@command{gcc})
3655 Enforce Ada 95 restrictions.
3656
3657 @item -gnat05
3658 @cindex @option{-gnat05} (@command{gcc})
3659 Allow full Ada 2005 features.
3660
3661 @item -gnat2005
3662 @cindex @option{-gnat2005} (@command{gcc})
3663 Allow full Ada 2005 features (same as @option{-gnat05})
3664
3665 @item -gnat12
3666 @cindex @option{-gnat12} (@command{gcc})
3667
3668 @item -gnat2012
3669 @cindex @option{-gnat2012} (@command{gcc})
3670 Allow full Ada 2012 features (same as @option{-gnat12})
3671
3672 @item -gnata
3673 @cindex @option{-gnata} (@command{gcc})
3674 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3675 activated. Note that these pragmas can also be controlled using the
3676 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3677 It also activates pragmas @code{Check}, @code{Precondition}, and
3678 @code{Postcondition}. Note that these pragmas can also be controlled
3679 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
3680 also activates all assertions defined in the RM as aspects: preconditions,
3681 postconditions, type invariants and (sub)type predicates. In all Ada modes,
3682 corresponding pragmas for type invariants and (sub)type predicates are
3683 also activated.
3684
3685 @item -gnatA
3686 @cindex @option{-gnatA} (@command{gcc})
3687 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
3688 it will be ignored.
3689
3690 @item -gnatb
3691 @cindex @option{-gnatb} (@command{gcc})
3692 Generate brief messages to @file{stderr} even if verbose mode set.
3693
3694 @item -gnatB
3695 @cindex @option{-gnatB} (@command{gcc})
3696 Assume no invalid (bad) values except for 'Valid attribute use
3697 (@pxref{Validity Checking}).
3698
3699 @item -gnatc
3700 @cindex @option{-gnatc} (@command{gcc})
3701 Check syntax and semantics only (no code generation attempted). When the
3702 compiler is invoked by @command{gnatmake}, if the switch @option{-gnatc} is
3703 only given to the compiler (after @option{-cargs} or in package Compiler of
3704 the project file, @command{gnatmake} will fail because it will not find the
3705 object file after compilation. If @command{gnatmake} is called with
3706 @option{-gnatc} as a builder switch (before @option{-cargs} or in package
3707 Builder of the project file) then @command{gnatmake} will not fail because
3708 it will not look for the object files after compilation, and it will not try
3709 to build and link. This switch may not be given if a previous @code{-gnatR}
3710 switch has been given, since @code{-gnatR} requires that the code generator
3711 be called to complete determination of representation information.
3712
3713 @item -gnatC
3714 @cindex @option{-gnatC} (@command{gcc})
3715 Generate CodePeer information (no code generation attempted).
3716 This switch will generate an intermediate representation suitable for
3717 use by CodePeer (@file{.scil} files). This switch is not compatible with
3718 code generation (it will, among other things, disable some switches such
3719 as -gnatn, and enable others such as -gnata).
3720
3721 @item -gnatd
3722 @cindex @option{-gnatd} (@command{gcc})
3723 Specify debug options for the compiler. The string of characters after
3724 the @option{-gnatd} specify the specific debug options. The possible
3725 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3726 compiler source file @file{debug.adb} for details of the implemented
3727 debug options. Certain debug options are relevant to applications
3728 programmers, and these are documented at appropriate points in this
3729 users guide.
3730
3731 @ifclear vms
3732 @item -gnatD
3733 @cindex @option{-gnatD[nn]} (@command{gcc})
3734 @end ifclear
3735 @ifset vms
3736 @item /XDEBUG /LXDEBUG=nnn
3737 @end ifset
3738 Create expanded source files for source level debugging. This switch
3739 also suppress generation of cross-reference information
3740 (see @option{-gnatx}). Note that this switch is not allowed if a previous
3741 -gnatR switch has been given, since these two switches are not compatible.
3742
3743 @item ^-gnateA^/ALIASING_CHECK^
3744 @cindex @option{-gnateA} (@command{gcc})
3745 Check that there is no aliasing between two parameters of the same subprogram.
3746
3747 @item -gnatec=@var{path}
3748 @cindex @option{-gnatec} (@command{gcc})
3749 Specify a configuration pragma file
3750 @ifclear vms
3751 (the equal sign is optional)
3752 @end ifclear
3753 (@pxref{The Configuration Pragmas Files}).
3754
3755 @item ^-gnated^/DISABLE_ATOMIC_SYNCHRONIZATION^
3756 @cindex @option{-gnated} (@command{gcc})
3757 Disable atomic synchronization
3758
3759 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
3760 @cindex @option{-gnateD} (@command{gcc})
3761 Defines a symbol, associated with @var{value}, for preprocessing.
3762 (@pxref{Integrated Preprocessing}).
3763
3764 @item -gnateE
3765 @cindex @option{-gnateE} (@command{gcc})
3766 Generate extra information in exception messages. In particular, display
3767 extra column information and the value and range associated with index and
3768 range check failures, and extra column information for access checks.
3769 In cases where the compiler is able to determine at compile time that
3770 a check will fail, it gives a warning, and the extra information is not
3771 produced at run time.
3772
3773 @item -gnatef
3774 @cindex @option{-gnatef} (@command{gcc})
3775 Display full source path name in brief error messages.
3776
3777 @item -gnateF
3778 @cindex @option{-gnateF} (@command{gcc})
3779 Check for overflow on all floating-point operations, including those
3780 for unconstrained predefined types. See description of pragma
3781 @code{Check_Float_Overflow} in GNAT RM.
3782
3783 @item -gnateG
3784 @cindex @option{-gnateG} (@command{gcc})
3785 Save result of preprocessing in a text file.
3786
3787 @item -gnatei@var{nnn}
3788 @cindex @option{-gnatei} (@command{gcc})
3789 Set maximum number of instantiations during compilation of a single unit to
3790 @var{nnn}. This may be useful in increasing the default maximum of 8000 for
3791 the rare case when a single unit legitimately exceeds this limit.
3792
3793 @item -gnateI@var{nnn}
3794 @cindex @option{-gnateI} (@command{gcc})
3795 Indicates that the source is a multi-unit source and that the index of the
3796 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
3797 to be a valid index in the multi-unit source.
3798
3799 @item -gnatem=@var{path}
3800 @cindex @option{-gnatem} (@command{gcc})
3801 Specify a mapping file
3802 @ifclear vms
3803 (the equal sign is optional)
3804 @end ifclear
3805 (@pxref{Units to Sources Mapping Files}).
3806
3807 @item -gnatep=@var{file}
3808 @cindex @option{-gnatep} (@command{gcc})
3809 Specify a preprocessing data file
3810 @ifclear vms
3811 (the equal sign is optional)
3812 @end ifclear
3813 (@pxref{Integrated Preprocessing}).
3814
3815 @item -gnateP
3816 @cindex @option{-gnateP} (@command{gcc})
3817 Turn categorization dependency errors into warnings.
3818 Ada requires that units that WITH one another have compatible categories, for
3819 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
3820 these errors become warnings (which can be ignored, or suppressed in the usual
3821 manner). This can be useful in some specialized circumstances such as the
3822 temporary use of special test software.
3823
3824 @item -gnateS
3825 @cindex @option{-gnateS} (@command{gcc})
3826 Synonym of @option{-fdump-scos}, kept for backards compatibility.
3827
3828 @item ^-gnatet^/TARGET_DEPENDENT_INFO^
3829 @cindex @option{-gnatet} (@command{gcc})
3830 Generate target dependent information.
3831
3832 @item ^-gnateV^/PARAMETER_VALIDITY_CHECK^
3833 @cindex @option{-gnateV} (@command{gcc})
3834 Check validity of subprogram parameters.
3835
3836 @item ^-gnateY^/IGNORE_SUPPRESS_SYLE_CHECK_PRAGMAS^
3837 @cindex @option{-gnateY} (@command{gcc})
3838 Ignore all STYLE_CHECKS pragmas. Full legality checks
3839 are still carried out, but the pragmas have no effect
3840 on what style checks are active. This allows all style
3841 checking options to be controlled from the command line.
3842
3843 @item -gnatE
3844 @cindex @option{-gnatE} (@command{gcc})
3845 Full dynamic elaboration checks.
3846
3847 @item -gnatf
3848 @cindex @option{-gnatf} (@command{gcc})
3849 Full errors. Multiple errors per line, all undefined references, do not
3850 attempt to suppress cascaded errors.
3851
3852 @item -gnatF
3853 @cindex @option{-gnatF} (@command{gcc})
3854 Externals names are folded to all uppercase.
3855
3856 @item ^-gnatg^/GNAT_INTERNAL^
3857 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
3858 Internal GNAT implementation mode. This should not be used for
3859 applications programs, it is intended only for use by the compiler
3860 and its run-time library. For documentation, see the GNAT sources.
3861 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
3862 @option{^-gnatwae^/WARNINGS=ALL,ERRORS^} and
3863 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
3864 so that all standard warnings and all standard style options are turned on.
3865 All warnings and style messages are treated as errors.
3866
3867 @ifclear vms
3868 @item -gnatG=nn
3869 @cindex @option{-gnatG[nn]} (@command{gcc})
3870 @end ifclear
3871 @ifset vms
3872 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
3873 @end ifset
3874 List generated expanded code in source form.
3875
3876 @item ^-gnath^/HELP^
3877 @cindex @option{^-gnath^/HELP^} (@command{gcc})
3878 Output usage information. The output is written to @file{stdout}.
3879
3880 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
3881 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
3882 Identifier character set
3883 @ifclear vms
3884 (@var{c}=1/2/3/4/8/9/p/f/n/w).
3885 @end ifclear
3886 For details of the possible selections for @var{c},
3887 see @ref{Character Set Control}.
3888
3889 @item ^-gnatI^/IGNORE_REP_CLAUSES^
3890 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
3891 Ignore representation clauses. When this switch is used,
3892 representation clauses are treated as comments. This is useful
3893 when initially porting code where you want to ignore rep clause
3894 problems, and also for compiling foreign code (particularly
3895 for use with ASIS). The representation clauses that are ignored
3896 are: enumeration_representation_clause, record_representation_clause,
3897 and attribute_definition_clause for the following attributes:
3898 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
3899 Object_Size, Size, Small, Stream_Size, and Value_Size.
3900 Note that this option should be used only for compiling -- the
3901 code is likely to malfunction at run time.
3902
3903 @item -gnatjnn
3904 @cindex @option{-gnatjnn} (@command{gcc})
3905 Reformat error messages to fit on nn character lines
3906
3907 @item -gnatk=@var{n}
3908 @cindex @option{-gnatk} (@command{gcc})
3909 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
3910
3911 @item -gnatl
3912 @cindex @option{-gnatl} (@command{gcc})
3913 Output full source listing with embedded error messages.
3914
3915 @item -gnatL
3916 @cindex @option{-gnatL} (@command{gcc})
3917 Used in conjunction with -gnatG or -gnatD to intersperse original
3918 source lines (as comment lines with line numbers) in the expanded
3919 source output.
3920
3921 @item -gnatm=@var{n}
3922 @cindex @option{-gnatm} (@command{gcc})
3923 Limit number of detected error or warning messages to @var{n}
3924 where @var{n} is in the range 1..999999. The default setting if
3925 no switch is given is 9999. If the number of warnings reaches this
3926 limit, then a message is output and further warnings are suppressed,
3927 but the compilation is continued. If the number of error messages
3928 reaches this limit, then a message is output and the compilation
3929 is abandoned. The equal sign here is optional. A value of zero
3930 means that no limit applies.
3931
3932 @item -gnatn[12]
3933 @cindex @option{-gnatn} (@command{gcc})
3934 Activate inlining for subprograms for which pragma @code{Inline} is
3935 specified. This inlining is performed by the GCC back-end. An optional
3936 digit sets the inlining level: 1 for moderate inlining across modules
3937 or 2 for full inlining across modules. If no inlining level is specified,
3938 the compiler will pick it based on the optimization level.
3939
3940 @item -gnatN
3941 @cindex @option{-gnatN} (@command{gcc})
3942 Activate front end inlining for subprograms for which
3943 pragma @code{Inline} is specified. This inlining is performed
3944 by the front end and will be visible in the
3945 @option{-gnatG} output.
3946
3947 When using a gcc-based back end (in practice this means using any version
3948 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
3949 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
3950 Historically front end inlining was more extensive than the gcc back end
3951 inlining, but that is no longer the case.
3952
3953 @item -gnato??
3954 @cindex @option{-gnato??} (@command{gcc})
3955 Set default mode for handling generation of code to avoid intermediate
3956 arithmetic overflow. Here `@code{??}' is two digits, a
3957 single digit, or nothing. Each digit is one of the digits `@code{1}'
3958 through `@code{3}':
3959
3960 @itemize @bullet
3961 @item @code{1}:
3962 all intermediate overflows checked against base type (@code{STRICT})
3963 @item @code{2}:
3964 minimize intermediate overflows (@code{MINIMIZED})
3965 @item @code{3}:
3966 eliminate intermediate overflows (@code{ELIMINATED})
3967 @end itemize
3968
3969 If only one digit appears then it applies to all
3970 cases; if two digits are given, then the first applies outside
3971 assertions, and the second within assertions.
3972
3973 If no digits follow the @option{-gnato}, then it is equivalent to
3974 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
3975 causing all intermediate overflows to be handled in strict mode.
3976
3977 This switch also causes arithmetic overflow checking to be performed
3978 (as though pragma @code{Unsuppress (Overflow_Mode)} has been specified.
3979
3980 The default if no option @option{-gnato} is given is that overflow handling
3981 is in @code{STRICT} mode (computations done using the base type), and that
3982 overflow checking is suppressed.
3983
3984 Note that division by zero is a separate check that is not
3985 controlled by this switch (division by zero checking is on by default).
3986
3987 See also @ref{Specifying the Desired Mode}.
3988
3989 @item -gnatp
3990 @cindex @option{-gnatp} (@command{gcc})
3991 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
3992 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
3993
3994 @item -gnat-p
3995 @cindex @option{-gnat-p} (@command{gcc})
3996 Cancel effect of previous @option{-gnatp} switch.
3997
3998 @item -gnatP
3999 @cindex @option{-gnatP} (@command{gcc})
4000 Enable polling. This is required on some systems (notably Windows NT) to
4001 obtain asynchronous abort and asynchronous transfer of control capability.
4002 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4003 details.
4004
4005 @item -gnatq
4006 @cindex @option{-gnatq} (@command{gcc})
4007 Don't quit. Try semantics, even if parse errors.
4008
4009 @item -gnatQ
4010 @cindex @option{-gnatQ} (@command{gcc})
4011 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4012
4013 @item -gnatr
4014 @cindex @option{-gnatr} (@command{gcc})
4015 Treat pragma Restrictions as Restriction_Warnings.
4016
4017 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4018 @cindex @option{-gnatR} (@command{gcc})
4019 Output representation information for declared types and objects.
4020 Note that this switch is not allowed if a previous @code{-gnatD} switch has
4021 been given, since these two switches are not compatible. It is also not allowed
4022 if a previous @code{-gnatc} switch has been given, since we must be generating
4023 code to be able to determine representation information.
4024
4025 @item ^-gnatRm[s]^/REPRESENTATION_INFO^
4026 Output convention and parameter passing mechanisms for all subprograms.
4027 This form is also incompatible with the use of @code{-gnatc}.
4028
4029 @item -gnats
4030 @cindex @option{-gnats} (@command{gcc})
4031 Syntax check only.
4032
4033 @item -gnatS
4034 @cindex @option{-gnatS} (@command{gcc})
4035 Print package Standard.
4036
4037 @item -gnatt
4038 @cindex @option{-gnatt} (@command{gcc})
4039 Generate tree output file.
4040
4041 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4042 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4043 All compiler tables start at @var{nnn} times usual starting size.
4044
4045 @item -gnatu
4046 @cindex @option{-gnatu} (@command{gcc})
4047 List units for this compilation.
4048
4049 @item -gnatU
4050 @cindex @option{-gnatU} (@command{gcc})
4051 Tag all error messages with the unique string ``error:''
4052
4053 @item -gnatv
4054 @cindex @option{-gnatv} (@command{gcc})
4055 Verbose mode. Full error output with source lines to @file{stdout}.
4056
4057 @item -gnatV
4058 @cindex @option{-gnatV} (@command{gcc})
4059 Control level of validity checking (@pxref{Validity Checking}).
4060
4061 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4062 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4063 Warning mode where
4064 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4065 the exact warnings that
4066 are enabled or disabled (@pxref{Warning Message Control}).
4067
4068 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4069 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4070 Wide character encoding method
4071 @ifclear vms
4072 (@var{e}=n/h/u/s/e/8).
4073 @end ifclear
4074 @ifset vms
4075 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4076 @end ifset
4077
4078 @item -gnatx
4079 @cindex @option{-gnatx} (@command{gcc})
4080 Suppress generation of cross-reference information.
4081
4082 @item -gnatX
4083 @cindex @option{-gnatX} (@command{gcc})
4084 Enable GNAT implementation extensions and latest Ada version.
4085
4086 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4087 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4088 Enable built-in style checks (@pxref{Style Checking}).
4089
4090 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4091 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4092 Distribution stub generation and compilation
4093 @ifclear vms
4094 (@var{m}=r/c for receiver/caller stubs).
4095 @end ifclear
4096 @ifset vms
4097 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4098 to be generated and compiled).
4099 @end ifset
4100
4101 @item ^-I^/SEARCH=^@var{dir}
4102 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4103 @cindex RTL
4104 Direct GNAT to search the @var{dir} directory for source files needed by
4105 the current compilation
4106 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4107
4108 @item ^-I-^/NOCURRENT_DIRECTORY^
4109 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4110 @cindex RTL
4111 Except for the source file named in the command line, do not look for source
4112 files in the directory containing the source file named in the command line
4113 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4114
4115 @ifclear vms
4116 @item -mbig-switch
4117 @cindex @option{-mbig-switch} (@command{gcc})
4118 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4119 This standard gcc switch causes the compiler to use larger offsets in its
4120 jump table representation for @code{case} statements.
4121 This may result in less efficient code, but is sometimes necessary
4122 (for example on HP-UX targets)
4123 @cindex HP-UX and @option{-mbig-switch} option
4124 in order to compile large and/or nested @code{case} statements.
4125
4126 @item -o @var{file}
4127 @cindex @option{-o} (@command{gcc})
4128 This switch is used in @command{gcc} to redirect the generated object file
4129 and its associated ALI file. Beware of this switch with GNAT, because it may
4130 cause the object file and ALI file to have different names which in turn
4131 may confuse the binder and the linker.
4132 @end ifclear
4133
4134 @item -nostdinc
4135 @cindex @option{-nostdinc} (@command{gcc})
4136 Inhibit the search of the default location for the GNAT Run Time
4137 Library (RTL) source files.
4138
4139 @item -nostdlib
4140 @cindex @option{-nostdlib} (@command{gcc})
4141 Inhibit the search of the default location for the GNAT Run Time
4142 Library (RTL) ALI files.
4143
4144 @ifclear vms
4145 @c @item -O@ovar{n}
4146 @c Expanding @ovar macro inline (explanation in macro def comments)
4147 @item -O@r{[}@var{n}@r{]}
4148 @cindex @option{-O} (@command{gcc})
4149 @var{n} controls the optimization level.
4150
4151 @table @asis
4152 @item n = 0
4153 No optimization, the default setting if no @option{-O} appears
4154
4155 @item n = 1
4156 Normal optimization, the default if you specify @option{-O} without
4157 an operand. A good compromise between code quality and compilation
4158 time.
4159
4160 @item n = 2
4161 Extensive optimization, may improve execution time, possibly at the cost of
4162 substantially increased compilation time.
4163
4164 @item n = 3
4165 Same as @option{-O2}, and also includes inline expansion for small subprograms
4166 in the same unit.
4167
4168 @item n = s
4169 Optimize space usage
4170 @end table
4171
4172 @noindent
4173 See also @ref{Optimization Levels}.
4174 @end ifclear
4175
4176 @ifset vms
4177 @item /NOOPTIMIZE
4178 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4179 Equivalent to @option{/OPTIMIZE=NONE}.
4180 This is the default behavior in the absence of an @option{/OPTIMIZE}
4181 qualifier.
4182
4183 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4184 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4185 Selects the level of optimization for your program. The supported
4186 keywords are as follows:
4187 @table @code
4188 @item ALL
4189 Perform most optimizations, including those that
4190 are expensive.
4191 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4192 without keyword options.
4193
4194 @item NONE
4195 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4196
4197 @item SOME
4198 Perform some optimizations, but omit ones that are costly.
4199
4200 @item DEVELOPMENT
4201 Same as @code{SOME}.
4202
4203 @item INLINING
4204 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4205 automatic inlining of small subprograms within a unit
4206
4207 @item UNROLL_LOOPS
4208 Try to unroll loops. This keyword may be specified together with
4209 any keyword above other than @code{NONE}. Loop unrolling
4210 usually, but not always, improves the performance of programs.
4211
4212 @item SPACE
4213 Optimize space usage
4214 @end table
4215
4216 @noindent
4217 See also @ref{Optimization Levels}.
4218 @end ifset
4219
4220 @ifclear vms
4221 @item -pass-exit-codes
4222 @cindex @option{-pass-exit-codes} (@command{gcc})
4223 Catch exit codes from the compiler and use the most meaningful as
4224 exit status.
4225 @end ifclear
4226
4227 @item --RTS=@var{rts-path}
4228 @cindex @option{--RTS} (@command{gcc})
4229 Specifies the default location of the runtime library. Same meaning as the
4230 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4231
4232 @item ^-S^/ASM^
4233 @cindex @option{^-S^/ASM^} (@command{gcc})
4234 ^Used in place of @option{-c} to^Used to^
4235 cause the assembler source file to be
4236 generated, using @file{^.s^.S^} as the extension,
4237 instead of the object file.
4238 This may be useful if you need to examine the generated assembly code.
4239
4240 @item ^-fverbose-asm^/VERBOSE_ASM^
4241 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4242 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4243 to cause the generated assembly code file to be annotated with variable
4244 names, making it significantly easier to follow.
4245
4246 @item ^-v^/VERBOSE^
4247 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4248 Show commands generated by the @command{gcc} driver. Normally used only for
4249 debugging purposes or if you need to be sure what version of the
4250 compiler you are executing.
4251
4252 @ifclear vms
4253 @item -V @var{ver}
4254 @cindex @option{-V} (@command{gcc})
4255 Execute @var{ver} version of the compiler. This is the @command{gcc}
4256 version, not the GNAT version.
4257 @end ifclear
4258
4259 @item ^-w^/NO_BACK_END_WARNINGS^
4260 @cindex @option{-w} (@command{gcc})
4261 Turn off warnings generated by the back end of the compiler. Use of
4262 this switch also causes the default for front end warnings to be set
4263 to suppress (as though @option{-gnatws} had appeared at the start of
4264 the options).
4265
4266 @end table
4267
4268 @ifclear vms
4269 @c Combining qualifiers does not work on VMS
4270 You may combine a sequence of GNAT switches into a single switch. For
4271 example, the combined switch
4272
4273 @cindex Combining GNAT switches
4274 @smallexample
4275 -gnatofi3
4276 @end smallexample
4277
4278 @noindent
4279 is equivalent to specifying the following sequence of switches:
4280
4281 @smallexample
4282 -gnato -gnatf -gnati3
4283 @end smallexample
4284 @end ifclear
4285
4286 @noindent
4287 The following restrictions apply to the combination of switches
4288 in this manner:
4289
4290 @itemize @bullet
4291 @item
4292 The switch @option{-gnatc} if combined with other switches must come
4293 first in the string.
4294
4295 @item
4296 The switch @option{-gnats} if combined with other switches must come
4297 first in the string.
4298
4299 @item
4300 The switches
4301 ^^@option{/DISTRIBUTION_STUBS=},^
4302 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4303 switches, and only one of them may appear in the command line.
4304
4305 @item
4306 The switch @option{-gnat-p} may not be combined with any other switch.
4307
4308 @ifclear vms
4309 @item
4310 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4311 switch), then all further characters in the switch are interpreted
4312 as style modifiers (see description of @option{-gnaty}).
4313
4314 @item
4315 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4316 switch), then all further characters in the switch are interpreted
4317 as debug flags (see description of @option{-gnatd}).
4318
4319 @item
4320 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4321 switch), then all further characters in the switch are interpreted
4322 as warning mode modifiers (see description of @option{-gnatw}).
4323
4324 @item
4325 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4326 switch), then all further characters in the switch are interpreted
4327 as validity checking options (@pxref{Validity Checking}).
4328
4329 @item
4330 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4331 a combined list of options.
4332 @end ifclear
4333 @end itemize
4334
4335 @node Output and Error Message Control
4336 @subsection Output and Error Message Control
4337 @findex stderr
4338
4339 @noindent
4340 The standard default format for error messages is called ``brief format''.
4341 Brief format messages are written to @file{stderr} (the standard error
4342 file) and have the following form:
4343
4344 @smallexample
4345 e.adb:3:04: Incorrect spelling of keyword "function"
4346 e.adb:4:20: ";" should be "is"
4347 @end smallexample
4348
4349 @noindent
4350 The first integer after the file name is the line number in the file,
4351 and the second integer is the column number within the line.
4352 @ifclear vms
4353 @code{GPS} can parse the error messages
4354 and point to the referenced character.
4355 @end ifclear
4356 The following switches provide control over the error message
4357 format:
4358
4359 @table @option
4360 @c !sort!
4361 @item -gnatv
4362 @cindex @option{-gnatv} (@command{gcc})
4363 @findex stdout
4364 @ifclear vms
4365 The v stands for verbose.
4366 @end ifclear
4367 The effect of this setting is to write long-format error
4368 messages to @file{stdout} (the standard output file.
4369 The same program compiled with the
4370 @option{-gnatv} switch would generate:
4371
4372 @smallexample
4373 @cartouche
4374 3. funcion X (Q : Integer)
4375 |
4376 >>> Incorrect spelling of keyword "function"
4377 4. return Integer;
4378 |
4379 >>> ";" should be "is"
4380 @end cartouche
4381 @end smallexample
4382
4383 @noindent
4384 The vertical bar indicates the location of the error, and the @samp{>>>}
4385 prefix can be used to search for error messages. When this switch is
4386 used the only source lines output are those with errors.
4387
4388 @item -gnatl
4389 @cindex @option{-gnatl} (@command{gcc})
4390 @ifclear vms
4391 The @code{l} stands for list.
4392 @end ifclear
4393 This switch causes a full listing of
4394 the file to be generated. In the case where a body is
4395 compiled, the corresponding spec is also listed, along
4396 with any subunits. Typical output from compiling a package
4397 body @file{p.adb} might look like:
4398
4399 @smallexample @c ada
4400 @cartouche
4401 Compiling: p.adb
4402
4403 1. package body p is
4404 2. procedure a;
4405 3. procedure a is separate;
4406 4. begin
4407 5. null
4408 |
4409 >>> missing ";"
4410
4411 6. end;
4412
4413 Compiling: p.ads
4414
4415 1. package p is
4416 2. pragma Elaborate_Body
4417 |
4418 >>> missing ";"
4419
4420 3. end p;
4421
4422 Compiling: p-a.adb
4423
4424 1. separate p
4425 |
4426 >>> missing "("
4427
4428 2. procedure a is
4429 3. begin
4430 4. null
4431 |
4432 >>> missing ";"
4433
4434 5. end;
4435 @end cartouche
4436 @end smallexample
4437
4438 @noindent
4439 @findex stderr
4440 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4441 standard output is redirected, a brief summary is written to
4442 @file{stderr} (standard error) giving the number of error messages and
4443 warning messages generated.
4444
4445 @item ^-gnatl^/OUTPUT_FILE^=file
4446 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4447 This has the same effect as @option{-gnatl} except that the output is
4448 written to a file instead of to standard output. If the given name
4449 @file{fname} does not start with a period, then it is the full name
4450 of the file to be written. If @file{fname} is an extension, it is
4451 appended to the name of the file being compiled. For example, if
4452 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4453 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4454
4455 @item -gnatU
4456 @cindex @option{-gnatU} (@command{gcc})
4457 This switch forces all error messages to be preceded by the unique
4458 string ``error:''. This means that error messages take a few more
4459 characters in space, but allows easy searching for and identification
4460 of error messages.
4461
4462 @item -gnatb
4463 @cindex @option{-gnatb} (@command{gcc})
4464 @ifclear vms
4465 The @code{b} stands for brief.
4466 @end ifclear
4467 This switch causes GNAT to generate the
4468 brief format error messages to @file{stderr} (the standard error
4469 file) as well as the verbose
4470 format message or full listing (which as usual is written to
4471 @file{stdout} (the standard output file).
4472
4473 @item -gnatm=@var{n}
4474 @cindex @option{-gnatm} (@command{gcc})
4475 @ifclear vms
4476 The @code{m} stands for maximum.
4477 @end ifclear
4478 @var{n} is a decimal integer in the
4479 range of 1 to 999999 and limits the number of error or warning
4480 messages to be generated. For example, using
4481 @option{-gnatm2} might yield
4482
4483 @smallexample
4484 e.adb:3:04: Incorrect spelling of keyword "function"
4485 e.adb:5:35: missing ".."
4486 fatal error: maximum number of errors detected
4487 compilation abandoned
4488 @end smallexample
4489
4490 @noindent
4491 The default setting if
4492 no switch is given is 9999. If the number of warnings reaches this
4493 limit, then a message is output and further warnings are suppressed,
4494 but the compilation is continued. If the number of error messages
4495 reaches this limit, then a message is output and the compilation
4496 is abandoned. A value of zero means that no limit applies.
4497
4498 @noindent
4499 Note that the equal sign is optional, so the switches
4500 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4501
4502 @item -gnatf
4503 @cindex @option{-gnatf} (@command{gcc})
4504 @cindex Error messages, suppressing
4505 @ifclear vms
4506 The @code{f} stands for full.
4507 @end ifclear
4508 Normally, the compiler suppresses error messages that are likely to be
4509 redundant. This switch causes all error
4510 messages to be generated. In particular, in the case of
4511 references to undefined variables. If a given variable is referenced
4512 several times, the normal format of messages is
4513 @smallexample
4514 e.adb:7:07: "V" is undefined (more references follow)
4515 @end smallexample
4516
4517 @noindent
4518 where the parenthetical comment warns that there are additional
4519 references to the variable @code{V}. Compiling the same program with the
4520 @option{-gnatf} switch yields
4521
4522 @smallexample
4523 e.adb:7:07: "V" is undefined
4524 e.adb:8:07: "V" is undefined
4525 e.adb:8:12: "V" is undefined
4526 e.adb:8:16: "V" is undefined
4527 e.adb:9:07: "V" is undefined
4528 e.adb:9:12: "V" is undefined
4529 @end smallexample
4530
4531 @noindent
4532 The @option{-gnatf} switch also generates additional information for
4533 some error messages. Some examples are:
4534
4535 @itemize @bullet
4536 @item
4537 Details on possibly non-portable unchecked conversion
4538 @item
4539 List possible interpretations for ambiguous calls
4540 @item
4541 Additional details on incorrect parameters
4542 @end itemize
4543
4544 @item -gnatjnn
4545 @cindex @option{-gnatjnn} (@command{gcc})
4546 In normal operation mode (or if @option{-gnatj0} is used), then error messages
4547 with continuation lines are treated as though the continuation lines were
4548 separate messages (and so a warning with two continuation lines counts as
4549 three warnings, and is listed as three separate messages).
4550
4551 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4552 messages are output in a different manner. A message and all its continuation
4553 lines are treated as a unit, and count as only one warning or message in the
4554 statistics totals. Furthermore, the message is reformatted so that no line
4555 is longer than nn characters.
4556
4557 @item -gnatq
4558 @cindex @option{-gnatq} (@command{gcc})
4559 @ifclear vms
4560 The @code{q} stands for quit (really ``don't quit'').
4561 @end ifclear
4562 In normal operation mode, the compiler first parses the program and
4563 determines if there are any syntax errors. If there are, appropriate
4564 error messages are generated and compilation is immediately terminated.
4565 This switch tells
4566 GNAT to continue with semantic analysis even if syntax errors have been
4567 found. This may enable the detection of more errors in a single run. On
4568 the other hand, the semantic analyzer is more likely to encounter some
4569 internal fatal error when given a syntactically invalid tree.
4570
4571 @item -gnatQ
4572 @cindex @option{-gnatQ} (@command{gcc})
4573 In normal operation mode, the @file{ALI} file is not generated if any
4574 illegalities are detected in the program. The use of @option{-gnatQ} forces
4575 generation of the @file{ALI} file. This file is marked as being in
4576 error, so it cannot be used for binding purposes, but it does contain
4577 reasonably complete cross-reference information, and thus may be useful
4578 for use by tools (e.g., semantic browsing tools or integrated development
4579 environments) that are driven from the @file{ALI} file. This switch
4580 implies @option{-gnatq}, since the semantic phase must be run to get a
4581 meaningful ALI file.
4582
4583 In addition, if @option{-gnatt} is also specified, then the tree file is
4584 generated even if there are illegalities. It may be useful in this case
4585 to also specify @option{-gnatq} to ensure that full semantic processing
4586 occurs. The resulting tree file can be processed by ASIS, for the purpose
4587 of providing partial information about illegal units, but if the error
4588 causes the tree to be badly malformed, then ASIS may crash during the
4589 analysis.
4590
4591 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4592 being in error, @command{gnatmake} will attempt to recompile the source when it
4593 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4594
4595 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4596 since ALI files are never generated if @option{-gnats} is set.
4597
4598 @end table
4599
4600 @node Warning Message Control
4601 @subsection Warning Message Control
4602 @cindex Warning messages
4603 @noindent
4604 In addition to error messages, which correspond to illegalities as defined
4605 in the Ada Reference Manual, the compiler detects two kinds of warning
4606 situations.
4607
4608 First, the compiler considers some constructs suspicious and generates a
4609 warning message to alert you to a possible error. Second, if the
4610 compiler detects a situation that is sure to raise an exception at
4611 run time, it generates a warning message. The following shows an example
4612 of warning messages:
4613 @smallexample
4614 e.adb:4:24: warning: creation of object may raise Storage_Error
4615 e.adb:10:17: warning: static value out of range
4616 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4617 @end smallexample
4618
4619 @noindent
4620 GNAT considers a large number of situations as appropriate
4621 for the generation of warning messages. As always, warnings are not
4622 definite indications of errors. For example, if you do an out-of-range
4623 assignment with the deliberate intention of raising a
4624 @code{Constraint_Error} exception, then the warning that may be
4625 issued does not indicate an error. Some of the situations for which GNAT
4626 issues warnings (at least some of the time) are given in the following
4627 list. This list is not complete, and new warnings are often added to
4628 subsequent versions of GNAT. The list is intended to give a general idea
4629 of the kinds of warnings that are generated.
4630
4631 @itemize @bullet
4632 @item
4633 Possible infinitely recursive calls
4634
4635 @item
4636 Out-of-range values being assigned
4637
4638 @item
4639 Possible order of elaboration problems
4640
4641 @item
4642 Assertions (pragma Assert) that are sure to fail
4643
4644 @item
4645 Unreachable code
4646
4647 @item
4648 Address clauses with possibly unaligned values, or where an attempt is
4649 made to overlay a smaller variable with a larger one.
4650
4651 @item
4652 Fixed-point type declarations with a null range
4653
4654 @item
4655 Direct_IO or Sequential_IO instantiated with a type that has access values
4656
4657 @item
4658 Variables that are never assigned a value
4659
4660 @item
4661 Variables that are referenced before being initialized
4662
4663 @item
4664 Task entries with no corresponding @code{accept} statement
4665
4666 @item
4667 Duplicate accepts for the same task entry in a @code{select}
4668
4669 @item
4670 Objects that take too much storage
4671
4672 @item
4673 Unchecked conversion between types of differing sizes
4674
4675 @item
4676 Missing @code{return} statement along some execution path in a function
4677
4678 @item
4679 Incorrect (unrecognized) pragmas
4680
4681 @item
4682 Incorrect external names
4683
4684 @item
4685 Allocation from empty storage pool
4686
4687 @item
4688 Potentially blocking operation in protected type
4689
4690 @item
4691 Suspicious parenthesization of expressions
4692
4693 @item
4694 Mismatching bounds in an aggregate
4695
4696 @item
4697 Attempt to return local value by reference
4698
4699 @item
4700 Premature instantiation of a generic body
4701
4702 @item
4703 Attempt to pack aliased components
4704
4705 @item
4706 Out of bounds array subscripts
4707
4708 @item
4709 Wrong length on string assignment
4710
4711 @item
4712 Violations of style rules if style checking is enabled
4713
4714 @item
4715 Unused @code{with} clauses
4716
4717 @item
4718 @code{Bit_Order} usage that does not have any effect
4719
4720 @item
4721 @code{Standard.Duration} used to resolve universal fixed expression
4722
4723 @item
4724 Dereference of possibly null value
4725
4726 @item
4727 Declaration that is likely to cause storage error
4728
4729 @item
4730 Internal GNAT unit @code{with}'ed by application unit
4731
4732 @item
4733 Values known to be out of range at compile time
4734
4735 @item
4736 Unreferenced labels and variables
4737
4738 @item
4739 Address overlays that could clobber memory
4740
4741 @item
4742 Unexpected initialization when address clause present
4743
4744 @item
4745 Bad alignment for address clause
4746
4747 @item
4748 Useless type conversions
4749
4750 @item
4751 Redundant assignment statements and other redundant constructs
4752
4753 @item
4754 Useless exception handlers
4755
4756 @item
4757 Accidental hiding of name by child unit
4758
4759 @item
4760 Access before elaboration detected at compile time
4761
4762 @item
4763 A range in a @code{for} loop that is known to be null or might be null
4764
4765 @end itemize
4766
4767 @noindent
4768 The following section lists compiler switches that are available
4769 to control the handling of warning messages. It is also possible
4770 to exercise much finer control over what warnings are issued and
4771 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
4772 gnat_rm, GNAT Reference manual}.
4773
4774 @table @option
4775 @c !sort!
4776 @item -gnatwa
4777 @emph{Activate most optional warnings.}
4778 @cindex @option{-gnatwa} (@command{gcc})
4779 This switch activates most optional warning messages. See the remaining list
4780 in this section for details on optional warning messages that can be
4781 individually controlled. The warnings that are not turned on by this
4782 switch are
4783 @option{-gnatwd} (implicit dereferencing),
4784 @option{-gnatwh} (hiding),
4785 @option{-gnatw.d} (tag warnings with -gnatw switch)
4786 @option{-gnatw.h} (holes (gaps) in record layouts)
4787 @option{-gnatw.i} (overlapping actuals),
4788 @option{-gnatw.k} (redefinition of names in standard),
4789 @option{-gnatwl} (elaboration warnings),
4790 @option{-gnatw.l} (inherited aspects),
4791 @option{-gnatw.o} (warn on values set by out parameters ignored),
4792 @option{-gnatwt} (tracking of deleted conditional code)
4793 and @option{-gnatw.u} (unordered enumeration),
4794 All other optional warnings are turned on.
4795
4796 @item -gnatwA
4797 @emph{Suppress all optional errors.}
4798 @cindex @option{-gnatwA} (@command{gcc})
4799 This switch suppresses all optional warning messages, see remaining list
4800 in this section for details on optional warning messages that can be
4801 individually controlled. Note that unlike switch @option{-gnatws}, the
4802 use of switch @option{-gnatwA} does not suppress warnings that are
4803 normally given unconditionally and cannot be individually controlled
4804 (for example, the warning about a missing exit path in a function).
4805 Also, again unlike switch @option{-gnatws}, warnings suppressed by
4806 the use of switch @option{-gnatwA} can be individually turned back
4807 on. For example the use of switch @option{-gnatwA} followed by
4808 switch @option{-gnatwd} will suppress all optional warnings except
4809 the warnings for implicit dereferencing.
4810
4811 @item -gnatw.a
4812 @emph{Activate warnings on failing assertions.}
4813 @cindex @option{-gnatw.a} (@command{gcc})
4814 @cindex Assert failures
4815 This switch activates warnings for assertions where the compiler can tell at
4816 compile time that the assertion will fail. Note that this warning is given
4817 even if assertions are disabled. The default is that such warnings are
4818 generated.
4819
4820 @item -gnatw.A
4821 @emph{Suppress warnings on failing assertions.}
4822 @cindex @option{-gnatw.A} (@command{gcc})
4823 @cindex Assert failures
4824 This switch suppresses warnings for assertions where the compiler can tell at
4825 compile time that the assertion will fail.
4826
4827 @item -gnatwb
4828 @emph{Activate warnings on bad fixed values.}
4829 @cindex @option{-gnatwb} (@command{gcc})
4830 @cindex Bad fixed values
4831 @cindex Fixed-point Small value
4832 @cindex Small value
4833 This switch activates warnings for static fixed-point expressions whose
4834 value is not an exact multiple of Small. Such values are implementation
4835 dependent, since an implementation is free to choose either of the multiples
4836 that surround the value. GNAT always chooses the closer one, but this is not
4837 required behavior, and it is better to specify a value that is an exact
4838 multiple, ensuring predictable execution. The default is that such warnings
4839 are not generated.
4840
4841 @item -gnatwB
4842 @emph{Suppress warnings on bad fixed values.}
4843 @cindex @option{-gnatwB} (@command{gcc})
4844 This switch suppresses warnings for static fixed-point expressions whose
4845 value is not an exact multiple of Small.
4846
4847 @item -gnatw.b
4848 @emph{Activate warnings on biased representation.}
4849 @cindex @option{-gnatw.b} (@command{gcc})
4850 @cindex Biased representation
4851 This switch activates warnings when a size clause, value size clause, component
4852 clause, or component size clause forces the use of biased representation for an
4853 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
4854 to represent 10/11). The default is that such warnings are generated.
4855
4856 @item -gnatw.B
4857 @emph{Suppress warnings on biased representation.}
4858 @cindex @option{-gnatwB} (@command{gcc})
4859 This switch suppresses warnings for representation clauses that force the use
4860 of biased representation.
4861
4862 @item -gnatwc
4863 @emph{Activate warnings on conditionals.}
4864 @cindex @option{-gnatwc} (@command{gcc})
4865 @cindex Conditionals, constant
4866 This switch activates warnings for conditional expressions used in
4867 tests that are known to be True or False at compile time. The default
4868 is that such warnings are not generated.
4869 Note that this warning does
4870 not get issued for the use of boolean variables or constants whose
4871 values are known at compile time, since this is a standard technique
4872 for conditional compilation in Ada, and this would generate too many
4873 false positive warnings.
4874
4875 This warning option also activates a special test for comparisons using
4876 the operators ``>='' and`` <=''.
4877 If the compiler can tell that only the equality condition is possible,
4878 then it will warn that the ``>'' or ``<'' part of the test
4879 is useless and that the operator could be replaced by ``=''.
4880 An example would be comparing a @code{Natural} variable <= 0.
4881
4882 This warning option also generates warnings if
4883 one or both tests is optimized away in a membership test for integer
4884 values if the result can be determined at compile time. Range tests on
4885 enumeration types are not included, since it is common for such tests
4886 to include an end point.
4887
4888 This warning can also be turned on using @option{-gnatwa}.
4889
4890 @item -gnatwC
4891 @emph{Suppress warnings on conditionals.}
4892 @cindex @option{-gnatwC} (@command{gcc})
4893 This switch suppresses warnings for conditional expressions used in
4894 tests that are known to be True or False at compile time.
4895
4896 @item -gnatw.c
4897 @emph{Activate warnings on missing component clauses.}
4898 @cindex @option{-gnatw.c} (@command{gcc})
4899 @cindex Component clause, missing
4900 This switch activates warnings for record components where a record
4901 representation clause is present and has component clauses for the
4902 majority, but not all, of the components. A warning is given for each
4903 component for which no component clause is present.
4904
4905 This warning can also be turned on using @option{-gnatwa}.
4906
4907 @item -gnatw.C
4908 @emph{Suppress warnings on missing component clauses.}
4909 @cindex @option{-gnatwC} (@command{gcc})
4910 This switch suppresses warnings for record components that are
4911 missing a component clause in the situation described above.
4912
4913 @item -gnatwd
4914 @emph{Activate warnings on implicit dereferencing.}
4915 @cindex @option{-gnatwd} (@command{gcc})
4916 If this switch is set, then the use of a prefix of an access type
4917 in an indexed component, slice, or selected component without an
4918 explicit @code{.all} will generate a warning. With this warning
4919 enabled, access checks occur only at points where an explicit
4920 @code{.all} appears in the source code (assuming no warnings are
4921 generated as a result of this switch). The default is that such
4922 warnings are not generated.
4923 Note that @option{-gnatwa} does not affect the setting of
4924 this warning option.
4925
4926 @item -gnatwD
4927 @emph{Suppress warnings on implicit dereferencing.}
4928 @cindex @option{-gnatwD} (@command{gcc})
4929 @cindex Implicit dereferencing
4930 @cindex Dereferencing, implicit
4931 This switch suppresses warnings for implicit dereferences in
4932 indexed components, slices, and selected components.
4933
4934 @item -gnatw.d
4935 @emph{Activate tagging of warning messages.}
4936 @cindex @option{-gnatw.d} (@command{gcc})
4937 If this switch is set, then warning messages are tagged, either with
4938 the string ``@option{-gnatw?}'' showing which switch controls the warning,
4939 or with ``[enabled by default]'' if the warning is not under control of a
4940 specific @option{-gnatw?} switch. This mode is off by default, and is not
4941 affected by the use of @code{-gnatwa}.
4942
4943 @item -gnatw.D
4944 @emph{Deactivate tagging of warning messages.}
4945 @cindex @option{-gnatw.d} (@command{gcc})
4946 If this switch is set, then warning messages return to the default
4947 mode in which warnings are not tagged as described above for
4948 @code{-gnatw.d}.
4949
4950 @item -gnatwe
4951 @emph{Treat warnings and style checks as errors.}
4952 @cindex @option{-gnatwe} (@command{gcc})
4953 @cindex Warnings, treat as error
4954 This switch causes warning messages and style check messages to be
4955 treated as errors.
4956 The warning string still appears, but the warning messages are counted
4957 as errors, and prevent the generation of an object file. Note that this
4958 is the only -gnatw switch that affects the handling of style check messages.
4959
4960 @item -gnatw.e
4961 @emph{Activate every optional warning}
4962 @cindex @option{-gnatw.e} (@command{gcc})
4963 @cindex Warnings, activate every optional warning
4964 This switch activates all optional warnings, including those which
4965 are not activated by @code{-gnatwa}. The use of this switch is not
4966 recommended for normal use. If you turn this switch on, it is almost
4967 certain that you will get large numbers of useless warnings. The
4968 warnings that are excluded from @code{-gnatwa} are typically highly
4969 specialized warnings that are suitable for use only in code that has
4970 been specifically designed according to specialized coding rules.
4971
4972 @item -gnatwf
4973 @emph{Activate warnings on unreferenced formals.}
4974 @cindex @option{-gnatwf} (@command{gcc})
4975 @cindex Formals, unreferenced
4976 This switch causes a warning to be generated if a formal parameter
4977 is not referenced in the body of the subprogram. This warning can
4978 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
4979 default is that these warnings are not generated.
4980
4981 @item -gnatwF
4982 @emph{Suppress warnings on unreferenced formals.}
4983 @cindex @option{-gnatwF} (@command{gcc})
4984 This switch suppresses warnings for unreferenced formal
4985 parameters. Note that the
4986 combination @option{-gnatwu} followed by @option{-gnatwF} has the
4987 effect of warning on unreferenced entities other than subprogram
4988 formals.
4989
4990 @item -gnatwg
4991 @emph{Activate warnings on unrecognized pragmas.}
4992 @cindex @option{-gnatwg} (@command{gcc})
4993 @cindex Pragmas, unrecognized
4994 This switch causes a warning to be generated if an unrecognized
4995 pragma is encountered. Apart from issuing this warning, the
4996 pragma is ignored and has no effect. This warning can
4997 also be turned on using @option{-gnatwa}. The default
4998 is that such warnings are issued (satisfying the Ada Reference
4999 Manual requirement that such warnings appear).
5000
5001 @item -gnatwG
5002 @emph{Suppress warnings on unrecognized pragmas.}
5003 @cindex @option{-gnatwG} (@command{gcc})
5004 This switch suppresses warnings for unrecognized pragmas.
5005
5006 @item -gnatwh
5007 @emph{Activate warnings on hiding.}
5008 @cindex @option{-gnatwh} (@command{gcc})
5009 @cindex Hiding of Declarations
5010 This switch activates warnings on hiding declarations.
5011 A declaration is considered hiding
5012 if it is for a non-overloadable entity, and it declares an entity with the
5013 same name as some other entity that is directly or use-visible. The default
5014 is that such warnings are not generated.
5015 Note that @option{-gnatwa} does not affect the setting of this warning option.
5016
5017 @item -gnatwH
5018 @emph{Suppress warnings on hiding.}
5019 @cindex @option{-gnatwH} (@command{gcc})
5020 This switch suppresses warnings on hiding declarations.
5021
5022 @item -gnatw.h
5023 @emph{Activate warnings on holes/gaps in records.}
5024 @cindex @option{-gnatw.h} (@command{gcc})
5025 @cindex Record Representation (gaps)
5026 This switch activates warnings on component clauses in record
5027 representation clauses that leave holes (gaps) in the record layout.
5028 If this warning option is active, then record representation clauses
5029 should specify a contiguous layout, adding unused fill fields if needed.
5030 Note that @option{-gnatwa} does not affect the setting of this warning option.
5031
5032 @item -gnatw.H
5033 @emph{Suppress warnings on holes/gaps in records.}
5034 @cindex @option{-gnatw.H} (@command{gcc})
5035 This switch suppresses warnings on component clauses in record
5036 representation clauses that leave holes (haps) in the record layout.
5037
5038 @item -gnatwi
5039 @emph{Activate warnings on implementation units.}
5040 @cindex @option{-gnatwi} (@command{gcc})
5041 This switch activates warnings for a @code{with} of an internal GNAT
5042 implementation unit, defined as any unit from the @code{Ada},
5043 @code{Interfaces}, @code{GNAT},
5044 ^^@code{DEC},^ or @code{System}
5045 hierarchies that is not
5046 documented in either the Ada Reference Manual or the GNAT
5047 Programmer's Reference Manual. Such units are intended only
5048 for internal implementation purposes and should not be @code{with}'ed
5049 by user programs. The default is that such warnings are generated
5050 This warning can also be turned on using @option{-gnatwa}.
5051
5052 @item -gnatwI
5053 @emph{Disable warnings on implementation units.}
5054 @cindex @option{-gnatwI} (@command{gcc})
5055 This switch disables warnings for a @code{with} of an internal GNAT
5056 implementation unit.
5057
5058 @item -gnatw.i
5059 @emph{Activate warnings on overlapping actuals.}
5060 @cindex @option{-gnatw.i} (@command{gcc})
5061 This switch enables a warning on statically detectable overlapping actuals in
5062 a subprogram call, when one of the actuals is an in-out parameter, and the
5063 types of the actuals are not by-copy types. The warning is off by default,
5064 and is not included under -gnatwa.
5065
5066 @item -gnatw.I
5067 @emph{Disable warnings on overlapping actuals.}
5068 @cindex @option{-gnatw.I} (@command{gcc})
5069 This switch disables warnings on overlapping actuals in a call..
5070
5071 @item -gnatwj
5072 @emph{Activate warnings on obsolescent features (Annex J).}
5073 @cindex @option{-gnatwj} (@command{gcc})
5074 @cindex Features, obsolescent
5075 @cindex Obsolescent features
5076 If this warning option is activated, then warnings are generated for
5077 calls to subprograms marked with @code{pragma Obsolescent} and
5078 for use of features in Annex J of the Ada Reference Manual. In the
5079 case of Annex J, not all features are flagged. In particular use
5080 of the renamed packages (like @code{Text_IO}) and use of package
5081 @code{ASCII} are not flagged, since these are very common and
5082 would generate many annoying positive warnings. The default is that
5083 such warnings are not generated. This warning is also turned on by
5084 the use of @option{-gnatwa}.
5085
5086 In addition to the above cases, warnings are also generated for
5087 GNAT features that have been provided in past versions but which
5088 have been superseded (typically by features in the new Ada standard).
5089 For example, @code{pragma Ravenscar} will be flagged since its
5090 function is replaced by @code{pragma Profile(Ravenscar)}, and
5091 @code{pragma Interface_Name} will be flagged since its function
5092 is replaced by @code{pragma Import}.
5093
5094 Note that this warning option functions differently from the
5095 restriction @code{No_Obsolescent_Features} in two respects.
5096 First, the restriction applies only to annex J features.
5097 Second, the restriction does flag uses of package @code{ASCII}.
5098
5099 @item -gnatwJ
5100 @emph{Suppress warnings on obsolescent features (Annex J).}
5101 @cindex @option{-gnatwJ} (@command{gcc})
5102 This switch disables warnings on use of obsolescent features.
5103
5104 @item -gnatwk
5105 @emph{Activate warnings on variables that could be constants.}
5106 @cindex @option{-gnatwk} (@command{gcc})
5107 This switch activates warnings for variables that are initialized but
5108 never modified, and then could be declared constants. The default is that
5109 such warnings are not given.
5110 This warning can also be turned on using @option{-gnatwa}.
5111
5112 @item -gnatwK
5113 @emph{Suppress warnings on variables that could be constants.}
5114 @cindex @option{-gnatwK} (@command{gcc})
5115 This switch disables warnings on variables that could be declared constants.
5116
5117 @item -gnatw.k
5118 @emph{Activate warnings on redefinition of names in standard.}
5119 @cindex @option{-gnatw.k} (@command{gcc})
5120 This switch activates warnings for declarations that declare a name that
5121 is defined in package Standard. Such declarations can be confusing,
5122 especially since the names in package Standard continue to be directly
5123 visible, meaning that use visibiliy on such redeclared names does not
5124 work as expected. Names of discriminants and components in records are
5125 not included in this check.
5126 This warning is not part of the warnings activated by @option{-gnatwa}.
5127 It must be explicitly activated.
5128
5129 @item -gnatw.K
5130 @emph{Suppress warnings on variables that could be constants.}
5131 @cindex @option{-gnatwK} (@command{gcc})
5132 This switch activates warnings for declarations that declare a name that
5133 is defined in package Standard.
5134
5135 @item -gnatwl
5136 @emph{Activate warnings for elaboration pragmas.}
5137 @cindex @option{-gnatwl} (@command{gcc})
5138 @cindex Elaboration, warnings
5139 This switch activates warnings on missing
5140 @code{Elaborate_All} and @code{Elaborate} pragmas.
5141 See the section in this guide on elaboration checking for details on
5142 when such pragmas should be used. In dynamic elaboration mode, this switch
5143 generations warnings about the need to add elaboration pragmas. Note however,
5144 that if you blindly follow these warnings, and add @code{Elaborate_All}
5145 warnings wherever they are recommended, you basically end up with the
5146 equivalent of the static elaboration model, which may not be what you want for
5147 legacy code for which the static model does not work.
5148
5149 For the static model, the messages generated are labeled "info:" (for
5150 information messages). They are not warnings to add elaboration pragmas,
5151 merely informational messages showing what implicit elaboration pragmas
5152 have been added, for use in analyzing elaboration circularity problems.
5153
5154 Warnings are also generated if you
5155 are using the static mode of elaboration, and a @code{pragma Elaborate}
5156 is encountered. The default is that such warnings
5157 are not generated.
5158 This warning is not automatically turned on by the use of @option{-gnatwa}.
5159
5160 @item -gnatwL
5161 @emph{Suppress warnings for elaboration pragmas.}
5162 @cindex @option{-gnatwL} (@command{gcc})
5163 This switch suppresses warnings on missing Elaborate and Elaborate_All pragmas.
5164 See the section in this guide on elaboration checking for details on
5165 when such pragmas should be used.
5166
5167 @item -gnatw.l
5168 @emph{List inherited aspects.}
5169 @cindex @option{-gnatw.l} (@command{gcc})
5170 This switch causes the compiler to list inherited invariants,
5171 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
5172 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
5173 These messages are not automatically turned on by the use of @option{-gnatwa}.
5174
5175 @item -gnatw.L
5176 @emph{Suppress listing of inherited aspects.}
5177 @cindex @option{-gnatw.L} (@command{gcc})
5178 This switch suppresses listing of inherited aspects.
5179
5180 @item -gnatwm
5181 @emph{Activate warnings on modified but unreferenced variables.}
5182 @cindex @option{-gnatwm} (@command{gcc})
5183 This switch activates warnings for variables that are assigned (using
5184 an initialization value or with one or more assignment statements) but
5185 whose value is never read. The warning is suppressed for volatile
5186 variables and also for variables that are renamings of other variables
5187 or for which an address clause is given.
5188 This warning can also be turned on using @option{-gnatwa}.
5189 The default is that these warnings are not given.
5190
5191 @item -gnatwM
5192 @emph{Disable warnings on modified but unreferenced variables.}
5193 @cindex @option{-gnatwM} (@command{gcc})
5194 This switch disables warnings for variables that are assigned or
5195 initialized, but never read.
5196
5197 @item -gnatw.m
5198 @emph{Activate warnings on suspicious modulus values.}
5199 @cindex @option{-gnatw.m} (@command{gcc})
5200 This switch activates warnings for modulus values that seem suspicious.
5201 The cases caught are where the size is the same as the modulus (e.g.
5202 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5203 with no size clause. The guess in both cases is that 2**x was intended
5204 rather than x. In addition expressions of the form 2*x for small x
5205 generate a warning (the almost certainly accurate guess being that
5206 2**x was intended). The default is that these warnings are given.
5207
5208 @item -gnatw.M
5209 @emph{Disable warnings on suspicious modulus values.}
5210 @cindex @option{-gnatw.M} (@command{gcc})
5211 This switch disables warnings for suspicious modulus values.
5212
5213 @item -gnatwn
5214 @emph{Set normal warnings mode.}
5215 @cindex @option{-gnatwn} (@command{gcc})
5216 This switch sets normal warning mode, in which enabled warnings are
5217 issued and treated as warnings rather than errors. This is the default
5218 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5219 an explicit @option{-gnatws} or
5220 @option{-gnatwe}. It also cancels the effect of the
5221 implicit @option{-gnatwe} that is activated by the
5222 use of @option{-gnatg}.
5223
5224 @item -gnatwo
5225 @emph{Activate warnings on address clause overlays.}
5226 @cindex @option{-gnatwo} (@command{gcc})
5227 @cindex Address Clauses, warnings
5228 This switch activates warnings for possibly unintended initialization
5229 effects of defining address clauses that cause one variable to overlap
5230 another. The default is that such warnings are generated.
5231 This warning can also be turned on using @option{-gnatwa}.
5232
5233 @item -gnatwO
5234 @emph{Suppress warnings on address clause overlays.}
5235 @cindex @option{-gnatwO} (@command{gcc})
5236 This switch suppresses warnings on possibly unintended initialization
5237 effects of defining address clauses that cause one variable to overlap
5238 another.
5239
5240 @item -gnatw.o
5241 @emph{Activate warnings on modified but unreferenced out parameters.}
5242 @cindex @option{-gnatw.o} (@command{gcc})
5243 This switch activates warnings for variables that are modified by using
5244 them as actuals for a call to a procedure with an out mode formal, where
5245 the resulting assigned value is never read. It is applicable in the case
5246 where there is more than one out mode formal. If there is only one out
5247 mode formal, the warning is issued by default (controlled by -gnatwu).
5248 The warning is suppressed for volatile
5249 variables and also for variables that are renamings of other variables
5250 or for which an address clause is given.
5251 The default is that these warnings are not given. Note that this warning
5252 is not included in -gnatwa, it must be activated explicitly.
5253
5254 @item -gnatw.O
5255 @emph{Disable warnings on modified but unreferenced out parameters.}
5256 @cindex @option{-gnatw.O} (@command{gcc})
5257 This switch suppresses warnings for variables that are modified by using
5258 them as actuals for a call to a procedure with an out mode formal, where
5259 the resulting assigned value is never read.
5260
5261 @item -gnatwp
5262 @emph{Activate warnings on ineffective pragma Inlines.}
5263 @cindex @option{-gnatwp} (@command{gcc})
5264 @cindex Inlining, warnings
5265 This switch activates warnings for failure of front end inlining
5266 (activated by @option{-gnatN}) to inline a particular call. There are
5267 many reasons for not being able to inline a call, including most
5268 commonly that the call is too complex to inline. The default is
5269 that such warnings are not given.
5270 This warning can also be turned on using @option{-gnatwa}.
5271 Warnings on ineffective inlining by the gcc back-end can be activated
5272 separately, using the gcc switch -Winline.
5273
5274 @item -gnatwP
5275 @emph{Suppress warnings on ineffective pragma Inlines.}
5276 @cindex @option{-gnatwP} (@command{gcc})
5277 This switch suppresses warnings on ineffective pragma Inlines. If the
5278 inlining mechanism cannot inline a call, it will simply ignore the
5279 request silently.
5280
5281 @item -gnatw.p
5282 @emph{Activate warnings on parameter ordering.}
5283 @cindex @option{-gnatw.p} (@command{gcc})
5284 @cindex Parameter order, warnings
5285 This switch activates warnings for cases of suspicious parameter
5286 ordering when the list of arguments are all simple identifiers that
5287 match the names of the formals, but are in a different order. The
5288 warning is suppressed if any use of named parameter notation is used,
5289 so this is the appropriate way to suppress a false positive (and
5290 serves to emphasize that the "misordering" is deliberate). The
5291 default is
5292 that such warnings are not given.
5293 This warning can also be turned on using @option{-gnatwa}.
5294
5295 @item -gnatw.P
5296 @emph{Suppress warnings on parameter ordering.}
5297 @cindex @option{-gnatw.P} (@command{gcc})
5298 This switch suppresses warnings on cases of suspicious parameter
5299 ordering.
5300
5301 @item -gnatwq
5302 @emph{Activate warnings on questionable missing parentheses.}
5303 @cindex @option{-gnatwq} (@command{gcc})
5304 @cindex Parentheses, warnings
5305 This switch activates warnings for cases where parentheses are not used and
5306 the result is potential ambiguity from a readers point of view. For example
5307 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5308 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5309 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5310 follow the rule of always parenthesizing to make the association clear, and
5311 this warning switch warns if such parentheses are not present. The default
5312 is that these warnings are given.
5313 This warning can also be turned on using @option{-gnatwa}.
5314
5315 @item -gnatwQ
5316 @emph{Suppress warnings on questionable missing parentheses.}
5317 @cindex @option{-gnatwQ} (@command{gcc})
5318 This switch suppresses warnings for cases where the association is not
5319 clear and the use of parentheses is preferred.
5320
5321 @item -gnatwr
5322 @emph{Activate warnings on redundant constructs.}
5323 @cindex @option{-gnatwr} (@command{gcc})
5324 This switch activates warnings for redundant constructs. The following
5325 is the current list of constructs regarded as redundant:
5326
5327 @itemize @bullet
5328 @item
5329 Assignment of an item to itself.
5330 @item
5331 Type conversion that converts an expression to its own type.
5332 @item
5333 Use of the attribute @code{Base} where @code{typ'Base} is the same
5334 as @code{typ}.
5335 @item
5336 Use of pragma @code{Pack} when all components are placed by a record
5337 representation clause.
5338 @item
5339 Exception handler containing only a reraise statement (raise with no
5340 operand) which has no effect.
5341 @item
5342 Use of the operator abs on an operand that is known at compile time
5343 to be non-negative
5344 @item
5345 Comparison of boolean expressions to an explicit True value.
5346 @end itemize
5347
5348 This warning can also be turned on using @option{-gnatwa}.
5349 The default is that warnings for redundant constructs are not given.
5350
5351 @item -gnatwR
5352 @emph{Suppress warnings on redundant constructs.}
5353 @cindex @option{-gnatwR} (@command{gcc})
5354 This switch suppresses warnings for redundant constructs.
5355
5356 @item -gnatw.r
5357 @emph{Activate warnings for object renaming function.}
5358 @cindex @option{-gnatw.r} (@command{gcc})
5359 This switch activates warnings for an object renaming that renames a
5360 function call, which is equivalent to a constant declaration (as
5361 opposed to renaming the function itself). The default is that these
5362 warnings are given. This warning can also be turned on using
5363 @option{-gnatwa}.
5364
5365 @item -gnatw.R
5366 @emph{Suppress warnings for object renaming function.}
5367 @cindex @option{-gnatwT} (@command{gcc})
5368 This switch suppresses warnings for object renaming function.
5369
5370 @item -gnatws
5371 @emph{Suppress all warnings.}
5372 @cindex @option{-gnatws} (@command{gcc})
5373 This switch completely suppresses the
5374 output of all warning messages from the GNAT front end, including
5375 both warnings that can be controlled by switches described in this
5376 section, and those that are normally given unconditionally. The
5377 effect of this suppress action can only be cancelled by a subsequent
5378 use of the switch @option{-gnatwn}.
5379
5380 Note that switch @option{-gnatws} does not suppress
5381 warnings from the @command{gcc} back end.
5382 To suppress these back end warnings as well, use the switch @option{-w}
5383 in addition to @option{-gnatws}. Also this switch has no effect on the
5384 handling of style check messages.
5385
5386 @item -gnatw.s
5387 @emph{Activate warnings on overridden size clauses.}
5388 @cindex @option{-gnatw.s} (@command{gcc})
5389 @cindex Record Representation (component sizes)
5390 This switch activates warnings on component clauses in record
5391 representation clauses where the length given overrides that
5392 specified by an explicit size clause for the component type. A
5393 warning is similarly given in the array case if a specified
5394 component size overrides an explicit size clause for the array
5395 component type.
5396 Note that @option{-gnatwa} does not affect the setting of this warning option.
5397
5398 @item -gnatw.S
5399 @emph{Suppress warnings on overridden size clauses.}
5400 @cindex @option{-gnatw.S} (@command{gcc})
5401 This switch suppresses warnings on component clauses in record
5402 representation clauses that override size clauses, and similar
5403 warnings when an array component size overrides a size clause.
5404
5405 @item -gnatwt
5406 @emph{Activate warnings for tracking of deleted conditional code.}
5407 @cindex @option{-gnatwt} (@command{gcc})
5408 @cindex Deactivated code, warnings
5409 @cindex Deleted code, warnings
5410 This switch activates warnings for tracking of code in conditionals (IF and
5411 CASE statements) that is detected to be dead code which cannot be executed, and
5412 which is removed by the front end. This warning is off by default, and is not
5413 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5414 useful for detecting deactivated code in certified applications.
5415
5416 @item -gnatwT
5417 @emph{Suppress warnings for tracking of deleted conditional code.}
5418 @cindex @option{-gnatwT} (@command{gcc})
5419 This switch suppresses warnings for tracking of deleted conditional code.
5420
5421 @item -gnatw.t
5422 @emph{Activate warnings on suspicious contracts.}
5423 @cindex @option{-gnatw.t} (@command{gcc})
5424 This switch activates warnings on suspicious postconditions (whether a
5425 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012)
5426 and suspicious contract cases (pragma @code{Contract_Cases}). A
5427 function postcondition or contract case is suspicious when no postcondition
5428 or contract case for this function mentions the result of the function.
5429 A procedure postcondition or contract case is suspicious when it only
5430 refers to the pre-state of the procedure, because in that case it should
5431 rather be expressed as a precondition. The default is that such warnings
5432 are not generated. This warning can also be turned on using @option{-gnatwa}.
5433
5434 @item -gnatw.T
5435 @emph{Suppress warnings on suspicious contracts.}
5436 @cindex @option{-gnatw.T} (@command{gcc})
5437 This switch suppresses warnings on suspicious postconditions.
5438
5439 @item -gnatwu
5440 @emph{Activate warnings on unused entities.}
5441 @cindex @option{-gnatwu} (@command{gcc})
5442 This switch activates warnings to be generated for entities that
5443 are declared but not referenced, and for units that are @code{with}'ed
5444 and not
5445 referenced. In the case of packages, a warning is also generated if
5446 no entities in the package are referenced. This means that if a with'ed
5447 package is referenced but the only references are in @code{use}
5448 clauses or @code{renames}
5449 declarations, a warning is still generated. A warning is also generated
5450 for a generic package that is @code{with}'ed but never instantiated.
5451 In the case where a package or subprogram body is compiled, and there
5452 is a @code{with} on the corresponding spec
5453 that is only referenced in the body,
5454 a warning is also generated, noting that the
5455 @code{with} can be moved to the body. The default is that
5456 such warnings are not generated.
5457 This switch also activates warnings on unreferenced formals
5458 (it includes the effect of @option{-gnatwf}).
5459 This warning can also be turned on using @option{-gnatwa}.
5460
5461 @item -gnatwU
5462 @emph{Suppress warnings on unused entities.}
5463 @cindex @option{-gnatwU} (@command{gcc})
5464 This switch suppresses warnings for unused entities and packages.
5465 It also turns off warnings on unreferenced formals (and thus includes
5466 the effect of @option{-gnatwF}).
5467
5468 @item -gnatw.u
5469 @emph{Activate warnings on unordered enumeration types.}
5470 @cindex @option{-gnatw.u} (@command{gcc})
5471 This switch causes enumeration types to be considered as conceptually
5472 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5473 The effect is to generate warnings in clients that use explicit comparisons
5474 or subranges, since these constructs both treat objects of the type as
5475 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5476 which the type is declared, or its body or subunits.) Please refer to
5477 the description of pragma @code{Ordered} in the
5478 @cite{@value{EDITION} Reference Manual} for further details.
5479 The default is that such warnings are not generated.
5480 This warning is not automatically turned on by the use of @option{-gnatwa}.
5481
5482 @item -gnatw.U
5483 @emph{Deactivate warnings on unordered enumeration types.}
5484 @cindex @option{-gnatw.U} (@command{gcc})
5485 This switch causes all enumeration types to be considered as ordered, so
5486 that no warnings are given for comparisons or subranges for any type.
5487
5488 @item -gnatwv
5489 @emph{Activate warnings on unassigned variables.}
5490 @cindex @option{-gnatwv} (@command{gcc})
5491 @cindex Unassigned variable warnings
5492 This switch activates warnings for access to variables which
5493 may not be properly initialized. The default is that
5494 such warnings are generated.
5495 This warning can also be turned on using @option{-gnatwa}.
5496
5497 @item -gnatwV
5498 @emph{Suppress warnings on unassigned variables.}
5499 @cindex @option{-gnatwV} (@command{gcc})
5500 This switch suppresses warnings for access to variables which
5501 may not be properly initialized.
5502 For variables of a composite type, the warning can also be suppressed in
5503 Ada 2005 by using a default initialization with a box. For example, if
5504 Table is an array of records whose components are only partially uninitialized,
5505 then the following code:
5506
5507 @smallexample @c ada
5508 Tab : Table := (others => <>);
5509 @end smallexample
5510
5511 will suppress warnings on subsequent statements that access components
5512 of variable Tab.
5513
5514 @item -gnatw.v
5515 @emph{Activate info messages for non-default bit order.}
5516 @cindex @option{-gnatw.v} (@command{gcc})
5517 @cindex bit order warnings
5518 This switch activates messages (labeled "info", they are not warnings,
5519 just informational messages) about the effects of non-default bit-order
5520 on records to which a component clause is applied. The effect of specifying
5521 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
5522 these messages, which are given by default, are useful in understanding the
5523 exact consequences of using this feature. These messages
5524 can also be turned on using @option{-gnatwa}
5525
5526 @item -gnatw.V
5527 @emph{Suppress info messages for non-default bit order.}
5528 @cindex @option{-gnatw.V} (@command{gcc})
5529 This switch suppresses information messages for the effects of specifying
5530 non-default bit order on record components with component clauses.
5531
5532 @item -gnatww
5533 @emph{Activate warnings on wrong low bound assumption.}
5534 @cindex @option{-gnatww} (@command{gcc})
5535 @cindex String indexing warnings
5536 This switch activates warnings for indexing an unconstrained string parameter
5537 with a literal or S'Length. This is a case where the code is assuming that the
5538 low bound is one, which is in general not true (for example when a slice is
5539 passed). The default is that such warnings are generated.
5540 This warning can also be turned on using @option{-gnatwa}.
5541
5542 @item -gnatwW
5543 @emph{Suppress warnings on wrong low bound assumption.}
5544 @cindex @option{-gnatwW} (@command{gcc})
5545 This switch suppresses warnings for indexing an unconstrained string parameter
5546 with a literal or S'Length. Note that this warning can also be suppressed
5547 in a particular case by adding an
5548 assertion that the lower bound is 1,
5549 as shown in the following example.
5550
5551 @smallexample @c ada
5552 procedure K (S : String) is
5553 pragma Assert (S'First = 1);
5554 @dots{}
5555 @end smallexample
5556
5557 @item -gnatw.w
5558 @emph{Activate warnings on unnecessary Warnings Off pragmas}
5559 @cindex @option{-gnatw.w} (@command{gcc})
5560 @cindex Warnings Off control
5561 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5562 where either the pragma is entirely useless (because it suppresses no
5563 warnings), or it could be replaced by @code{pragma Unreferenced} or
5564 @code{pragma Unmodified}. The default is that these warnings are not given.
5565 Note that this warning is not included in -gnatwa, it must be
5566 activated explicitly.
5567
5568 @item -gnatw.W
5569 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5570 @cindex @option{-gnatw.W} (@command{gcc})
5571 This switch suppresses warnings for use of @code{pragma Warnings (Off, entity)}.
5572
5573 @item -gnatwx
5574 @emph{Activate warnings on Export/Import pragmas.}
5575 @cindex @option{-gnatwx} (@command{gcc})
5576 @cindex Export/Import pragma warnings
5577 This switch activates warnings on Export/Import pragmas when
5578 the compiler detects a possible conflict between the Ada and
5579 foreign language calling sequences. For example, the use of
5580 default parameters in a convention C procedure is dubious
5581 because the C compiler cannot supply the proper default, so
5582 a warning is issued. The default is that such warnings are
5583 generated.
5584 This warning can also be turned on using @option{-gnatwa}.
5585
5586 @item -gnatwX
5587 @emph{Suppress warnings on Export/Import pragmas.}
5588 @cindex @option{-gnatwX} (@command{gcc})
5589 This switch suppresses warnings on Export/Import pragmas.
5590 The sense of this is that you are telling the compiler that
5591 you know what you are doing in writing the pragma, and it
5592 should not complain at you.
5593
5594 @item -gnatw.x
5595 @emph{Activate warnings for No_Exception_Propagation mode.}
5596 @cindex @option{-gnatwm} (@command{gcc})
5597 This switch activates warnings for exception usage when pragma Restrictions
5598 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5599 explicit exception raises which are not covered by a local handler, and for
5600 exception handlers which do not cover a local raise. The default is that these
5601 warnings are not given.
5602
5603 @item -gnatw.X
5604 @emph{Disable warnings for No_Exception_Propagation mode.}
5605 This switch disables warnings for exception usage when pragma Restrictions
5606 (No_Exception_Propagation) is in effect.
5607
5608 @item -gnatwy
5609 @emph{Activate warnings for Ada compatibility issues.}
5610 @cindex @option{-gnatwy} (@command{gcc})
5611 @cindex Ada compatibility issues warnings
5612 For the most part, newer versions of Ada are upwards compatible
5613 with older versions. For example, Ada 2005 programs will almost
5614 always work when compiled as Ada 2012.
5615 However there are some exceptions (for example the fact that
5616 @code{some} is now a reserved word in Ada 2012). This
5617 switch activates several warnings to help in identifying
5618 and correcting such incompatibilities. The default is that
5619 these warnings are generated. Note that at one point Ada 2005
5620 was called Ada 0Y, hence the choice of character.
5621 This warning can also be turned on using @option{-gnatwa}.
5622
5623 @item -gnatwY
5624 @emph{Disable warnings for Ada compatibility issues.}
5625 @cindex @option{-gnatwY} (@command{gcc})
5626 @cindex Ada compatibility issues warnings
5627 This switch suppresses the warnings intended to help in identifying
5628 incompatibilities between Ada language versions.
5629
5630 @item -gnatwz
5631 @emph{Activate warnings on unchecked conversions.}
5632 @cindex @option{-gnatwz} (@command{gcc})
5633 @cindex Unchecked_Conversion warnings
5634 This switch activates warnings for unchecked conversions
5635 where the types are known at compile time to have different
5636 sizes. The default
5637 is that such warnings are generated. Warnings are also
5638 generated for subprogram pointers with different conventions,
5639 and, on VMS only, for data pointers with different conventions.
5640 This warning can also be turned on using @option{-gnatwa}.
5641
5642 @item -gnatwZ
5643 @emph{Suppress warnings on unchecked conversions.}
5644 @cindex @option{-gnatwZ} (@command{gcc})
5645 This switch suppresses warnings for unchecked conversions
5646 where the types are known at compile time to have different
5647 sizes or conventions.
5648
5649 @item ^-Wunused^WARNINGS=UNUSED^
5650 @cindex @option{-Wunused}
5651 The warnings controlled by the @option{-gnatw} switch are generated by
5652 the front end of the compiler. The @option{GCC} back end can provide
5653 additional warnings and they are controlled by the @option{-W} switch.
5654 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5655 warnings for entities that are declared but not referenced.
5656
5657 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5658 @cindex @option{-Wuninitialized}
5659 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5660 the back end warning for uninitialized variables. This switch must be
5661 used in conjunction with an optimization level greater than zero.
5662
5663 @item -Wstack-usage=@var{len}
5664 @cindex @option{-Wstack-usage}
5665 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5666 See @ref{Static Stack Usage Analysis} for details.
5667
5668 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5669 @cindex @option{-Wall}
5670 This switch enables most warnings from the @option{GCC} back end.
5671 The code generator detects a number of warning situations that are missed
5672 by the @option{GNAT} front end, and this switch can be used to activate them.
5673 The use of this switch also sets the default front end warning mode to
5674 @option{-gnatwa}, that is, most front end warnings activated as well.
5675
5676 @item ^-w^/NO_BACK_END_WARNINGS^
5677 @cindex @option{-w}
5678 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5679 The use of this switch also sets the default front end warning mode to
5680 @option{-gnatws}, that is, front end warnings suppressed as well.
5681
5682 @end table
5683
5684 @noindent
5685 @ifclear vms
5686 A string of warning parameters can be used in the same parameter. For example:
5687
5688 @smallexample
5689 -gnatwaGe
5690 @end smallexample
5691
5692 @noindent
5693 will turn on all optional warnings except for unrecognized pragma warnings,
5694 and also specify that warnings should be treated as errors.
5695 @end ifclear
5696
5697 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5698
5699 @table @option
5700 @c !sort!
5701 @item -gnatw.a
5702 @item -gnatwB
5703 @item -gnatw.b
5704 @item -gnatwC
5705 @item -gnatw.C
5706 @item -gnatwD
5707 @item -gnatwF
5708 @item -gnatwg
5709 @item -gnatwH
5710 @item -gnatwi
5711 @item -gnatw.I
5712 @item -gnatwJ
5713 @item -gnatwK
5714 @item -gnatwL
5715 @item -gnatw.L
5716 @item -gnatwM
5717 @item -gnatw.m
5718 @item -gnatwn
5719 @item -gnatwo
5720 @item -gnatw.O
5721 @item -gnatwP
5722 @item -gnatw.P
5723 @item -gnatwq
5724 @item -gnatwR
5725 @item -gnatw.R
5726 @item -gnatw.S
5727 @item -gnatwT
5728 @item -gnatw.T
5729 @item -gnatwU
5730 @item -gnatwv
5731 @item -gnatww
5732 @item -gnatw.W
5733 @item -gnatwx
5734 @item -gnatw.X
5735 @item -gnatwy
5736 @item -gnatwz
5737
5738 @end table
5739
5740 @node Debugging and Assertion Control
5741 @subsection Debugging and Assertion Control
5742
5743 @table @option
5744 @item -gnata
5745 @cindex @option{-gnata} (@command{gcc})
5746 @findex Assert
5747 @findex Debug
5748 @cindex Assertions
5749
5750 @noindent
5751 The pragmas @code{Assert} and @code{Debug} normally have no effect and
5752 are ignored. This switch, where @samp{a} stands for assert, causes
5753 @code{Assert} and @code{Debug} pragmas to be activated.
5754
5755 The pragmas have the form:
5756
5757 @smallexample
5758 @cartouche
5759 @b{pragma} Assert (@var{Boolean-expression} @r{[},
5760 @var{static-string-expression}@r{]})
5761 @b{pragma} Debug (@var{procedure call})
5762 @end cartouche
5763 @end smallexample
5764
5765 @noindent
5766 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
5767 If the result is @code{True}, the pragma has no effect (other than
5768 possible side effects from evaluating the expression). If the result is
5769 @code{False}, the exception @code{Assert_Failure} declared in the package
5770 @code{System.Assertions} is
5771 raised (passing @var{static-string-expression}, if present, as the
5772 message associated with the exception). If no string expression is
5773 given the default is a string giving the file name and line number
5774 of the pragma.
5775
5776 The @code{Debug} pragma causes @var{procedure} to be called. Note that
5777 @code{pragma Debug} may appear within a declaration sequence, allowing
5778 debugging procedures to be called between declarations.
5779
5780 @ifset vms
5781 @item /DEBUG@r{[}=debug-level@r{]}
5782 @itemx /NODEBUG
5783 Specifies how much debugging information is to be included in
5784 the resulting object file where 'debug-level' is one of the following:
5785 @table @code
5786 @item TRACEBACK
5787 Include both debugger symbol records and traceback
5788 the object file.
5789 This is the default setting.
5790 @item ALL
5791 Include both debugger symbol records and traceback in
5792 object file.
5793 @item NONE
5794 Excludes both debugger symbol records and traceback
5795 the object file. Same as /NODEBUG.
5796 @item SYMBOLS
5797 Includes only debugger symbol records in the object
5798 file. Note that this doesn't include traceback information.
5799 @end table
5800 @end ifset
5801 @end table
5802
5803 @node Validity Checking
5804 @subsection Validity Checking
5805 @findex Validity Checking
5806
5807 @noindent
5808 The Ada Reference Manual defines the concept of invalid values (see
5809 RM 13.9.1). The primary source of invalid values is uninitialized
5810 variables. A scalar variable that is left uninitialized may contain
5811 an invalid value; the concept of invalid does not apply to access or
5812 composite types.
5813
5814 It is an error to read an invalid value, but the RM does not require
5815 run-time checks to detect such errors, except for some minimal
5816 checking to prevent erroneous execution (i.e. unpredictable
5817 behavior). This corresponds to the @option{-gnatVd} switch below,
5818 which is the default. For example, by default, if the expression of a
5819 case statement is invalid, it will raise Constraint_Error rather than
5820 causing a wild jump, and if an array index on the left-hand side of an
5821 assignment is invalid, it will raise Constraint_Error rather than
5822 overwriting an arbitrary memory location.
5823
5824 The @option{-gnatVa} may be used to enable additional validity checks,
5825 which are not required by the RM. These checks are often very
5826 expensive (which is why the RM does not require them). These checks
5827 are useful in tracking down uninitialized variables, but they are
5828 not usually recommended for production builds.
5829
5830 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
5831 control; you can enable whichever validity checks you desire. However,
5832 for most debugging purposes, @option{-gnatVa} is sufficient, and the
5833 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
5834 sufficient for non-debugging use.
5835
5836 The @option{-gnatB} switch tells the compiler to assume that all
5837 values are valid (that is, within their declared subtype range)
5838 except in the context of a use of the Valid attribute. This means
5839 the compiler can generate more efficient code, since the range
5840 of values is better known at compile time. However, an uninitialized
5841 variable can cause wild jumps and memory corruption in this mode.
5842
5843 The @option{-gnatV^@var{x}^^} switch allows control over the validity
5844 checking mode as described below.
5845 @ifclear vms
5846 The @code{x} argument is a string of letters that
5847 indicate validity checks that are performed or not performed in addition
5848 to the default checks required by Ada as described above.
5849 @end ifclear
5850 @ifset vms
5851 The options allowed for this qualifier
5852 indicate validity checks that are performed or not performed in addition
5853 to the default checks required by Ada as described above.
5854 @end ifset
5855
5856 @table @option
5857 @c !sort!
5858 @item -gnatVa
5859 @emph{All validity checks.}
5860 @cindex @option{-gnatVa} (@command{gcc})
5861 All validity checks are turned on.
5862 @ifclear vms
5863 That is, @option{-gnatVa} is
5864 equivalent to @option{gnatVcdfimorst}.
5865 @end ifclear
5866
5867 @item -gnatVc
5868 @emph{Validity checks for copies.}
5869 @cindex @option{-gnatVc} (@command{gcc})
5870 The right hand side of assignments, and the initializing values of
5871 object declarations are validity checked.
5872
5873 @item -gnatVd
5874 @emph{Default (RM) validity checks.}
5875 @cindex @option{-gnatVd} (@command{gcc})
5876 Some validity checks are done by default following normal Ada semantics
5877 (RM 13.9.1 (9-11)).
5878 A check is done in case statements that the expression is within the range
5879 of the subtype. If it is not, Constraint_Error is raised.
5880 For assignments to array components, a check is done that the expression used
5881 as index is within the range. If it is not, Constraint_Error is raised.
5882 Both these validity checks may be turned off using switch @option{-gnatVD}.
5883 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
5884 switch @option{-gnatVd} will leave the checks turned on.
5885 Switch @option{-gnatVD} should be used only if you are sure that all such
5886 expressions have valid values. If you use this switch and invalid values
5887 are present, then the program is erroneous, and wild jumps or memory
5888 overwriting may occur.
5889
5890 @item -gnatVe
5891 @emph{Validity checks for elementary components.}
5892 @cindex @option{-gnatVe} (@command{gcc})
5893 In the absence of this switch, assignments to record or array components are
5894 not validity checked, even if validity checks for assignments generally
5895 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
5896 require valid data, but assignment of individual components does. So for
5897 example, there is a difference between copying the elements of an array with a
5898 slice assignment, compared to assigning element by element in a loop. This
5899 switch allows you to turn off validity checking for components, even when they
5900 are assigned component by component.
5901
5902 @item -gnatVf
5903 @emph{Validity checks for floating-point values.}
5904 @cindex @option{-gnatVf} (@command{gcc})
5905 In the absence of this switch, validity checking occurs only for discrete
5906 values. If @option{-gnatVf} is specified, then validity checking also applies
5907 for floating-point values, and NaNs and infinities are considered invalid,
5908 as well as out of range values for constrained types. Note that this means
5909 that standard IEEE infinity mode is not allowed. The exact contexts
5910 in which floating-point values are checked depends on the setting of other
5911 options. For example,
5912 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
5913 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
5914 (the order does not matter) specifies that floating-point parameters of mode
5915 @code{in} should be validity checked.
5916
5917 @item -gnatVi
5918 @emph{Validity checks for @code{in} mode parameters}
5919 @cindex @option{-gnatVi} (@command{gcc})
5920 Arguments for parameters of mode @code{in} are validity checked in function
5921 and procedure calls at the point of call.
5922
5923 @item -gnatVm
5924 @emph{Validity checks for @code{in out} mode parameters.}
5925 @cindex @option{-gnatVm} (@command{gcc})
5926 Arguments for parameters of mode @code{in out} are validity checked in
5927 procedure calls at the point of call. The @code{'m'} here stands for
5928 modify, since this concerns parameters that can be modified by the call.
5929 Note that there is no specific option to test @code{out} parameters,
5930 but any reference within the subprogram will be tested in the usual
5931 manner, and if an invalid value is copied back, any reference to it
5932 will be subject to validity checking.
5933
5934 @item -gnatVn
5935 @emph{No validity checks.}
5936 @cindex @option{-gnatVn} (@command{gcc})
5937 This switch turns off all validity checking, including the default checking
5938 for case statements and left hand side subscripts. Note that the use of
5939 the switch @option{-gnatp} suppresses all run-time checks, including
5940 validity checks, and thus implies @option{-gnatVn}. When this switch
5941 is used, it cancels any other @option{-gnatV} previously issued.
5942
5943 @item -gnatVo
5944 @emph{Validity checks for operator and attribute operands.}
5945 @cindex @option{-gnatVo} (@command{gcc})
5946 Arguments for predefined operators and attributes are validity checked.
5947 This includes all operators in package @code{Standard},
5948 the shift operators defined as intrinsic in package @code{Interfaces}
5949 and operands for attributes such as @code{Pos}. Checks are also made
5950 on individual component values for composite comparisons, and on the
5951 expressions in type conversions and qualified expressions. Checks are
5952 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
5953
5954 @item -gnatVp
5955 @emph{Validity checks for parameters.}
5956 @cindex @option{-gnatVp} (@command{gcc})
5957 This controls the treatment of parameters within a subprogram (as opposed
5958 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
5959 of parameters on a call. If either of these call options is used, then
5960 normally an assumption is made within a subprogram that the input arguments
5961 have been validity checking at the point of call, and do not need checking
5962 again within a subprogram). If @option{-gnatVp} is set, then this assumption
5963 is not made, and parameters are not assumed to be valid, so their validity
5964 will be checked (or rechecked) within the subprogram.
5965
5966 @item -gnatVr
5967 @emph{Validity checks for function returns.}
5968 @cindex @option{-gnatVr} (@command{gcc})
5969 The expression in @code{return} statements in functions is validity
5970 checked.
5971
5972 @item -gnatVs
5973 @emph{Validity checks for subscripts.}
5974 @cindex @option{-gnatVs} (@command{gcc})
5975 All subscripts expressions are checked for validity, whether they appear
5976 on the right side or left side (in default mode only left side subscripts
5977 are validity checked).
5978
5979 @item -gnatVt
5980 @emph{Validity checks for tests.}
5981 @cindex @option{-gnatVt} (@command{gcc})
5982 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
5983 statements are checked, as well as guard expressions in entry calls.
5984
5985 @end table
5986
5987 @noindent
5988 The @option{-gnatV} switch may be followed by
5989 ^a string of letters^a list of options^
5990 to turn on a series of validity checking options.
5991 For example,
5992 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
5993 specifies that in addition to the default validity checking, copies and
5994 function return expressions are to be validity checked.
5995 In order to make it easier
5996 to specify the desired combination of effects,
5997 @ifclear vms
5998 the upper case letters @code{CDFIMORST} may
5999 be used to turn off the corresponding lower case option.
6000 @end ifclear
6001 @ifset vms
6002 the prefix @code{NO} on an option turns off the corresponding validity
6003 checking:
6004 @itemize @bullet
6005 @item @code{NOCOPIES}
6006 @item @code{NODEFAULT}
6007 @item @code{NOFLOATS}
6008 @item @code{NOIN_PARAMS}
6009 @item @code{NOMOD_PARAMS}
6010 @item @code{NOOPERANDS}
6011 @item @code{NORETURNS}
6012 @item @code{NOSUBSCRIPTS}
6013 @item @code{NOTESTS}
6014 @end itemize
6015 @end ifset
6016 Thus
6017 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6018 turns on all validity checking options except for
6019 checking of @code{@b{in out}} procedure arguments.
6020
6021 The specification of additional validity checking generates extra code (and
6022 in the case of @option{-gnatVa} the code expansion can be substantial).
6023 However, these additional checks can be very useful in detecting
6024 uninitialized variables, incorrect use of unchecked conversion, and other
6025 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6026 is useful in conjunction with the extra validity checking, since this
6027 ensures that wherever possible uninitialized variables have invalid values.
6028
6029 See also the pragma @code{Validity_Checks} which allows modification of
6030 the validity checking mode at the program source level, and also allows for
6031 temporary disabling of validity checks.
6032
6033 @node Style Checking
6034 @subsection Style Checking
6035 @findex Style checking
6036
6037 @noindent
6038 The @option{-gnaty^x^(option,option,@dots{})^} switch
6039 @cindex @option{-gnaty} (@command{gcc})
6040 causes the compiler to
6041 enforce specified style rules. A limited set of style rules has been used
6042 in writing the GNAT sources themselves. This switch allows user programs
6043 to activate all or some of these checks. If the source program fails a
6044 specified style check, an appropriate message is given, preceded by
6045 the character sequence ``(style)''. This message does not prevent
6046 successful compilation (unless the @option{-gnatwe} switch is used).
6047
6048 Note that this is by no means intended to be a general facility for
6049 checking arbitrary coding standards. It is simply an embedding of the
6050 style rules we have chosen for the GNAT sources. If you are starting
6051 a project which does not have established style standards, you may
6052 find it useful to adopt the entire set of GNAT coding standards, or
6053 some subset of them. If you already have an established set of coding
6054 standards, then it may be that selected style checking options do
6055 indeed correspond to choices you have made, but for general checking
6056 of an existing set of coding rules, you should look to the gnatcheck
6057 tool, which is designed for that purpose.
6058
6059 @ifset vms
6060 @code{(option,option,@dots{})} is a sequence of keywords
6061 @end ifset
6062 @ifclear vms
6063 The string @var{x} is a sequence of letters or digits
6064 @end ifclear
6065 indicating the particular style
6066 checks to be performed. The following checks are defined:
6067
6068 @table @option
6069 @c !sort!
6070 @item 0-9
6071 @emph{Specify indentation level.}
6072 If a digit from 1-9 appears
6073 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6074 then proper indentation is checked, with the digit indicating the
6075 indentation level required. A value of zero turns off this style check.
6076 The general style of required indentation is as specified by
6077 the examples in the Ada Reference Manual. Full line comments must be
6078 aligned with the @code{--} starting on a column that is a multiple of
6079 the alignment level, or they may be aligned the same way as the following
6080 non-blank line (this is useful when full line comments appear in the middle
6081 of a statement, or they may be aligned with the source line on the previous
6082 non-blank line.
6083
6084 @item ^a^ATTRIBUTE^
6085 @emph{Check attribute casing.}
6086 Attribute names, including the case of keywords such as @code{digits}
6087 used as attributes names, must be written in mixed case, that is, the
6088 initial letter and any letter following an underscore must be uppercase.
6089 All other letters must be lowercase.
6090
6091 @item ^A^ARRAY_INDEXES^
6092 @emph{Use of array index numbers in array attributes.}
6093 When using the array attributes First, Last, Range,
6094 or Length, the index number must be omitted for one-dimensional arrays
6095 and is required for multi-dimensional arrays.
6096
6097 @item ^b^BLANKS^
6098 @emph{Blanks not allowed at statement end.}
6099 Trailing blanks are not allowed at the end of statements. The purpose of this
6100 rule, together with h (no horizontal tabs), is to enforce a canonical format
6101 for the use of blanks to separate source tokens.
6102
6103 @item ^B^BOOLEAN_OPERATORS^
6104 @emph{Check Boolean operators.}
6105 The use of AND/OR operators is not permitted except in the cases of modular
6106 operands, array operands, and simple stand-alone boolean variables or
6107 boolean constants. In all other cases @code{and then}/@code{or else} are
6108 required.
6109
6110 @item ^c^COMMENTS^
6111 @emph{Check comments, double space.}
6112 Comments must meet the following set of rules:
6113
6114 @itemize @bullet
6115
6116 @item
6117 The ``@code{--}'' that starts the column must either start in column one,
6118 or else at least one blank must precede this sequence.
6119
6120 @item
6121 Comments that follow other tokens on a line must have at least one blank
6122 following the ``@code{--}'' at the start of the comment.
6123
6124 @item
6125 Full line comments must have at least two blanks following the
6126 ``@code{--}'' that starts the comment, with the following exceptions.
6127
6128 @item
6129 A line consisting only of the ``@code{--}'' characters, possibly preceded
6130 by blanks is permitted.
6131
6132 @item
6133 A comment starting with ``@code{--x}'' where @code{x} is a special character
6134 is permitted.
6135 This allows proper processing of the output generated by specialized tools
6136 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6137 annotation
6138 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6139 special character is defined as being in one of the ASCII ranges
6140 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6141 Note that this usage is not permitted
6142 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6143
6144 @item
6145 A line consisting entirely of minus signs, possibly preceded by blanks, is
6146 permitted. This allows the construction of box comments where lines of minus
6147 signs are used to form the top and bottom of the box.
6148
6149 @item
6150 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6151 least one blank follows the initial ``@code{--}''. Together with the preceding
6152 rule, this allows the construction of box comments, as shown in the following
6153 example:
6154 @smallexample
6155 ---------------------------
6156 -- This is a box comment --
6157 -- with two text lines. --
6158 ---------------------------
6159 @end smallexample
6160 @end itemize
6161
6162 @item ^C^COMMENTS1^
6163 @emph{Check comments, single space.}
6164 This is identical to @code{^c^COMMENTS^} except that only one space
6165 is required following the @code{--} of a comment instead of two.
6166
6167 @item ^d^DOS_LINE_ENDINGS^
6168 @emph{Check no DOS line terminators present.}
6169 All lines must be terminated by a single ASCII.LF
6170 character (in particular the DOS line terminator sequence CR/LF is not
6171 allowed).
6172
6173 @item ^e^END^
6174 @emph{Check end/exit labels.}
6175 Optional labels on @code{end} statements ending subprograms and on
6176 @code{exit} statements exiting named loops, are required to be present.
6177
6178 @item ^f^VTABS^
6179 @emph{No form feeds or vertical tabs.}
6180 Neither form feeds nor vertical tab characters are permitted
6181 in the source text.
6182
6183 @item ^g^GNAT^
6184 @emph{GNAT style mode.}
6185 The set of style check switches is set to match that used by the GNAT sources.
6186 This may be useful when developing code that is eventually intended to be
6187 incorporated into GNAT. For further details, see GNAT sources.
6188
6189 @item ^h^HTABS^
6190 @emph{No horizontal tabs.}
6191 Horizontal tab characters are not permitted in the source text.
6192 Together with the b (no blanks at end of line) check, this
6193 enforces a canonical form for the use of blanks to separate
6194 source tokens.
6195
6196 @item ^i^IF_THEN^
6197 @emph{Check if-then layout.}
6198 The keyword @code{then} must appear either on the same
6199 line as corresponding @code{if}, or on a line on its own, lined
6200 up under the @code{if} with at least one non-blank line in between
6201 containing all or part of the condition to be tested.
6202
6203 @item ^I^IN_MODE^
6204 @emph{check mode IN keywords.}
6205 Mode @code{in} (the default mode) is not
6206 allowed to be given explicitly. @code{in out} is fine,
6207 but not @code{in} on its own.
6208
6209 @item ^k^KEYWORD^
6210 @emph{Check keyword casing.}
6211 All keywords must be in lower case (with the exception of keywords
6212 such as @code{digits} used as attribute names to which this check
6213 does not apply).
6214
6215 @item ^l^LAYOUT^
6216 @emph{Check layout.}
6217 Layout of statement and declaration constructs must follow the
6218 recommendations in the Ada Reference Manual, as indicated by the
6219 form of the syntax rules. For example an @code{else} keyword must
6220 be lined up with the corresponding @code{if} keyword.
6221
6222 There are two respects in which the style rule enforced by this check
6223 option are more liberal than those in the Ada Reference Manual. First
6224 in the case of record declarations, it is permissible to put the
6225 @code{record} keyword on the same line as the @code{type} keyword, and
6226 then the @code{end} in @code{end record} must line up under @code{type}.
6227 This is also permitted when the type declaration is split on two lines.
6228 For example, any of the following three layouts is acceptable:
6229
6230 @smallexample @c ada
6231 @cartouche
6232 type q is record
6233 a : integer;
6234 b : integer;
6235 end record;
6236
6237 type q is
6238 record
6239 a : integer;
6240 b : integer;
6241 end record;
6242
6243 type q is
6244 record
6245 a : integer;
6246 b : integer;
6247 end record;
6248
6249 @end cartouche
6250 @end smallexample
6251
6252 @noindent
6253 Second, in the case of a block statement, a permitted alternative
6254 is to put the block label on the same line as the @code{declare} or
6255 @code{begin} keyword, and then line the @code{end} keyword up under
6256 the block label. For example both the following are permitted:
6257
6258 @smallexample @c ada
6259 @cartouche
6260 Block : declare
6261 A : Integer := 3;
6262 begin
6263 Proc (A, A);
6264 end Block;
6265
6266 Block :
6267 declare
6268 A : Integer := 3;
6269 begin
6270 Proc (A, A);
6271 end Block;
6272 @end cartouche
6273 @end smallexample
6274
6275 @noindent
6276 The same alternative format is allowed for loops. For example, both of
6277 the following are permitted:
6278
6279 @smallexample @c ada
6280 @cartouche
6281 Clear : while J < 10 loop
6282 A (J) := 0;
6283 end loop Clear;
6284
6285 Clear :
6286 while J < 10 loop
6287 A (J) := 0;
6288 end loop Clear;
6289 @end cartouche
6290 @end smallexample
6291
6292 @item ^Lnnn^MAX_NESTING=nnn^
6293 @emph{Set maximum nesting level.}
6294 The maximum level of nesting of constructs (including subprograms, loops,
6295 blocks, packages, and conditionals) may not exceed the given value
6296 @option{nnn}. A value of zero disconnects this style check.
6297
6298 @item ^m^LINE_LENGTH^
6299 @emph{Check maximum line length.}
6300 The length of source lines must not exceed 79 characters, including
6301 any trailing blanks. The value of 79 allows convenient display on an
6302 80 character wide device or window, allowing for possible special
6303 treatment of 80 character lines. Note that this count is of
6304 characters in the source text. This means that a tab character counts
6305 as one character in this count and a wide character sequence counts as
6306 a single character (however many bytes are needed in the encoding).
6307
6308 @item ^Mnnn^MAX_LENGTH=nnn^
6309 @emph{Set maximum line length.}
6310 The length of lines must not exceed the
6311 given value @option{nnn}. The maximum value that can be specified is 32767.
6312 If neither style option for setting the line length is used, then the
6313 default is 255. This also controls the maximum length of lexical elements,
6314 where the only restriction is that they must fit on a single line.
6315
6316 @item ^n^STANDARD_CASING^
6317 @emph{Check casing of entities in Standard.}
6318 Any identifier from Standard must be cased
6319 to match the presentation in the Ada Reference Manual (for example,
6320 @code{Integer} and @code{ASCII.NUL}).
6321
6322 @item ^N^NONE^
6323 @emph{Turn off all style checks.}
6324 All style check options are turned off.
6325
6326 @item ^o^ORDERED_SUBPROGRAMS^
6327 @emph{Check order of subprogram bodies.}
6328 All subprogram bodies in a given scope
6329 (e.g.@: a package body) must be in alphabetical order. The ordering
6330 rule uses normal Ada rules for comparing strings, ignoring casing
6331 of letters, except that if there is a trailing numeric suffix, then
6332 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6333 before Junk10).
6334
6335 @item ^O^OVERRIDING_INDICATORS^
6336 @emph{Check that overriding subprograms are explicitly marked as such.}
6337 The declaration of a primitive operation of a type extension that overrides
6338 an inherited operation must carry an overriding indicator.
6339
6340 @item ^p^PRAGMA^
6341 @emph{Check pragma casing.}
6342 Pragma names must be written in mixed case, that is, the
6343 initial letter and any letter following an underscore must be uppercase.
6344 All other letters must be lowercase.
6345
6346 @item ^r^REFERENCES^
6347 @emph{Check references.}
6348 All identifier references must be cased in the same way as the
6349 corresponding declaration. No specific casing style is imposed on
6350 identifiers. The only requirement is for consistency of references
6351 with declarations.
6352
6353 @item ^s^SPECS^
6354 @emph{Check separate specs.}
6355 Separate declarations (``specs'') are required for subprograms (a
6356 body is not allowed to serve as its own declaration). The only
6357 exception is that parameterless library level procedures are
6358 not required to have a separate declaration. This exception covers
6359 the most frequent form of main program procedures.
6360
6361 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6362 @emph{Check no statements after @code{then}/@code{else}.}
6363 No statements are allowed
6364 on the same line as a @code{then} or @code{else} keyword following the
6365 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6366 affected, and a special exception allows a pragma to appear after @code{else}.
6367
6368 @item ^t^TOKEN^
6369 @emph{Check token spacing.}
6370 The following token spacing rules are enforced:
6371
6372 @itemize @bullet
6373
6374 @item
6375 The keywords @code{abs} and @code{not} must be followed by a space.
6376
6377 @item
6378 The token @code{=>} must be surrounded by spaces.
6379
6380 @item
6381 The token @code{<>} must be preceded by a space or a left parenthesis.
6382
6383 @item
6384 Binary operators other than @code{**} must be surrounded by spaces.
6385 There is no restriction on the layout of the @code{**} binary operator.
6386
6387 @item
6388 Colon must be surrounded by spaces.
6389
6390 @item
6391 Colon-equal (assignment, initialization) must be surrounded by spaces.
6392
6393 @item
6394 Comma must be the first non-blank character on the line, or be
6395 immediately preceded by a non-blank character, and must be followed
6396 by a space.
6397
6398 @item
6399 If the token preceding a left parenthesis ends with a letter or digit, then
6400 a space must separate the two tokens.
6401
6402 @item
6403 if the token following a right parenthesis starts with a letter or digit, then
6404 a space must separate the two tokens.
6405
6406 @item
6407 A right parenthesis must either be the first non-blank character on
6408 a line, or it must be preceded by a non-blank character.
6409
6410 @item
6411 A semicolon must not be preceded by a space, and must not be followed by
6412 a non-blank character.
6413
6414 @item
6415 A unary plus or minus may not be followed by a space.
6416
6417 @item
6418 A vertical bar must be surrounded by spaces.
6419 @end itemize
6420
6421 @item
6422 Exactly one blank (and no other white space) must appear between
6423 a @code{not} token and a following @code{in} token.
6424
6425 @item ^u^UNNECESSARY_BLANK_LINES^
6426 @emph{Check unnecessary blank lines.}
6427 Unnecessary blank lines are not allowed. A blank line is considered
6428 unnecessary if it appears at the end of the file, or if more than
6429 one blank line occurs in sequence.
6430
6431 @item ^x^XTRA_PARENS^
6432 @emph{Check extra parentheses.}
6433 Unnecessary extra level of parentheses (C-style) are not allowed
6434 around conditions in @code{if} statements, @code{while} statements and
6435 @code{exit} statements.
6436
6437 @item ^y^ALL_BUILTIN^
6438 @emph{Set all standard style check options}
6439 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6440 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6441 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6442 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6443
6444 @ifclear vms
6445 @item -
6446 @emph{Remove style check options}
6447 This causes any subsequent options in the string to act as canceling the
6448 corresponding style check option. To cancel maximum nesting level control,
6449 use @option{L} parameter witout any integer value after that, because any
6450 digit following @option{-} in the parameter string of the @option{-gnaty}
6451 option will be threated as canceling indentation check. The same is true
6452 for @option{M} parameter. @option{y} and @option{N} parameters are not
6453 allowed after @option{-}.
6454
6455 @item +
6456 This causes any subsequent options in the string to enable the corresponding
6457 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6458 if any.
6459 @end ifclear
6460
6461 @ifset vms
6462 @item NOxxx
6463 @emph{Removing style check options}
6464 If the name of a style check is preceded by @option{NO} then the corresponding
6465 style check is turned off. For example @option{NOCOMMENTS} turns off style
6466 checking for comments.
6467 @end ifset
6468 @end table
6469
6470 @noindent
6471 In the above rules, appearing in column one is always permitted, that is,
6472 counts as meeting either a requirement for a required preceding space,
6473 or as meeting a requirement for no preceding space.
6474
6475 Appearing at the end of a line is also always permitted, that is, counts
6476 as meeting either a requirement for a following space, or as meeting
6477 a requirement for no following space.
6478
6479 @noindent
6480 If any of these style rules is violated, a message is generated giving
6481 details on the violation. The initial characters of such messages are
6482 always ``@code{(style)}''. Note that these messages are treated as warning
6483 messages, so they normally do not prevent the generation of an object
6484 file. The @option{-gnatwe} switch can be used to treat warning messages,
6485 including style messages, as fatal errors.
6486
6487 The switch
6488 @ifclear vms
6489 @option{-gnaty} on its own (that is not
6490 followed by any letters or digits) is equivalent
6491 to the use of @option{-gnatyy} as described above, that is all
6492 built-in standard style check options are enabled.
6493
6494 @end ifclear
6495 @ifset vms
6496 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6497 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6498 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6499 @end ifset
6500
6501 The switch
6502 @ifclear vms
6503 @option{-gnatyN}
6504 @end ifclear
6505 @ifset vms
6506 /STYLE_CHECKS=NONE
6507 @end ifset
6508 clears any previously set style checks.
6509
6510 @node Run-Time Checks
6511 @subsection Run-Time Checks
6512 @cindex Division by zero
6513 @cindex Access before elaboration
6514 @cindex Checks, division by zero
6515 @cindex Checks, access before elaboration
6516 @cindex Checks, stack overflow checking
6517
6518 @noindent
6519 By default, the following checks are suppressed: integer overflow
6520 checks, stack overflow checks, and checks for access before
6521 elaboration on subprogram calls. All other checks, including range
6522 checks and array bounds checks, are turned on by default. The
6523 following @command{gcc} switches refine this default behavior.
6524
6525 @table @option
6526 @c !sort!
6527 @item -gnatp
6528 @cindex @option{-gnatp} (@command{gcc})
6529 @cindex Suppressing checks
6530 @cindex Checks, suppressing
6531 @findex Suppress
6532 This switch causes the unit to be compiled
6533 as though @code{pragma Suppress (All_checks)}
6534 had been present in the source. Validity checks are also eliminated (in
6535 other words @option{-gnatp} also implies @option{-gnatVn}.
6536 Use this switch to improve the performance
6537 of the code at the expense of safety in the presence of invalid data or
6538 program bugs.
6539
6540 Note that when checks are suppressed, the compiler is allowed, but not
6541 required, to omit the checking code. If the run-time cost of the
6542 checking code is zero or near-zero, the compiler will generate it even
6543 if checks are suppressed. In particular, if the compiler can prove
6544 that a certain check will necessarily fail, it will generate code to
6545 do an unconditional ``raise'', even if checks are suppressed. The
6546 compiler warns in this case. Another case in which checks may not be
6547 eliminated is when they are embedded in certain run time routines such
6548 as math library routines.
6549
6550 Of course, run-time checks are omitted whenever the compiler can prove
6551 that they will not fail, whether or not checks are suppressed.
6552
6553 Note that if you suppress a check that would have failed, program
6554 execution is erroneous, which means the behavior is totally
6555 unpredictable. The program might crash, or print wrong answers, or
6556 do anything else. It might even do exactly what you wanted it to do
6557 (and then it might start failing mysteriously next week or next
6558 year). The compiler will generate code based on the assumption that
6559 the condition being checked is true, which can result in disaster if
6560 that assumption is wrong.
6561
6562 The checks subject to suppression include all the checks defined by
6563 the Ada standard, the additional implementation defined checks
6564 @code{Alignment_Check}, @code{Atomic_Synchronization}, and
6565 @code{Validity_Check}, as well as any checks introduced using
6566 @code{pragma Check_Name}.
6567
6568 The @option{-gnatp} switch has no effect if a subsequent
6569 @option{-gnat-p} switch appears.
6570
6571 @item -gnat-p
6572 @cindex @option{-gnat-p} (@command{gcc})
6573 @cindex Suppressing checks
6574 @cindex Checks, suppressing
6575 @findex Suppress
6576 This switch cancels the effect of a previous @option{gnatp} switch.
6577
6578 @item -gnato??
6579 @cindex @option{-gnato??} (@command{gcc})
6580 @cindex Overflow checks
6581 @cindex Overflow mode
6582 @cindex Check, overflow
6583 This switch controls the mode used for computing intermediate
6584 arithmetic integer operations, and also enables overflow checking.
6585 For a full description of overflow mode and checking control, see
6586 the ``Overflow Check Handling in GNAT'' appendix in this
6587 User's Guide.
6588
6589 Overflow checks are always enabled by this switch. The argument
6590 controls the mode, using the codes
6591
6592 @itemize
6593 @item 1 = STRICT
6594 In STRICT mode, intermediate operations are always done using the
6595 base type, and overflow checking ensures that the result is within
6596 the base type range.
6597
6598 @item 2 = MINIMIZED
6599 In MINIMIZED mode, overflows in intermediate operations are avoided
6600 where possible by using a larger integer type for the computation
6601 (typically @code{Long_Long_Integer}). Overflow checking ensures that
6602 the result fits in this larger integer type.
6603
6604 @item 3 = ELIMINATED
6605 In ELIMINATED mode, overflows in intermediate operations are avoided
6606 by using multi-precision arithmetic. In this case, overflow checking
6607 has no effect on intermediate operations (since overflow is impossible).
6608 @end itemize
6609
6610 If two digits are present after @option{-gnato} then the first digit
6611 sets the mode for expressions outside assertions, and the second digit
6612 sets the mode for expressions within assertions. Here assertions is used
6613 in the technical sense (which includes for example precondition and
6614 postcondition expressions).
6615
6616 If one digit is present, the corresponding mode is applicable to both
6617 expressions within and outside assertion expressions.
6618
6619 If no digits are present, the default is to enable overflow checks
6620 and set STRICT mode for both kinds of expressions. This is compatible
6621 with the use of @option{-gnato} in previous versions of GNAT.
6622
6623 @findex Machine_Overflows
6624 Note that the @option{-gnato??} switch does not affect the code generated
6625 for any floating-point operations; it applies only to integer semantics.
6626 For floating-point, @value{EDITION} has the @code{Machine_Overflows}
6627 attribute set to @code{False} and the normal mode of operation is to
6628 generate IEEE NaN and infinite values on overflow or invalid operations
6629 (such as dividing 0.0 by 0.0).
6630
6631 The reason that we distinguish overflow checking from other kinds of
6632 range constraint checking is that a failure of an overflow check, unlike
6633 for example the failure of a range check, can result in an incorrect
6634 value, but cannot cause random memory destruction (like an out of range
6635 subscript), or a wild jump (from an out of range case value). Overflow
6636 checking is also quite expensive in time and space, since in general it
6637 requires the use of double length arithmetic.
6638
6639 Note again that the default is @option{^-gnato00^/OVERFLOW_CHECKS=00^},
6640 so overflow checking is not performed in default mode. This means that out of
6641 the box, with the default settings, @value{EDITION} does not do all the checks
6642 expected from the language description in the Ada Reference Manual.
6643 If you want all constraint checks to be performed, as described in this Manual,
6644 then you must explicitly use the @option{-gnato??}
6645 switch either on the @command{gnatmake} or @command{gcc} command.
6646
6647 @item -gnatE
6648 @cindex @option{-gnatE} (@command{gcc})
6649 @cindex Elaboration checks
6650 @cindex Check, elaboration
6651 Enables dynamic checks for access-before-elaboration
6652 on subprogram calls and generic instantiations.
6653 Note that @option{-gnatE} is not necessary for safety, because in the
6654 default mode, GNAT ensures statically that the checks would not fail.
6655 For full details of the effect and use of this switch,
6656 @xref{Compiling with gcc}.
6657
6658 @item -fstack-check
6659 @cindex @option{-fstack-check} (@command{gcc})
6660 @cindex Stack Overflow Checking
6661 @cindex Checks, stack overflow checking
6662 Activates stack overflow checking. For full details of the effect and use of
6663 this switch see @ref{Stack Overflow Checking}.
6664 @end table
6665
6666 @findex Unsuppress
6667 @noindent
6668 The setting of these switches only controls the default setting of the
6669 checks. You may modify them using either @code{Suppress} (to remove
6670 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6671 the program source.
6672
6673 @node Using gcc for Syntax Checking
6674 @subsection Using @command{gcc} for Syntax Checking
6675 @table @option
6676 @item -gnats
6677 @cindex @option{-gnats} (@command{gcc})
6678 @ifclear vms
6679
6680 @noindent
6681 The @code{s} stands for ``syntax''.
6682 @end ifclear
6683
6684 Run GNAT in syntax checking only mode. For
6685 example, the command
6686
6687 @smallexample
6688 $ gcc -c -gnats x.adb
6689 @end smallexample
6690
6691 @noindent
6692 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6693 series of files in a single command
6694 @ifclear vms
6695 , and can use wild cards to specify such a group of files.
6696 Note that you must specify the @option{-c} (compile
6697 only) flag in addition to the @option{-gnats} flag.
6698 @end ifclear
6699 .
6700 You may use other switches in conjunction with @option{-gnats}. In
6701 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6702 format of any generated error messages.
6703
6704 When the source file is empty or contains only empty lines and/or comments,
6705 the output is a warning:
6706
6707 @smallexample
6708 $ gcc -c -gnats -x ada toto.txt
6709 toto.txt:1:01: warning: empty file, contains no compilation units
6710 $
6711 @end smallexample
6712
6713 Otherwise, the output is simply the error messages, if any. No object file or
6714 ALI file is generated by a syntax-only compilation. Also, no units other
6715 than the one specified are accessed. For example, if a unit @code{X}
6716 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6717 check only mode does not access the source file containing unit
6718 @code{Y}.
6719
6720 @cindex Multiple units, syntax checking
6721 Normally, GNAT allows only a single unit in a source file. However, this
6722 restriction does not apply in syntax-check-only mode, and it is possible
6723 to check a file containing multiple compilation units concatenated
6724 together. This is primarily used by the @code{gnatchop} utility
6725 (@pxref{Renaming Files with gnatchop}).
6726 @end table
6727
6728 @node Using gcc for Semantic Checking
6729 @subsection Using @command{gcc} for Semantic Checking
6730 @table @option
6731 @item -gnatc
6732 @cindex @option{-gnatc} (@command{gcc})
6733
6734 @ifclear vms
6735 @noindent
6736 The @code{c} stands for ``check''.
6737 @end ifclear
6738 Causes the compiler to operate in semantic check mode,
6739 with full checking for all illegalities specified in the
6740 Ada Reference Manual, but without generation of any object code
6741 (no object file is generated).
6742
6743 Because dependent files must be accessed, you must follow the GNAT
6744 semantic restrictions on file structuring to operate in this mode:
6745
6746 @itemize @bullet
6747 @item
6748 The needed source files must be accessible
6749 (@pxref{Search Paths and the Run-Time Library (RTL)}).
6750
6751 @item
6752 Each file must contain only one compilation unit.
6753
6754 @item
6755 The file name and unit name must match (@pxref{File Naming Rules}).
6756 @end itemize
6757
6758 The output consists of error messages as appropriate. No object file is
6759 generated. An @file{ALI} file is generated for use in the context of
6760 cross-reference tools, but this file is marked as not being suitable
6761 for binding (since no object file is generated).
6762 The checking corresponds exactly to the notion of
6763 legality in the Ada Reference Manual.
6764
6765 Any unit can be compiled in semantics-checking-only mode, including
6766 units that would not normally be compiled (subunits,
6767 and specifications where a separate body is present).
6768 @end table
6769
6770 @node Compiling Different Versions of Ada
6771 @subsection Compiling Different Versions of Ada
6772
6773 @noindent
6774 The switches described in this section allow you to explicitly specify
6775 the version of the Ada language that your programs are written in.
6776 The default mode is Ada 2012,
6777 but you can also specify Ada 95, Ada 2005 mode, or
6778 indicate Ada 83 compatibility mode.
6779
6780 @table @option
6781 @cindex Compatibility with Ada 83
6782
6783 @item -gnat83 (Ada 83 Compatibility Mode)
6784 @cindex @option{-gnat83} (@command{gcc})
6785 @cindex ACVC, Ada 83 tests
6786 @cindex Ada 83 mode
6787
6788 @noindent
6789 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
6790 specifies that the program is to be compiled in Ada 83 mode. With
6791 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
6792 semantics where this can be done easily.
6793 It is not possible to guarantee this switch does a perfect
6794 job; some subtle tests, such as are
6795 found in earlier ACVC tests (and that have been removed from the ACATS suite
6796 for Ada 95), might not compile correctly.
6797 Nevertheless, this switch may be useful in some circumstances, for example
6798 where, due to contractual reasons, existing code needs to be maintained
6799 using only Ada 83 features.
6800
6801 With few exceptions (most notably the need to use @code{<>} on
6802 @cindex Generic formal parameters
6803 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
6804 reserved words, and the use of packages
6805 with optional bodies), it is not necessary to specify the
6806 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
6807 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
6808 a correct Ada 83 program is usually also a correct program
6809 in these later versions of the language standard.
6810 For further information, please refer to @ref{Compatibility and Porting Guide}.
6811
6812 @item -gnat95 (Ada 95 mode)
6813 @cindex @option{-gnat95} (@command{gcc})
6814 @cindex Ada 95 mode
6815
6816 @noindent
6817 This switch directs the compiler to implement the Ada 95 version of the
6818 language.
6819 Since Ada 95 is almost completely upwards
6820 compatible with Ada 83, Ada 83 programs may generally be compiled using
6821 this switch (see the description of the @option{-gnat83} switch for further
6822 information about Ada 83 mode).
6823 If an Ada 2005 program is compiled in Ada 95 mode,
6824 uses of the new Ada 2005 features will cause error
6825 messages or warnings.
6826
6827 This switch also can be used to cancel the effect of a previous
6828 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
6829 switch earlier in the command line.
6830
6831 @item -gnat05 or -gnat2005 (Ada 2005 mode)
6832 @cindex @option{-gnat05} (@command{gcc})
6833 @cindex @option{-gnat2005} (@command{gcc})
6834 @cindex Ada 2005 mode
6835
6836 @noindent
6837 This switch directs the compiler to implement the Ada 2005 version of the
6838 language, as documented in the official Ada standards document.
6839 Since Ada 2005 is almost completely upwards
6840 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
6841 may generally be compiled using this switch (see the description of the
6842 @option{-gnat83} and @option{-gnat95} switches for further
6843 information).
6844
6845 @item -gnat12 or -gnat2012 (Ada 2012 mode)
6846 @cindex @option{-gnat12} (@command{gcc})
6847 @cindex @option{-gnat2012} (@command{gcc})
6848 @cindex Ada 2012 mode
6849
6850 @noindent
6851 This switch directs the compiler to implement the Ada 2012 version of the
6852 language (also the default).
6853 Since Ada 2012 is almost completely upwards
6854 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
6855 Ada 83 and Ada 95 programs
6856 may generally be compiled using this switch (see the description of the
6857 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
6858 for further information).
6859
6860 @item -gnatX (Enable GNAT Extensions)
6861 @cindex @option{-gnatX} (@command{gcc})
6862 @cindex Ada language extensions
6863 @cindex GNAT extensions
6864
6865 @noindent
6866 This switch directs the compiler to implement the latest version of the
6867 language (currently Ada 2012) and also to enable certain GNAT implementation
6868 extensions that are not part of any Ada standard. For a full list of these
6869 extensions, see the GNAT reference manual.
6870
6871 @end table
6872
6873 @node Character Set Control
6874 @subsection Character Set Control
6875 @table @option
6876 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
6877 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
6878
6879 @noindent
6880 Normally GNAT recognizes the Latin-1 character set in source program
6881 identifiers, as described in the Ada Reference Manual.
6882 This switch causes
6883 GNAT to recognize alternate character sets in identifiers. @var{c} is a
6884 single character ^^or word^ indicating the character set, as follows:
6885
6886 @table @code
6887 @item 1
6888 ISO 8859-1 (Latin-1) identifiers
6889
6890 @item 2
6891 ISO 8859-2 (Latin-2) letters allowed in identifiers
6892
6893 @item 3
6894 ISO 8859-3 (Latin-3) letters allowed in identifiers
6895
6896 @item 4
6897 ISO 8859-4 (Latin-4) letters allowed in identifiers
6898
6899 @item 5
6900 ISO 8859-5 (Cyrillic) letters allowed in identifiers
6901
6902 @item 9
6903 ISO 8859-15 (Latin-9) letters allowed in identifiers
6904
6905 @item ^p^PC^
6906 IBM PC letters (code page 437) allowed in identifiers
6907
6908 @item ^8^PC850^
6909 IBM PC letters (code page 850) allowed in identifiers
6910
6911 @item ^f^FULL_UPPER^
6912 Full upper-half codes allowed in identifiers
6913
6914 @item ^n^NO_UPPER^
6915 No upper-half codes allowed in identifiers
6916
6917 @item ^w^WIDE^
6918 Wide-character codes (that is, codes greater than 255)
6919 allowed in identifiers
6920 @end table
6921
6922 @xref{Foreign Language Representation}, for full details on the
6923 implementation of these character sets.
6924
6925 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
6926 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
6927 Specify the method of encoding for wide characters.
6928 @var{e} is one of the following:
6929
6930 @table @code
6931
6932 @item ^h^HEX^
6933 Hex encoding (brackets coding also recognized)
6934
6935 @item ^u^UPPER^
6936 Upper half encoding (brackets encoding also recognized)
6937
6938 @item ^s^SHIFT_JIS^
6939 Shift/JIS encoding (brackets encoding also recognized)
6940
6941 @item ^e^EUC^
6942 EUC encoding (brackets encoding also recognized)
6943
6944 @item ^8^UTF8^
6945 UTF-8 encoding (brackets encoding also recognized)
6946
6947 @item ^b^BRACKETS^
6948 Brackets encoding only (default value)
6949 @end table
6950 For full details on these encoding
6951 methods see @ref{Wide Character Encodings}.
6952 Note that brackets coding is always accepted, even if one of the other
6953 options is specified, so for example @option{-gnatW8} specifies that both
6954 brackets and UTF-8 encodings will be recognized. The units that are
6955 with'ed directly or indirectly will be scanned using the specified
6956 representation scheme, and so if one of the non-brackets scheme is
6957 used, it must be used consistently throughout the program. However,
6958 since brackets encoding is always recognized, it may be conveniently
6959 used in standard libraries, allowing these libraries to be used with
6960 any of the available coding schemes.
6961
6962 Note that brackets encoding only applies to program text. Within comments,
6963 brackets are considered to be normal graphic characters, and bracket sequences
6964 are never recognized as wide characters.
6965
6966 If no @option{-gnatW?} parameter is present, then the default
6967 representation is normally Brackets encoding only. However, if the
6968 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
6969 byte order mark or BOM for UTF-8), then these three characters are
6970 skipped and the default representation for the file is set to UTF-8.
6971
6972 Note that the wide character representation that is specified (explicitly
6973 or by default) for the main program also acts as the default encoding used
6974 for Wide_Text_IO files if not specifically overridden by a WCEM form
6975 parameter.
6976
6977 @end table
6978
6979 When no @option{-gnatW?} is specified, then characters (other than wide
6980 characters represented using brackets notation) are treated as 8-bit
6981 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
6982 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
6983 characters in the range 16#00#..16#1F# are not accepted in program text
6984 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
6985 in program text, but allowed and ignored in comments. Note in particular
6986 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
6987 as an end of line in this default mode. If your source program contains
6988 instances of the NEL character used as a line terminator,
6989 you must use UTF-8 encoding for the whole
6990 source program. In default mode, all lines must be ended by a standard
6991 end of line sequence (CR, CR/LF, or LF).
6992
6993 Note that the convention of simply accepting all upper half characters in
6994 comments means that programs that use standard ASCII for program text, but
6995 UTF-8 encoding for comments are accepted in default mode, providing that the
6996 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
6997 This is a common mode for many programs with foreign language comments.
6998
6999 @node File Naming Control
7000 @subsection File Naming Control
7001
7002 @table @option
7003 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7004 @cindex @option{-gnatk} (@command{gcc})
7005 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7006 1-999, indicates the maximum allowable length of a file name (not
7007 including the @file{.ads} or @file{.adb} extension). The default is not
7008 to enable file name krunching.
7009
7010 For the source file naming rules, @xref{File Naming Rules}.
7011 @end table
7012
7013 @node Subprogram Inlining Control
7014 @subsection Subprogram Inlining Control
7015
7016 @table @option
7017 @c !sort!
7018 @item -gnatn[12]
7019 @cindex @option{-gnatn} (@command{gcc})
7020 @ifclear vms
7021 The @code{n} here is intended to suggest the first syllable of the
7022 word ``inline''.
7023 @end ifclear
7024 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7025 inlining to actually occur, optimization must be enabled and, in order
7026 to enable inlining of subprograms specified by pragma @code{Inline},
7027 you must also specify this switch.
7028 In the absence of this switch, GNAT does not attempt
7029 inlining and does not need to access the bodies of
7030 subprograms for which @code{pragma Inline} is specified if they are not
7031 in the current unit.
7032
7033 You can optionally specify the inlining level: 1 for moderate inlining across
7034 modules, which is a good compromise between compilation times and performances
7035 at run time, or 2 for full inlining across modules, which may bring about
7036 longer compilation times. If no inlining level is specified, the compiler will
7037 pick it based on the optimization level: 1 for @option{-O1}, @option{-O2} or
7038 @option{-Os} and 2 for @option{-O3}.
7039
7040 If you specify this switch the compiler will access these bodies,
7041 creating an extra source dependency for the resulting object file, and
7042 where possible, the call will be inlined.
7043 For further details on when inlining is possible
7044 see @ref{Inlining of Subprograms}.
7045
7046 @item -gnatN
7047 @cindex @option{-gnatN} (@command{gcc})
7048 This switch activates front-end inlining which also
7049 generates additional dependencies.
7050
7051 When using a gcc-based back end (in practice this means using any version
7052 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7053 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7054 Historically front end inlining was more extensive than the gcc back end
7055 inlining, but that is no longer the case.
7056 @end table
7057
7058 @node Auxiliary Output Control
7059 @subsection Auxiliary Output Control
7060
7061 @table @option
7062 @item -gnatt
7063 @cindex @option{-gnatt} (@command{gcc})
7064 @cindex Writing internal trees
7065 @cindex Internal trees, writing to file
7066 Causes GNAT to write the internal tree for a unit to a file (with the
7067 extension @file{.adt}.
7068 This not normally required, but is used by separate analysis tools.
7069 Typically
7070 these tools do the necessary compilations automatically, so you should
7071 not have to specify this switch in normal operation.
7072 Note that the combination of switches @option{-gnatct}
7073 generates a tree in the form required by ASIS applications.
7074
7075 @item -gnatu
7076 @cindex @option{-gnatu} (@command{gcc})
7077 Print a list of units required by this compilation on @file{stdout}.
7078 The listing includes all units on which the unit being compiled depends
7079 either directly or indirectly.
7080
7081 @ifclear vms
7082 @item -pass-exit-codes
7083 @cindex @option{-pass-exit-codes} (@command{gcc})
7084 If this switch is not used, the exit code returned by @command{gcc} when
7085 compiling multiple files indicates whether all source files have
7086 been successfully used to generate object files or not.
7087
7088 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7089 exit status and allows an integrated development environment to better
7090 react to a compilation failure. Those exit status are:
7091
7092 @table @asis
7093 @item 5
7094 There was an error in at least one source file.
7095 @item 3
7096 At least one source file did not generate an object file.
7097 @item 2
7098 The compiler died unexpectedly (internal error for example).
7099 @item 0
7100 An object file has been generated for every source file.
7101 @end table
7102 @end ifclear
7103 @end table
7104
7105 @node Debugging Control
7106 @subsection Debugging Control
7107
7108 @table @option
7109 @c !sort!
7110 @cindex Debugging options
7111 @ifclear vms
7112 @item -gnatd@var{x}
7113 @cindex @option{-gnatd} (@command{gcc})
7114 Activate internal debugging switches. @var{x} is a letter or digit, or
7115 string of letters or digits, which specifies the type of debugging
7116 outputs desired. Normally these are used only for internal development
7117 or system debugging purposes. You can find full documentation for these
7118 switches in the body of the @code{Debug} unit in the compiler source
7119 file @file{debug.adb}.
7120 @end ifclear
7121
7122 @item -gnatG[=nn]
7123 @cindex @option{-gnatG} (@command{gcc})
7124 This switch causes the compiler to generate auxiliary output containing
7125 a pseudo-source listing of the generated expanded code. Like most Ada
7126 compilers, GNAT works by first transforming the high level Ada code into
7127 lower level constructs. For example, tasking operations are transformed
7128 into calls to the tasking run-time routines. A unique capability of GNAT
7129 is to list this expanded code in a form very close to normal Ada source.
7130 This is very useful in understanding the implications of various Ada
7131 usage on the efficiency of the generated code. There are many cases in
7132 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7133 generate a lot of run-time code. By using @option{-gnatG} you can identify
7134 these cases, and consider whether it may be desirable to modify the coding
7135 approach to improve efficiency.
7136
7137 The optional parameter @code{nn} if present after -gnatG specifies an
7138 alternative maximum line length that overrides the normal default of 72.
7139 This value is in the range 40-999999, values less than 40 being silently
7140 reset to 40. The equal sign is optional.
7141
7142 The format of the output is very similar to standard Ada source, and is
7143 easily understood by an Ada programmer. The following special syntactic
7144 additions correspond to low level features used in the generated code that
7145 do not have any exact analogies in pure Ada source form. The following
7146 is a partial list of these special constructions. See the spec
7147 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7148
7149 If the switch @option{-gnatL} is used in conjunction with
7150 @cindex @option{-gnatL} (@command{gcc})
7151 @option{-gnatG}, then the original source lines are interspersed
7152 in the expanded source (as comment lines with the original line number).
7153
7154 @table @code
7155 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7156 Shows the storage pool being used for an allocator.
7157
7158 @item at end @var{procedure-name};
7159 Shows the finalization (cleanup) procedure for a scope.
7160
7161 @item (if @var{expr} then @var{expr} else @var{expr})
7162 Conditional expression equivalent to the @code{x?y:z} construction in C.
7163
7164 @item @var{target}^^^(@var{source})
7165 A conversion with floating-point truncation instead of rounding.
7166
7167 @item @var{target}?(@var{source})
7168 A conversion that bypasses normal Ada semantic checking. In particular
7169 enumeration types and fixed-point types are treated simply as integers.
7170
7171 @item @var{target}?^^^(@var{source})
7172 Combines the above two cases.
7173
7174 @item @var{x} #/ @var{y}
7175 @itemx @var{x} #mod @var{y}
7176 @itemx @var{x} #* @var{y}
7177 @itemx @var{x} #rem @var{y}
7178 A division or multiplication of fixed-point values which are treated as
7179 integers without any kind of scaling.
7180
7181 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7182 Shows the storage pool associated with a @code{free} statement.
7183
7184 @item [subtype or type declaration]
7185 Used to list an equivalent declaration for an internally generated
7186 type that is referenced elsewhere in the listing.
7187
7188 @c @item freeze @var{type-name} @ovar{actions}
7189 @c Expanding @ovar macro inline (explanation in macro def comments)
7190 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7191 Shows the point at which @var{type-name} is frozen, with possible
7192 associated actions to be performed at the freeze point.
7193
7194 @item reference @var{itype}
7195 Reference (and hence definition) to internal type @var{itype}.
7196
7197 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7198 Intrinsic function call.
7199
7200 @item @var{label-name} : label
7201 Declaration of label @var{labelname}.
7202
7203 @item #$ @var{subprogram-name}
7204 An implicit call to a run-time support routine
7205 (to meet the requirement of H.3.1(9) in a
7206 convenient manner).
7207
7208 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7209 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7210 @var{expr}, but handled more efficiently).
7211
7212 @item [constraint_error]
7213 Raise the @code{Constraint_Error} exception.
7214
7215 @item @var{expression}'reference
7216 A pointer to the result of evaluating @var{expression}.
7217
7218 @item @var{target-type}!(@var{source-expression})
7219 An unchecked conversion of @var{source-expression} to @var{target-type}.
7220
7221 @item [@var{numerator}/@var{denominator}]
7222 Used to represent internal real literals (that) have no exact
7223 representation in base 2-16 (for example, the result of compile time
7224 evaluation of the expression 1.0/27.0).
7225 @end table
7226
7227 @item -gnatD[=nn]
7228 @cindex @option{-gnatD} (@command{gcc})
7229 When used in conjunction with @option{-gnatG}, this switch causes
7230 the expanded source, as described above for
7231 @option{-gnatG} to be written to files with names
7232 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7233 instead of to the standard output file. For
7234 example, if the source file name is @file{hello.adb}, then a file
7235 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
7236 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7237 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7238 you to do source level debugging using the generated code which is
7239 sometimes useful for complex code, for example to find out exactly
7240 which part of a complex construction raised an exception. This switch
7241 also suppress generation of cross-reference information (see
7242 @option{-gnatx}) since otherwise the cross-reference information
7243 would refer to the @file{^.dg^.DG^} file, which would cause
7244 confusion since this is not the original source file.
7245
7246 Note that @option{-gnatD} actually implies @option{-gnatG}
7247 automatically, so it is not necessary to give both options.
7248 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7249
7250 If the switch @option{-gnatL} is used in conjunction with
7251 @cindex @option{-gnatL} (@command{gcc})
7252 @option{-gnatDG}, then the original source lines are interspersed
7253 in the expanded source (as comment lines with the original line number).
7254
7255 The optional parameter @code{nn} if present after -gnatD specifies an
7256 alternative maximum line length that overrides the normal default of 72.
7257 This value is in the range 40-999999, values less than 40 being silently
7258 reset to 40. The equal sign is optional.
7259
7260 @item -gnatr
7261 @cindex @option{-gnatr} (@command{gcc})
7262 @cindex pragma Restrictions
7263 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7264 so that violation of restrictions causes warnings rather than illegalities.
7265 This is useful during the development process when new restrictions are added
7266 or investigated. The switch also causes pragma Profile to be treated as
7267 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7268 restriction warnings rather than restrictions.
7269
7270 @ifclear vms
7271 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7272 @cindex @option{-gnatR} (@command{gcc})
7273 This switch controls output from the compiler of a listing showing
7274 representation information for declared types and objects. For
7275 @option{-gnatR0}, no information is output (equivalent to omitting
7276 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7277 so @option{-gnatR} with no parameter has the same effect), size and alignment
7278 information is listed for declared array and record types. For
7279 @option{-gnatR2}, size and alignment information is listed for all
7280 declared types and objects. Finally @option{-gnatR3} includes symbolic
7281 expressions for values that are computed at run time for
7282 variant records. These symbolic expressions have a mostly obvious
7283 format with #n being used to represent the value of the n'th
7284 discriminant. See source files @file{repinfo.ads/adb} in the
7285 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7286 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7287 the output is to a file with the name @file{^file.rep^file_REP^} where
7288 file is the name of the corresponding source file.
7289
7290 @item -gnatRm[s]
7291 This form of the switch controls output of subprogram conventions
7292 and parameter passing mechanisms for all subprograms. A following
7293 @code{s} means output to a file as described above.
7294 @end ifclear
7295 @ifset vms
7296 @item /REPRESENTATION_INFO
7297 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7298 This qualifier controls output from the compiler of a listing showing
7299 representation information for declared types and objects. For
7300 @option{/REPRESENTATION_INFO=NONE}, no information is output
7301 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7302 @option{/REPRESENTATION_INFO} without option is equivalent to
7303 @option{/REPRESENTATION_INFO=ARRAYS}.
7304 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7305 information is listed for declared array and record types. For
7306 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7307 is listed for all expression information for values that are computed
7308 at run time for variant records. These symbolic expressions have a mostly
7309 obvious format with #n being used to represent the value of the n'th
7310 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7311 @code{GNAT} sources for full details on the format of
7312 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7313 If _FILE is added at the end of an option
7314 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7315 then the output is to a file with the name @file{file_REP} where
7316 file is the name of the corresponding source file.
7317
7318 @item /REPRESENTATION_INFO=MECHANISMS
7319 This qualifier form controls output of subprogram conventions
7320 and parameter passing mechanisms for all subprograms. It is
7321 possible to append _FILE as described above to cause information
7322 to be written to a file.
7323 @end ifset
7324
7325 Note that it is possible for record components to have zero size. In
7326 this case, the component clause uses an obvious extension of permitted
7327 Ada syntax, for example @code{at 0 range 0 .. -1}.
7328
7329 Representation information requires that code be generated (since it is the
7330 code generator that lays out complex data structures). If an attempt is made
7331 to output representation information when no code is generated, for example
7332 when a subunit is compiled on its own, then no information can be generated
7333 and the compiler outputs a message to this effect.
7334
7335 @item -gnatS
7336 @cindex @option{-gnatS} (@command{gcc})
7337 The use of the switch @option{-gnatS} for an
7338 Ada compilation will cause the compiler to output a
7339 representation of package Standard in a form very
7340 close to standard Ada. It is not quite possible to
7341 do this entirely in standard Ada (since new
7342 numeric base types cannot be created in standard
7343 Ada), but the output is easily
7344 readable to any Ada programmer, and is useful to
7345 determine the characteristics of target dependent
7346 types in package Standard.
7347
7348 @item -gnatx
7349 @cindex @option{-gnatx} (@command{gcc})
7350 Normally the compiler generates full cross-referencing information in
7351 the @file{ALI} file. This information is used by a number of tools,
7352 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7353 suppresses this information. This saves some space and may slightly
7354 speed up compilation, but means that these tools cannot be used.
7355 @end table
7356
7357 @node Exception Handling Control
7358 @subsection Exception Handling Control
7359
7360 @noindent
7361 GNAT uses two methods for handling exceptions at run-time. The
7362 @code{setjmp/longjmp} method saves the context when entering
7363 a frame with an exception handler. Then when an exception is
7364 raised, the context can be restored immediately, without the
7365 need for tracing stack frames. This method provides very fast
7366 exception propagation, but introduces significant overhead for
7367 the use of exception handlers, even if no exception is raised.
7368
7369 The other approach is called ``zero cost'' exception handling.
7370 With this method, the compiler builds static tables to describe
7371 the exception ranges. No dynamic code is required when entering
7372 a frame containing an exception handler. When an exception is
7373 raised, the tables are used to control a back trace of the
7374 subprogram invocation stack to locate the required exception
7375 handler. This method has considerably poorer performance for
7376 the propagation of exceptions, but there is no overhead for
7377 exception handlers if no exception is raised. Note that in this
7378 mode and in the context of mixed Ada and C/C++ programming,
7379 to propagate an exception through a C/C++ code, the C/C++ code
7380 must be compiled with the @option{-funwind-tables} GCC's
7381 option.
7382
7383 The following switches may be used to control which of the
7384 two exception handling methods is used.
7385
7386 @table @option
7387 @c !sort!
7388
7389 @item --RTS=sjlj
7390 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7391 This switch causes the setjmp/longjmp run-time (when available) to be used
7392 for exception handling. If the default
7393 mechanism for the target is zero cost exceptions, then
7394 this switch can be used to modify this default, and must be
7395 used for all units in the partition.
7396 This option is rarely used. One case in which it may be
7397 advantageous is if you have an application where exception
7398 raising is common and the overall performance of the
7399 application is improved by favoring exception propagation.
7400
7401 @item --RTS=zcx
7402 @cindex @option{--RTS=zcx} (@command{gnatmake})
7403 @cindex Zero Cost Exceptions
7404 This switch causes the zero cost approach to be used
7405 for exception handling. If this is the default mechanism for the
7406 target (see below), then this switch is unneeded. If the default
7407 mechanism for the target is setjmp/longjmp exceptions, then
7408 this switch can be used to modify this default, and must be
7409 used for all units in the partition.
7410 This option can only be used if the zero cost approach
7411 is available for the target in use, otherwise it will generate an error.
7412 @end table
7413
7414 @noindent
7415 The same option @option{--RTS} must be used both for @command{gcc}
7416 and @command{gnatbind}. Passing this option to @command{gnatmake}
7417 (@pxref{Switches for gnatmake}) will ensure the required consistency
7418 through the compilation and binding steps.
7419
7420 @node Units to Sources Mapping Files
7421 @subsection Units to Sources Mapping Files
7422
7423 @table @option
7424
7425 @item -gnatem=@var{path}
7426 @cindex @option{-gnatem} (@command{gcc})
7427 A mapping file is a way to communicate to the compiler two mappings:
7428 from unit names to file names (without any directory information) and from
7429 file names to path names (with full directory information). These mappings
7430 are used by the compiler to short-circuit the path search.
7431
7432 The use of mapping files is not required for correct operation of the
7433 compiler, but mapping files can improve efficiency, particularly when
7434 sources are read over a slow network connection. In normal operation,
7435 you need not be concerned with the format or use of mapping files,
7436 and the @option{-gnatem} switch is not a switch that you would use
7437 explicitly. It is intended primarily for use by automatic tools such as
7438 @command{gnatmake} running under the project file facility. The
7439 description here of the format of mapping files is provided
7440 for completeness and for possible use by other tools.
7441
7442 A mapping file is a sequence of sets of three lines. In each set, the
7443 first line is the unit name, in lower case, with @code{%s} appended
7444 for specs and @code{%b} appended for bodies; the second line is the
7445 file name; and the third line is the path name.
7446
7447 Example:
7448 @smallexample
7449 main%b
7450 main.2.ada
7451 /gnat/project1/sources/main.2.ada
7452 @end smallexample
7453
7454 When the switch @option{-gnatem} is specified, the compiler will
7455 create in memory the two mappings from the specified file. If there is
7456 any problem (nonexistent file, truncated file or duplicate entries),
7457 no mapping will be created.
7458
7459 Several @option{-gnatem} switches may be specified; however, only the
7460 last one on the command line will be taken into account.
7461
7462 When using a project file, @command{gnatmake} creates a temporary
7463 mapping file and communicates it to the compiler using this switch.
7464
7465 @end table
7466
7467 @node Integrated Preprocessing
7468 @subsection Integrated Preprocessing
7469
7470 @noindent
7471 GNAT sources may be preprocessed immediately before compilation.
7472 In this case, the actual
7473 text of the source is not the text of the source file, but is derived from it
7474 through a process called preprocessing. Integrated preprocessing is specified
7475 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7476 indicates, through a text file, the preprocessing data to be used.
7477 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7478
7479 @noindent
7480 Note that when integrated preprocessing is used, the output from the
7481 preprocessor is not written to any external file. Instead it is passed
7482 internally to the compiler. If you need to preserve the result of
7483 preprocessing in a file, then you should use @command{gnatprep}
7484 to perform the desired preprocessing in stand-alone mode.
7485
7486 @noindent
7487 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7488 used when Integrated Preprocessing is used. The reason is that preprocessing
7489 with another Preprocessing Data file without changing the sources will
7490 not trigger recompilation without this switch.
7491
7492 @noindent
7493 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7494 always trigger recompilation for sources that are preprocessed,
7495 because @command{gnatmake} cannot compute the checksum of the source after
7496 preprocessing.
7497
7498 @noindent
7499 The actual preprocessing function is described in details in section
7500 @ref{Preprocessing with gnatprep}. This section only describes how integrated
7501 preprocessing is triggered and parameterized.
7502
7503 @table @code
7504
7505 @item -gnatep=@var{file}
7506 @cindex @option{-gnatep} (@command{gcc})
7507 This switch indicates to the compiler the file name (without directory
7508 information) of the preprocessor data file to use. The preprocessor data file
7509 should be found in the source directories. Note that when the compiler is
7510 called by a builder such as (@command{gnatmake} with a project
7511 file, if the object directory is not also a source directory, the builder needs
7512 to be called with @option{-x}.
7513
7514 @noindent
7515 A preprocessing data file is a text file with significant lines indicating
7516 how should be preprocessed either a specific source or all sources not
7517 mentioned in other lines. A significant line is a nonempty, non-comment line.
7518 Comments are similar to Ada comments.
7519
7520 @noindent
7521 Each significant line starts with either a literal string or the character '*'.
7522 A literal string is the file name (without directory information) of the source
7523 to preprocess. A character '*' indicates the preprocessing for all the sources
7524 that are not specified explicitly on other lines (order of the lines is not
7525 significant). It is an error to have two lines with the same file name or two
7526 lines starting with the character '*'.
7527
7528 @noindent
7529 After the file name or the character '*', another optional literal string
7530 indicating the file name of the definition file to be used for preprocessing
7531 (@pxref{Form of Definitions File}). The definition files are found by the
7532 compiler in one of the source directories. In some cases, when compiling
7533 a source in a directory other than the current directory, if the definition
7534 file is in the current directory, it may be necessary to add the current
7535 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7536 the compiler would not find the definition file.
7537
7538 @noindent
7539 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7540 be found. Those ^switches^switches^ are:
7541
7542 @table @code
7543
7544 @item -b
7545 Causes both preprocessor lines and the lines deleted by
7546 preprocessing to be replaced by blank lines, preserving the line number.
7547 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7548 it cancels the effect of @option{-c}.
7549
7550 @item -c
7551 Causes both preprocessor lines and the lines deleted
7552 by preprocessing to be retained as comments marked
7553 with the special string ``@code{--! }''.
7554
7555 @item -Dsymbol=value
7556 Define or redefine a symbol, associated with value. A symbol is an Ada
7557 identifier, or an Ada reserved word, with the exception of @code{if},
7558 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7559 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7560 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7561 same name defined in a definition file.
7562
7563 @item -s
7564 Causes a sorted list of symbol names and values to be
7565 listed on the standard output file.
7566
7567 @item -u
7568 Causes undefined symbols to be treated as having the value @code{FALSE}
7569 in the context
7570 of a preprocessor test. In the absence of this option, an undefined symbol in
7571 a @code{#if} or @code{#elsif} test will be treated as an error.
7572
7573 @end table
7574
7575 @noindent
7576 Examples of valid lines in a preprocessor data file:
7577
7578 @smallexample
7579 "toto.adb" "prep.def" -u
7580 -- preprocess "toto.adb", using definition file "prep.def",
7581 -- undefined symbol are False.
7582
7583 * -c -DVERSION=V101
7584 -- preprocess all other sources without a definition file;
7585 -- suppressed lined are commented; symbol VERSION has the value V101.
7586
7587 "titi.adb" "prep2.def" -s
7588 -- preprocess "titi.adb", using definition file "prep2.def";
7589 -- list all symbols with their values.
7590 @end smallexample
7591
7592 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7593 @cindex @option{-gnateD} (@command{gcc})
7594 Define or redefine a preprocessing symbol, associated with value. If no value
7595 is given on the command line, then the value of the symbol is @code{True}.
7596 A symbol is an identifier, following normal Ada (case-insensitive)
7597 rules for its syntax, and value is any sequence (including an empty sequence)
7598 of characters from the set (letters, digits, period, underline).
7599 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7600 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7601
7602 @noindent
7603 A symbol declared with this ^switch^switch^ on the command line replaces a
7604 symbol with the same name either in a definition file or specified with a
7605 ^switch^switch^ -D in the preprocessor data file.
7606
7607 @noindent
7608 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7609
7610 @item -gnateG
7611 When integrated preprocessing is performed and the preprocessor modifies
7612 the source text, write the result of this preprocessing into a file
7613 <source>^.prep^_prep^.
7614
7615 @end table
7616
7617 @node Code Generation Control
7618 @subsection Code Generation Control
7619
7620 @noindent
7621
7622 The GCC technology provides a wide range of target dependent
7623 @option{-m} switches for controlling
7624 details of code generation with respect to different versions of
7625 architectures. This includes variations in instruction sets (e.g.@:
7626 different members of the power pc family), and different requirements
7627 for optimal arrangement of instructions (e.g.@: different members of
7628 the x86 family). The list of available @option{-m} switches may be
7629 found in the GCC documentation.
7630
7631 Use of these @option{-m} switches may in some cases result in improved
7632 code performance.
7633
7634 The @value{EDITION} technology is tested and qualified without any
7635 @option{-m} switches,
7636 so generally the most reliable approach is to avoid the use of these
7637 switches. However, we generally expect most of these switches to work
7638 successfully with @value{EDITION}, and many customers have reported successful
7639 use of these options.
7640
7641 Our general advice is to avoid the use of @option{-m} switches unless
7642 special needs lead to requirements in this area. In particular,
7643 there is no point in using @option{-m} switches to improve performance
7644 unless you actually see a performance improvement.
7645
7646 @ifset vms
7647 @node Return Codes
7648 @subsection Return Codes
7649 @cindex Return Codes
7650 @cindex @option{/RETURN_CODES=VMS}
7651
7652 @noindent
7653 On VMS, GNAT compiled programs return POSIX-style codes by default,
7654 e.g.@: @option{/RETURN_CODES=POSIX}.
7655
7656 To enable VMS style return codes, use GNAT BIND and LINK with the option
7657 @option{/RETURN_CODES=VMS}. For example:
7658
7659 @smallexample
7660 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7661 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7662 @end smallexample
7663
7664 @noindent
7665 Programs built with /RETURN_CODES=VMS are suitable to be called in
7666 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7667 are suitable for spawning with appropriate GNAT RTL routines.
7668
7669 @end ifset
7670
7671 @node Search Paths and the Run-Time Library (RTL)
7672 @section Search Paths and the Run-Time Library (RTL)
7673
7674 @noindent
7675 With the GNAT source-based library system, the compiler must be able to
7676 find source files for units that are needed by the unit being compiled.
7677 Search paths are used to guide this process.
7678
7679 The compiler compiles one source file whose name must be given
7680 explicitly on the command line. In other words, no searching is done
7681 for this file. To find all other source files that are needed (the most
7682 common being the specs of units), the compiler examines the following
7683 directories, in the following order:
7684
7685 @enumerate
7686 @item
7687 The directory containing the source file of the main unit being compiled
7688 (the file name on the command line).
7689
7690 @item
7691 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7692 @command{gcc} command line, in the order given.
7693
7694 @item
7695 @findex ADA_PRJ_INCLUDE_FILE
7696 Each of the directories listed in the text file whose name is given
7697 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7698
7699 @noindent
7700 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7701 driver when project files are used. It should not normally be set
7702 by other means.
7703
7704 @item
7705 @findex ADA_INCLUDE_PATH
7706 Each of the directories listed in the value of the
7707 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7708 @ifclear vms
7709 Construct this value
7710 exactly as the @env{PATH} environment variable: a list of directory
7711 names separated by colons (semicolons when working with the NT version).
7712 @end ifclear
7713 @ifset vms
7714 Normally, define this value as a logical name containing a comma separated
7715 list of directory names.
7716
7717 This variable can also be defined by means of an environment string
7718 (an argument to the HP C exec* set of functions).
7719
7720 Logical Name:
7721 @smallexample
7722 DEFINE ANOTHER_PATH FOO:[BAG]
7723 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
7724 @end smallexample
7725
7726 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
7727 first, followed by the standard Ada
7728 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
7729 If this is not redefined, the user will obtain the HP Ada 83 IO packages
7730 (Text_IO, Sequential_IO, etc)
7731 instead of the standard Ada packages. Thus, in order to get the standard Ada
7732 packages by default, ADA_INCLUDE_PATH must be redefined.
7733 @end ifset
7734
7735 @item
7736 The content of the @file{ada_source_path} file which is part of the GNAT
7737 installation tree and is used to store standard libraries such as the
7738 GNAT Run Time Library (RTL) source files.
7739 @ifclear vms
7740 @ref{Installing a library}
7741 @end ifclear
7742 @end enumerate
7743
7744 @noindent
7745 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
7746 inhibits the use of the directory
7747 containing the source file named in the command line. You can still
7748 have this directory on your search path, but in this case it must be
7749 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
7750
7751 Specifying the switch @option{-nostdinc}
7752 inhibits the search of the default location for the GNAT Run Time
7753 Library (RTL) source files.
7754
7755 The compiler outputs its object files and ALI files in the current
7756 working directory.
7757 @ifclear vms
7758 Caution: The object file can be redirected with the @option{-o} switch;
7759 however, @command{gcc} and @code{gnat1} have not been coordinated on this
7760 so the @file{ALI} file will not go to the right place. Therefore, you should
7761 avoid using the @option{-o} switch.
7762 @end ifclear
7763
7764 @findex System.IO
7765 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
7766 children make up the GNAT RTL, together with the simple @code{System.IO}
7767 package used in the @code{"Hello World"} example. The sources for these units
7768 are needed by the compiler and are kept together in one directory. Not
7769 all of the bodies are needed, but all of the sources are kept together
7770 anyway. In a normal installation, you need not specify these directory
7771 names when compiling or binding. Either the environment variables or
7772 the built-in defaults cause these files to be found.
7773
7774 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
7775 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
7776 consisting of child units of @code{GNAT}. This is a collection of generally
7777 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
7778 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
7779
7780 Besides simplifying access to the RTL, a major use of search paths is
7781 in compiling sources from multiple directories. This can make
7782 development environments much more flexible.
7783
7784 @node Order of Compilation Issues
7785 @section Order of Compilation Issues
7786
7787 @noindent
7788 If, in our earlier example, there was a spec for the @code{hello}
7789 procedure, it would be contained in the file @file{hello.ads}; yet this
7790 file would not have to be explicitly compiled. This is the result of the
7791 model we chose to implement library management. Some of the consequences
7792 of this model are as follows:
7793
7794 @itemize @bullet
7795 @item
7796 There is no point in compiling specs (except for package
7797 specs with no bodies) because these are compiled as needed by clients. If
7798 you attempt a useless compilation, you will receive an error message.
7799 It is also useless to compile subunits because they are compiled as needed
7800 by the parent.
7801
7802 @item
7803 There are no order of compilation requirements: performing a
7804 compilation never obsoletes anything. The only way you can obsolete
7805 something and require recompilations is to modify one of the
7806 source files on which it depends.
7807
7808 @item
7809 There is no library as such, apart from the ALI files
7810 (@pxref{The Ada Library Information Files}, for information on the format
7811 of these files). For now we find it convenient to create separate ALI files,
7812 but eventually the information therein may be incorporated into the object
7813 file directly.
7814
7815 @item
7816 When you compile a unit, the source files for the specs of all units
7817 that it @code{with}'s, all its subunits, and the bodies of any generics it
7818 instantiates must be available (reachable by the search-paths mechanism
7819 described above), or you will receive a fatal error message.
7820 @end itemize
7821
7822 @node Examples
7823 @section Examples
7824
7825 @noindent
7826 The following are some typical Ada compilation command line examples:
7827
7828 @table @code
7829 @item $ gcc -c xyz.adb
7830 Compile body in file @file{xyz.adb} with all default options.
7831
7832 @ifclear vms
7833 @item $ gcc -c -O2 -gnata xyz-def.adb
7834 @end ifclear
7835 @ifset vms
7836 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
7837 @end ifset
7838
7839 Compile the child unit package in file @file{xyz-def.adb} with extensive
7840 optimizations, and pragma @code{Assert}/@code{Debug} statements
7841 enabled.
7842
7843 @item $ gcc -c -gnatc abc-def.adb
7844 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
7845 mode.
7846 @end table
7847
7848 @node Binding with gnatbind
7849 @chapter Binding with @code{gnatbind}
7850 @findex gnatbind
7851
7852 @menu
7853 * Running gnatbind::
7854 * Switches for gnatbind::
7855 * Command-Line Access::
7856 * Search Paths for gnatbind::
7857 * Examples of gnatbind Usage::
7858 @end menu
7859
7860 @noindent
7861 This chapter describes the GNAT binder, @code{gnatbind}, which is used
7862 to bind compiled GNAT objects.
7863
7864 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
7865 driver (see @ref{The GNAT Driver and Project Files}).
7866
7867 The @code{gnatbind} program performs four separate functions:
7868
7869 @enumerate
7870 @item
7871 Checks that a program is consistent, in accordance with the rules in
7872 Chapter 10 of the Ada Reference Manual. In particular, error
7873 messages are generated if a program uses inconsistent versions of a
7874 given unit.
7875
7876 @item
7877 Checks that an acceptable order of elaboration exists for the program
7878 and issues an error message if it cannot find an order of elaboration
7879 that satisfies the rules in Chapter 10 of the Ada Language Manual.
7880
7881 @item
7882 Generates a main program incorporating the given elaboration order.
7883 This program is a small Ada package (body and spec) that
7884 must be subsequently compiled
7885 using the GNAT compiler. The necessary compilation step is usually
7886 performed automatically by @command{gnatlink}. The two most important
7887 functions of this program
7888 are to call the elaboration routines of units in an appropriate order
7889 and to call the main program.
7890
7891 @item
7892 Determines the set of object files required by the given main program.
7893 This information is output in the forms of comments in the generated program,
7894 to be read by the @command{gnatlink} utility used to link the Ada application.
7895 @end enumerate
7896
7897 @node Running gnatbind
7898 @section Running @code{gnatbind}
7899
7900 @noindent
7901 The form of the @code{gnatbind} command is
7902
7903 @smallexample
7904 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
7905 @c Expanding @ovar macro inline (explanation in macro def comments)
7906 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
7907 @end smallexample
7908
7909 @noindent
7910 where @file{@var{mainprog}.adb} is the Ada file containing the main program
7911 unit body. @code{gnatbind} constructs an Ada
7912 package in two files whose names are
7913 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
7914 For example, if given the
7915 parameter @file{hello.ali}, for a main program contained in file
7916 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
7917 and @file{b~hello.adb}.
7918
7919 When doing consistency checking, the binder takes into consideration
7920 any source files it can locate. For example, if the binder determines
7921 that the given main program requires the package @code{Pack}, whose
7922 @file{.ALI}
7923 file is @file{pack.ali} and whose corresponding source spec file is
7924 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
7925 (using the same search path conventions as previously described for the
7926 @command{gcc} command). If it can locate this source file, it checks that
7927 the time stamps
7928 or source checksums of the source and its references to in @file{ALI} files
7929 match. In other words, any @file{ALI} files that mentions this spec must have
7930 resulted from compiling this version of the source file (or in the case
7931 where the source checksums match, a version close enough that the
7932 difference does not matter).
7933
7934 @cindex Source files, use by binder
7935 The effect of this consistency checking, which includes source files, is
7936 that the binder ensures that the program is consistent with the latest
7937 version of the source files that can be located at bind time. Editing a
7938 source file without compiling files that depend on the source file cause
7939 error messages to be generated by the binder.
7940
7941 For example, suppose you have a main program @file{hello.adb} and a
7942 package @code{P}, from file @file{p.ads} and you perform the following
7943 steps:
7944
7945 @enumerate
7946 @item
7947 Enter @code{gcc -c hello.adb} to compile the main program.
7948
7949 @item
7950 Enter @code{gcc -c p.ads} to compile package @code{P}.
7951
7952 @item
7953 Edit file @file{p.ads}.
7954
7955 @item
7956 Enter @code{gnatbind hello}.
7957 @end enumerate
7958
7959 @noindent
7960 At this point, the file @file{p.ali} contains an out-of-date time stamp
7961 because the file @file{p.ads} has been edited. The attempt at binding
7962 fails, and the binder generates the following error messages:
7963
7964 @smallexample
7965 error: "hello.adb" must be recompiled ("p.ads" has been modified)
7966 error: "p.ads" has been modified and must be recompiled
7967 @end smallexample
7968
7969 @noindent
7970 Now both files must be recompiled as indicated, and then the bind can
7971 succeed, generating a main program. You need not normally be concerned
7972 with the contents of this file, but for reference purposes a sample
7973 binder output file is given in @ref{Example of Binder Output File}.
7974
7975 In most normal usage, the default mode of @command{gnatbind} which is to
7976 generate the main package in Ada, as described in the previous section.
7977 In particular, this means that any Ada programmer can read and understand
7978 the generated main program. It can also be debugged just like any other
7979 Ada code provided the @option{^-g^/DEBUG^} switch is used for
7980 @command{gnatbind} and @command{gnatlink}.
7981
7982 @node Switches for gnatbind
7983 @section Switches for @command{gnatbind}
7984
7985 @noindent
7986 The following switches are available with @code{gnatbind}; details will
7987 be presented in subsequent sections.
7988
7989 @menu
7990 * Consistency-Checking Modes::
7991 * Binder Error Message Control::
7992 * Elaboration Control::
7993 * Output Control::
7994 * Dynamic Allocation Control::
7995 * Binding with Non-Ada Main Programs::
7996 * Binding Programs with No Main Subprogram::
7997 @end menu
7998
7999 @table @option
8000 @c !sort!
8001
8002 @item --version
8003 @cindex @option{--version} @command{gnatbind}
8004 Display Copyright and version, then exit disregarding all other options.
8005
8006 @item --help
8007 @cindex @option{--help} @command{gnatbind}
8008 If @option{--version} was not used, display usage, then exit disregarding
8009 all other options.
8010
8011 @item -a
8012 @cindex @option{-a} @command{gnatbind}
8013 Indicates that, if supported by the platform, the adainit procedure should
8014 be treated as an initialisation routine by the linker (a constructor). This
8015 is intended to be used by the Project Manager to automatically initialize
8016 shared Stand-Alone Libraries.
8017
8018 @item ^-aO^/OBJECT_SEARCH^
8019 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8020 Specify directory to be searched for ALI files.
8021
8022 @item ^-aI^/SOURCE_SEARCH^
8023 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8024 Specify directory to be searched for source file.
8025
8026 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8027 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8028 Output ALI list (to standard output or to the named file).
8029
8030 @item ^-b^/REPORT_ERRORS=BRIEF^
8031 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8032 Generate brief messages to @file{stderr} even if verbose mode set.
8033
8034 @item ^-c^/NOOUTPUT^
8035 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8036 Check only, no generation of binder output file.
8037
8038 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8039 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8040 This switch can be used to change the default task stack size value
8041 to a specified size @var{nn}, which is expressed in bytes by default, or
8042 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8043 with @var{m}.
8044 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8045 in effect, to completing all task specs with
8046 @smallexample @c ada
8047 pragma Storage_Size (nn);
8048 @end smallexample
8049 When they do not already have such a pragma.
8050
8051 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8052 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8053 This switch can be used to change the default secondary stack size value
8054 to a specified size @var{nn}, which is expressed in bytes by default, or
8055 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8056 with @var{m}.
8057
8058 The secondary stack is used to deal with functions that return a variable
8059 sized result, for example a function returning an unconstrained
8060 String. There are two ways in which this secondary stack is allocated.
8061
8062 For most targets, the secondary stack is growing on demand and is allocated
8063 as a chain of blocks in the heap. The -D option is not very
8064 relevant. It only give some control over the size of the allocated
8065 blocks (whose size is the minimum of the default secondary stack size value,
8066 and the actual size needed for the current allocation request).
8067
8068 For certain targets, notably VxWorks 653,
8069 the secondary stack is allocated by carving off a fixed ratio chunk of the
8070 primary task stack. The -D option is used to define the
8071 size of the environment task's secondary stack.
8072
8073 @item ^-e^/ELABORATION_DEPENDENCIES^
8074 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8075 Output complete list of elaboration-order dependencies.
8076
8077 @item ^-E^/STORE_TRACEBACKS^
8078 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8079 Store tracebacks in exception occurrences when the target supports it.
8080 @ignore
8081 @c The following may get moved to an appendix
8082 This option is currently supported on the following targets:
8083 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8084 @end ignore
8085 See also the packages @code{GNAT.Traceback} and
8086 @code{GNAT.Traceback.Symbolic} for more information.
8087 @ifclear vms
8088 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8089 @command{gcc} option.
8090 @end ifclear
8091
8092 @item ^-F^/FORCE_ELABS_FLAGS^
8093 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8094 Force the checks of elaboration flags. @command{gnatbind} does not normally
8095 generate checks of elaboration flags for the main executable, except when
8096 a Stand-Alone Library is used. However, there are cases when this cannot be
8097 detected by gnatbind. An example is importing an interface of a Stand-Alone
8098 Library through a pragma Import and only specifying through a linker switch
8099 this Stand-Alone Library. This switch is used to guarantee that elaboration
8100 flag checks are generated.
8101
8102 @item ^-h^/HELP^
8103 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8104 Output usage (help) information
8105
8106 @item ^-H32^/32_MALLOC^
8107 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8108 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8109 For further details see @ref{Dynamic Allocation Control}.
8110
8111 @item ^-H64^/64_MALLOC^
8112 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8113 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8114 @cindex @code{__gnat_malloc}
8115 For further details see @ref{Dynamic Allocation Control}.
8116
8117 @item ^-I^/SEARCH^
8118 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8119 Specify directory to be searched for source and ALI files.
8120
8121 @item ^-I-^/NOCURRENT_DIRECTORY^
8122 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8123 Do not look for sources in the current directory where @code{gnatbind} was
8124 invoked, and do not look for ALI files in the directory containing the
8125 ALI file named in the @code{gnatbind} command line.
8126
8127 @item ^-l^/ORDER_OF_ELABORATION^
8128 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8129 Output chosen elaboration order.
8130
8131 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8132 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8133 Bind the units for library building. In this case the adainit and
8134 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8135 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8136 ^@var{xxx}final^@var{XXX}FINAL^.
8137 Implies ^-n^/NOCOMPILE^.
8138 @ifclear vms
8139 (@xref{GNAT and Libraries}, for more details.)
8140 @end ifclear
8141 @ifset vms
8142 On OpenVMS, these init and final procedures are exported in uppercase
8143 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8144 the init procedure will be "TOTOINIT" and the exported name of the final
8145 procedure will be "TOTOFINAL".
8146 @end ifset
8147
8148 @item ^-Mxyz^/RENAME_MAIN=xyz^
8149 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8150 Rename generated main program from main to xyz. This option is
8151 supported on cross environments only.
8152
8153 @item ^-m^/ERROR_LIMIT=^@var{n}
8154 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8155 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8156 in the range 1..999999. The default value if no switch is
8157 given is 9999. If the number of warnings reaches this limit, then a
8158 message is output and further warnings are suppressed, the bind
8159 continues in this case. If the number of errors reaches this
8160 limit, then a message is output and the bind is abandoned.
8161 A value of zero means that no limit is enforced. The equal
8162 sign is optional.
8163
8164 @ifset unw
8165 Furthermore, under Windows, the sources pointed to by the libraries path
8166 set in the registry are not searched for.
8167 @end ifset
8168
8169 @item ^-n^/NOMAIN^
8170 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8171 No main program.
8172
8173 @item -nostdinc
8174 @cindex @option{-nostdinc} (@command{gnatbind})
8175 Do not look for sources in the system default directory.
8176
8177 @item -nostdlib
8178 @cindex @option{-nostdlib} (@command{gnatbind})
8179 Do not look for library files in the system default directory.
8180
8181 @item --RTS=@var{rts-path}
8182 @cindex @option{--RTS} (@code{gnatbind})
8183 Specifies the default location of the runtime library. Same meaning as the
8184 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8185
8186 @item ^-o ^/OUTPUT=^@var{file}
8187 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8188 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8189 Note that if this option is used, then linking must be done manually,
8190 gnatlink cannot be used.
8191
8192 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8193 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8194 Output object list (to standard output or to the named file).
8195
8196 @item ^-p^/PESSIMISTIC_ELABORATION^
8197 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8198 Pessimistic (worst-case) elaboration order
8199
8200 @item ^-P^-P^
8201 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8202 Generate binder file suitable for CodePeer.
8203
8204 @item ^-R^-R^
8205 @cindex @option{^-R^-R^} (@command{gnatbind})
8206 Output closure source list.
8207
8208 @item ^-s^/READ_SOURCES=ALL^
8209 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8210 Require all source files to be present.
8211
8212 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8213 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8214 Specifies the value to be used when detecting uninitialized scalar
8215 objects with pragma Initialize_Scalars.
8216 The @var{xxx} ^string specified with the switch^option^ may be either
8217 @itemize @bullet
8218 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8219 @item ``@option{^lo^LOW^}'' for the lowest possible value
8220 @item ``@option{^hi^HIGH^}'' for the highest possible value
8221 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8222 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8223 @end itemize
8224
8225 In addition, you can specify @option{-Sev} to indicate that the value is
8226 to be set at run time. In this case, the program will look for an environment
8227 @cindex GNAT_INIT_SCALARS
8228 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8229 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8230 If no environment variable is found, or if it does not have a valid value,
8231 then the default is @option{in} (invalid values).
8232
8233 @ifclear vms
8234 @item -static
8235 @cindex @option{-static} (@code{gnatbind})
8236 Link against a static GNAT run time.
8237
8238 @item -shared
8239 @cindex @option{-shared} (@code{gnatbind})
8240 Link against a shared GNAT run time when available.
8241 @end ifclear
8242
8243 @item ^-t^/NOTIME_STAMP_CHECK^
8244 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8245 Tolerate time stamp and other consistency errors
8246
8247 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8248 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8249 Set the time slice value to @var{n} milliseconds. If the system supports
8250 the specification of a specific time slice value, then the indicated value
8251 is used. If the system does not support specific time slice values, but
8252 does support some general notion of round-robin scheduling, then any
8253 nonzero value will activate round-robin scheduling.
8254
8255 A value of zero is treated specially. It turns off time
8256 slicing, and in addition, indicates to the tasking run time that the
8257 semantics should match as closely as possible the Annex D
8258 requirements of the Ada RM, and in particular sets the default
8259 scheduling policy to @code{FIFO_Within_Priorities}.
8260
8261 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8262 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8263 Enable dynamic stack usage, with @var{n} results stored and displayed
8264 at program termination. A result is generated when a task
8265 terminates. Results that can't be stored are displayed on the fly, at
8266 task termination. This option is currently not supported on Itanium
8267 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8268
8269 @item ^-v^/REPORT_ERRORS=VERBOSE^
8270 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8271 Verbose mode. Write error messages, header, summary output to
8272 @file{stdout}.
8273
8274 @ifclear vms
8275 @item -w@var{x}
8276 @cindex @option{-w} (@code{gnatbind})
8277 Warning mode (@var{x}=s/e for suppress/treat as error)
8278 @end ifclear
8279
8280 @ifset vms
8281 @item /WARNINGS=NORMAL
8282 @cindex @option{/WARNINGS} (@code{gnatbind})
8283 Normal warnings mode. Warnings are issued but ignored
8284
8285 @item /WARNINGS=SUPPRESS
8286 @cindex @option{/WARNINGS} (@code{gnatbind})
8287 All warning messages are suppressed
8288
8289 @item /WARNINGS=ERROR
8290 @cindex @option{/WARNINGS} (@code{gnatbind})
8291 Warning messages are treated as fatal errors
8292 @end ifset
8293
8294 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8295 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8296 Override default wide character encoding for standard Text_IO files.
8297
8298 @item ^-x^/READ_SOURCES=NONE^
8299 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8300 Exclude source files (check object consistency only).
8301
8302 @ifset vms
8303 @item /READ_SOURCES=AVAILABLE
8304 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8305 Default mode, in which sources are checked for consistency only if
8306 they are available.
8307 @end ifset
8308
8309 @item ^-y^/ENABLE_LEAP_SECONDS^
8310 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8311 Enable leap seconds support in @code{Ada.Calendar} and its children.
8312
8313 @item ^-z^/ZERO_MAIN^
8314 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8315 No main subprogram.
8316 @end table
8317
8318 @ifclear vms
8319 @noindent
8320 You may obtain this listing of switches by running @code{gnatbind} with
8321 no arguments.
8322 @end ifclear
8323
8324 @node Consistency-Checking Modes
8325 @subsection Consistency-Checking Modes
8326
8327 @noindent
8328 As described earlier, by default @code{gnatbind} checks
8329 that object files are consistent with one another and are consistent
8330 with any source files it can locate. The following switches control binder
8331 access to sources.
8332
8333 @table @option
8334 @c !sort!
8335 @item ^-s^/READ_SOURCES=ALL^
8336 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8337 Require source files to be present. In this mode, the binder must be
8338 able to locate all source files that are referenced, in order to check
8339 their consistency. In normal mode, if a source file cannot be located it
8340 is simply ignored. If you specify this switch, a missing source
8341 file is an error.
8342
8343 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8344 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8345 Override default wide character encoding for standard Text_IO files.
8346 Normally the default wide character encoding method used for standard
8347 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8348 the main source input (see description of switch
8349 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8350 use of this switch for the binder (which has the same set of
8351 possible arguments) overrides this default as specified.
8352
8353 @item ^-x^/READ_SOURCES=NONE^
8354 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8355 Exclude source files. In this mode, the binder only checks that ALI
8356 files are consistent with one another. Source files are not accessed.
8357 The binder runs faster in this mode, and there is still a guarantee that
8358 the resulting program is self-consistent.
8359 If a source file has been edited since it was last compiled, and you
8360 specify this switch, the binder will not detect that the object
8361 file is out of date with respect to the source file. Note that this is the
8362 mode that is automatically used by @command{gnatmake} because in this
8363 case the checking against sources has already been performed by
8364 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8365
8366 @ifset vms
8367 @item /READ_SOURCES=AVAILABLE
8368 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8369 This is the default mode in which source files are checked if they are
8370 available, and ignored if they are not available.
8371 @end ifset
8372 @end table
8373
8374 @node Binder Error Message Control
8375 @subsection Binder Error Message Control
8376
8377 @noindent
8378 The following switches provide control over the generation of error
8379 messages from the binder:
8380
8381 @table @option
8382 @c !sort!
8383 @item ^-v^/REPORT_ERRORS=VERBOSE^
8384 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8385 Verbose mode. In the normal mode, brief error messages are generated to
8386 @file{stderr}. If this switch is present, a header is written
8387 to @file{stdout} and any error messages are directed to @file{stdout}.
8388 All that is written to @file{stderr} is a brief summary message.
8389
8390 @item ^-b^/REPORT_ERRORS=BRIEF^
8391 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8392 Generate brief error messages to @file{stderr} even if verbose mode is
8393 specified. This is relevant only when used with the
8394 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8395
8396 @ifclear vms
8397 @item -m@var{n}
8398 @cindex @option{-m} (@code{gnatbind})
8399 Limits the number of error messages to @var{n}, a decimal integer in the
8400 range 1-999. The binder terminates immediately if this limit is reached.
8401
8402 @item -M@var{xxx}
8403 @cindex @option{-M} (@code{gnatbind})
8404 Renames the generated main program from @code{main} to @code{xxx}.
8405 This is useful in the case of some cross-building environments, where
8406 the actual main program is separate from the one generated
8407 by @code{gnatbind}.
8408 @end ifclear
8409
8410 @item ^-ws^/WARNINGS=SUPPRESS^
8411 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8412 @cindex Warnings
8413 Suppress all warning messages.
8414
8415 @item ^-we^/WARNINGS=ERROR^
8416 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8417 Treat any warning messages as fatal errors.
8418
8419 @ifset vms
8420 @item /WARNINGS=NORMAL
8421 Standard mode with warnings generated, but warnings do not get treated
8422 as errors.
8423 @end ifset
8424
8425 @item ^-t^/NOTIME_STAMP_CHECK^
8426 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8427 @cindex Time stamp checks, in binder
8428 @cindex Binder consistency checks
8429 @cindex Consistency checks, in binder
8430 The binder performs a number of consistency checks including:
8431
8432 @itemize @bullet
8433 @item
8434 Check that time stamps of a given source unit are consistent
8435 @item
8436 Check that checksums of a given source unit are consistent
8437 @item
8438 Check that consistent versions of @code{GNAT} were used for compilation
8439 @item
8440 Check consistency of configuration pragmas as required
8441 @end itemize
8442
8443 @noindent
8444 Normally failure of such checks, in accordance with the consistency
8445 requirements of the Ada Reference Manual, causes error messages to be
8446 generated which abort the binder and prevent the output of a binder
8447 file and subsequent link to obtain an executable.
8448
8449 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8450 into warnings, so that
8451 binding and linking can continue to completion even in the presence of such
8452 errors. The result may be a failed link (due to missing symbols), or a
8453 non-functional executable which has undefined semantics.
8454 @emph{This means that
8455 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8456 with extreme care.}
8457 @end table
8458
8459 @node Elaboration Control
8460 @subsection Elaboration Control
8461
8462 @noindent
8463 The following switches provide additional control over the elaboration
8464 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8465
8466 @table @option
8467 @item ^-p^/PESSIMISTIC_ELABORATION^
8468 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8469 Normally the binder attempts to choose an elaboration order that is
8470 likely to minimize the likelihood of an elaboration order error resulting
8471 in raising a @code{Program_Error} exception. This switch reverses the
8472 action of the binder, and requests that it deliberately choose an order
8473 that is likely to maximize the likelihood of an elaboration error.
8474 This is useful in ensuring portability and avoiding dependence on
8475 accidental fortuitous elaboration ordering.
8476
8477 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8478 switch if dynamic
8479 elaboration checking is used (@option{-gnatE} switch used for compilation).
8480 This is because in the default static elaboration mode, all necessary
8481 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8482 These implicit pragmas are still respected by the binder in
8483 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8484 safe elaboration order is assured.
8485
8486 Note that @option{^-p^/PESSIMISTIC_ELABORATION^} is not intended for
8487 production use; it is more for debugging/experimental use.
8488 @end table
8489
8490 @node Output Control
8491 @subsection Output Control
8492
8493 @noindent
8494 The following switches allow additional control over the output
8495 generated by the binder.
8496
8497 @table @option
8498 @c !sort!
8499
8500 @item ^-c^/NOOUTPUT^
8501 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8502 Check only. Do not generate the binder output file. In this mode the
8503 binder performs all error checks but does not generate an output file.
8504
8505 @item ^-e^/ELABORATION_DEPENDENCIES^
8506 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8507 Output complete list of elaboration-order dependencies, showing the
8508 reason for each dependency. This output can be rather extensive but may
8509 be useful in diagnosing problems with elaboration order. The output is
8510 written to @file{stdout}.
8511
8512 @item ^-h^/HELP^
8513 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8514 Output usage information. The output is written to @file{stdout}.
8515
8516 @item ^-K^/LINKER_OPTION_LIST^
8517 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8518 Output linker options to @file{stdout}. Includes library search paths,
8519 contents of pragmas Ident and Linker_Options, and libraries added
8520 by @code{gnatbind}.
8521
8522 @item ^-l^/ORDER_OF_ELABORATION^
8523 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8524 Output chosen elaboration order. The output is written to @file{stdout}.
8525
8526 @item ^-O^/OBJECT_LIST^
8527 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8528 Output full names of all the object files that must be linked to provide
8529 the Ada component of the program. The output is written to @file{stdout}.
8530 This list includes the files explicitly supplied and referenced by the user
8531 as well as implicitly referenced run-time unit files. The latter are
8532 omitted if the corresponding units reside in shared libraries. The
8533 directory names for the run-time units depend on the system configuration.
8534
8535 @item ^-o ^/OUTPUT=^@var{file}
8536 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8537 Set name of output file to @var{file} instead of the normal
8538 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8539 binder generated body filename.
8540 Note that if this option is used, then linking must be done manually.
8541 It is not possible to use gnatlink in this case, since it cannot locate
8542 the binder file.
8543
8544 @item ^-r^/RESTRICTION_LIST^
8545 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8546 Generate list of @code{pragma Restrictions} that could be applied to
8547 the current unit. This is useful for code audit purposes, and also may
8548 be used to improve code generation in some cases.
8549
8550 @end table
8551
8552 @node Dynamic Allocation Control
8553 @subsection Dynamic Allocation Control
8554
8555 @noindent
8556 The heap control switches -- @option{-H32} and @option{-H64} --
8557 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8558 They only affect compiler-generated allocations via @code{__gnat_malloc};
8559 explicit calls to @code{malloc} and related functions from the C
8560 run-time library are unaffected.
8561
8562 @table @option
8563 @item -H32
8564 Allocate memory on 32-bit heap
8565
8566 @item -H64
8567 Allocate memory on 64-bit heap. This is the default
8568 unless explicitly overridden by a @code{'Size} clause on the access type.
8569 @end table
8570
8571 @ifset vms
8572 @noindent
8573 See also @ref{Access types and 32/64-bit allocation}.
8574 @end ifset
8575 @ifclear vms
8576 @noindent
8577 These switches are only effective on VMS platforms.
8578 @end ifclear
8579
8580
8581 @node Binding with Non-Ada Main Programs
8582 @subsection Binding with Non-Ada Main Programs
8583
8584 @noindent
8585 In our description so far we have assumed that the main
8586 program is in Ada, and that the task of the binder is to generate a
8587 corresponding function @code{main} that invokes this Ada main
8588 program. GNAT also supports the building of executable programs where
8589 the main program is not in Ada, but some of the called routines are
8590 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8591 The following switch is used in this situation:
8592
8593 @table @option
8594 @item ^-n^/NOMAIN^
8595 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8596 No main program. The main program is not in Ada.
8597 @end table
8598
8599 @noindent
8600 In this case, most of the functions of the binder are still required,
8601 but instead of generating a main program, the binder generates a file
8602 containing the following callable routines:
8603
8604 @table @code
8605 @item adainit
8606 @findex adainit
8607 You must call this routine to initialize the Ada part of the program by
8608 calling the necessary elaboration routines. A call to @code{adainit} is
8609 required before the first call to an Ada subprogram.
8610
8611 Note that it is assumed that the basic execution environment must be setup
8612 to be appropriate for Ada execution at the point where the first Ada
8613 subprogram is called. In particular, if the Ada code will do any
8614 floating-point operations, then the FPU must be setup in an appropriate
8615 manner. For the case of the x86, for example, full precision mode is
8616 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8617 that the FPU is in the right state.
8618
8619 @item adafinal
8620 @findex adafinal
8621 You must call this routine to perform any library-level finalization
8622 required by the Ada subprograms. A call to @code{adafinal} is required
8623 after the last call to an Ada subprogram, and before the program
8624 terminates.
8625 @end table
8626
8627 @noindent
8628 If the @option{^-n^/NOMAIN^} switch
8629 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8630 @cindex Binder, multiple input files
8631 is given, more than one ALI file may appear on
8632 the command line for @code{gnatbind}. The normal @dfn{closure}
8633 calculation is performed for each of the specified units. Calculating
8634 the closure means finding out the set of units involved by tracing
8635 @code{with} references. The reason it is necessary to be able to
8636 specify more than one ALI file is that a given program may invoke two or
8637 more quite separate groups of Ada units.
8638
8639 The binder takes the name of its output file from the last specified ALI
8640 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8641 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8642 The output is an Ada unit in source form that can be compiled with GNAT.
8643 This compilation occurs automatically as part of the @command{gnatlink}
8644 processing.
8645
8646 Currently the GNAT run time requires a FPU using 80 bits mode
8647 precision. Under targets where this is not the default it is required to
8648 call GNAT.Float_Control.Reset before using floating point numbers (this
8649 include float computation, float input and output) in the Ada code. A
8650 side effect is that this could be the wrong mode for the foreign code
8651 where floating point computation could be broken after this call.
8652
8653 @node Binding Programs with No Main Subprogram
8654 @subsection Binding Programs with No Main Subprogram
8655
8656 @noindent
8657 It is possible to have an Ada program which does not have a main
8658 subprogram. This program will call the elaboration routines of all the
8659 packages, then the finalization routines.
8660
8661 The following switch is used to bind programs organized in this manner:
8662
8663 @table @option
8664 @item ^-z^/ZERO_MAIN^
8665 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8666 Normally the binder checks that the unit name given on the command line
8667 corresponds to a suitable main subprogram. When this switch is used,
8668 a list of ALI files can be given, and the execution of the program
8669 consists of elaboration of these units in an appropriate order. Note
8670 that the default wide character encoding method for standard Text_IO
8671 files is always set to Brackets if this switch is set (you can use
8672 the binder switch
8673 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8674 @end table
8675
8676 @node Command-Line Access
8677 @section Command-Line Access
8678
8679 @noindent
8680 The package @code{Ada.Command_Line} provides access to the command-line
8681 arguments and program name. In order for this interface to operate
8682 correctly, the two variables
8683
8684 @smallexample
8685 @group
8686 int gnat_argc;
8687 char **gnat_argv;
8688 @end group
8689 @end smallexample
8690
8691 @noindent
8692 @findex gnat_argv
8693 @findex gnat_argc
8694 are declared in one of the GNAT library routines. These variables must
8695 be set from the actual @code{argc} and @code{argv} values passed to the
8696 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8697 generates the C main program to automatically set these variables.
8698 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8699 set these variables. If they are not set, the procedures in
8700 @code{Ada.Command_Line} will not be available, and any attempt to use
8701 them will raise @code{Constraint_Error}. If command line access is
8702 required, your main program must set @code{gnat_argc} and
8703 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
8704 it.
8705
8706 @node Search Paths for gnatbind
8707 @section Search Paths for @code{gnatbind}
8708
8709 @noindent
8710 The binder takes the name of an ALI file as its argument and needs to
8711 locate source files as well as other ALI files to verify object consistency.
8712
8713 For source files, it follows exactly the same search rules as @command{gcc}
8714 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
8715 directories searched are:
8716
8717 @enumerate
8718 @item
8719 The directory containing the ALI file named in the command line, unless
8720 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
8721
8722 @item
8723 All directories specified by @option{^-I^/SEARCH^}
8724 switches on the @code{gnatbind}
8725 command line, in the order given.
8726
8727 @item
8728 @findex ADA_PRJ_OBJECTS_FILE
8729 Each of the directories listed in the text file whose name is given
8730 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
8731
8732 @noindent
8733 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
8734 driver when project files are used. It should not normally be set
8735 by other means.
8736
8737 @item
8738 @findex ADA_OBJECTS_PATH
8739 Each of the directories listed in the value of the
8740 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
8741 @ifset unw
8742 Construct this value
8743 exactly as the @env{PATH} environment variable: a list of directory
8744 names separated by colons (semicolons when working with the NT version
8745 of GNAT).
8746 @end ifset
8747 @ifset vms
8748 Normally, define this value as a logical name containing a comma separated
8749 list of directory names.
8750
8751 This variable can also be defined by means of an environment string
8752 (an argument to the HP C exec* set of functions).
8753
8754 Logical Name:
8755 @smallexample
8756 DEFINE ANOTHER_PATH FOO:[BAG]
8757 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8758 @end smallexample
8759
8760 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8761 first, followed by the standard Ada
8762 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
8763 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8764 (Text_IO, Sequential_IO, etc)
8765 instead of the standard Ada packages. Thus, in order to get the standard Ada
8766 packages by default, ADA_OBJECTS_PATH must be redefined.
8767 @end ifset
8768
8769 @item
8770 The content of the @file{ada_object_path} file which is part of the GNAT
8771 installation tree and is used to store standard libraries such as the
8772 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
8773 specified.
8774 @ifclear vms
8775 @ref{Installing a library}
8776 @end ifclear
8777 @end enumerate
8778
8779 @noindent
8780 In the binder the switch @option{^-I^/SEARCH^}
8781 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8782 is used to specify both source and
8783 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
8784 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8785 instead if you want to specify
8786 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
8787 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
8788 if you want to specify library paths
8789 only. This means that for the binder
8790 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
8791 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
8792 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
8793 The binder generates the bind file (a C language source file) in the
8794 current working directory.
8795
8796 @findex Ada
8797 @findex System
8798 @findex Interfaces
8799 @findex GNAT
8800 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8801 children make up the GNAT Run-Time Library, together with the package
8802 GNAT and its children, which contain a set of useful additional
8803 library functions provided by GNAT. The sources for these units are
8804 needed by the compiler and are kept together in one directory. The ALI
8805 files and object files generated by compiling the RTL are needed by the
8806 binder and the linker and are kept together in one directory, typically
8807 different from the directory containing the sources. In a normal
8808 installation, you need not specify these directory names when compiling
8809 or binding. Either the environment variables or the built-in defaults
8810 cause these files to be found.
8811
8812 Besides simplifying access to the RTL, a major use of search paths is
8813 in compiling sources from multiple directories. This can make
8814 development environments much more flexible.
8815
8816 @node Examples of gnatbind Usage
8817 @section Examples of @code{gnatbind} Usage
8818
8819 @noindent
8820 This section contains a number of examples of using the GNAT binding
8821 utility @code{gnatbind}.
8822
8823 @table @code
8824 @item gnatbind hello
8825 The main program @code{Hello} (source program in @file{hello.adb}) is
8826 bound using the standard switch settings. The generated main program is
8827 @file{b~hello.adb}. This is the normal, default use of the binder.
8828
8829 @ifclear vms
8830 @item gnatbind hello -o mainprog.adb
8831 @end ifclear
8832 @ifset vms
8833 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
8834 @end ifset
8835 The main program @code{Hello} (source program in @file{hello.adb}) is
8836 bound using the standard switch settings. The generated main program is
8837 @file{mainprog.adb} with the associated spec in
8838 @file{mainprog.ads}. Note that you must specify the body here not the
8839 spec. Note that if this option is used, then linking must be done manually,
8840 since gnatlink will not be able to find the generated file.
8841 @end table
8842
8843 @c ------------------------------------
8844 @node Linking with gnatlink
8845 @chapter Linking with @command{gnatlink}
8846 @c ------------------------------------
8847 @findex gnatlink
8848
8849 @noindent
8850 This chapter discusses @command{gnatlink}, a tool that links
8851 an Ada program and builds an executable file. This utility
8852 invokes the system linker ^(via the @command{gcc} command)^^
8853 with a correct list of object files and library references.
8854 @command{gnatlink} automatically determines the list of files and
8855 references for the Ada part of a program. It uses the binder file
8856 generated by the @command{gnatbind} to determine this list.
8857
8858 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
8859 driver (see @ref{The GNAT Driver and Project Files}).
8860
8861 @menu
8862 * Running gnatlink::
8863 * Switches for gnatlink::
8864 @end menu
8865
8866 @node Running gnatlink
8867 @section Running @command{gnatlink}
8868
8869 @noindent
8870 The form of the @command{gnatlink} command is
8871
8872 @smallexample
8873 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
8874 @c @ovar{non-Ada objects} @ovar{linker options}
8875 @c Expanding @ovar macro inline (explanation in macro def comments)
8876 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
8877 @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
8878
8879 @end smallexample
8880
8881 @noindent
8882 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
8883 non-Ada objects
8884 or linker options) may be in any order, provided that no non-Ada object may
8885 be mistaken for a main @file{ALI} file.
8886 Any file name @file{F} without the @file{.ali}
8887 extension will be taken as the main @file{ALI} file if a file exists
8888 whose name is the concatenation of @file{F} and @file{.ali}.
8889
8890 @noindent
8891 @file{@var{mainprog}.ali} references the ALI file of the main program.
8892 The @file{.ali} extension of this file can be omitted. From this
8893 reference, @command{gnatlink} locates the corresponding binder file
8894 @file{b~@var{mainprog}.adb} and, using the information in this file along
8895 with the list of non-Ada objects and linker options, constructs a
8896 linker command file to create the executable.
8897
8898 The arguments other than the @command{gnatlink} switches and the main
8899 @file{ALI} file are passed to the linker uninterpreted.
8900 They typically include the names of
8901 object files for units written in other languages than Ada and any library
8902 references required to resolve references in any of these foreign language
8903 units, or in @code{Import} pragmas in any Ada units.
8904
8905 @var{linker options} is an optional list of linker specific
8906 switches.
8907 The default linker called by gnatlink is @command{gcc} which in
8908 turn calls the appropriate system linker.
8909
8910 One useful option for the linker is @option{-s}: it reduces the size of the
8911 executable by removing all symbol table and relocation information from the
8912 executable.
8913
8914 Standard options for the linker such as @option{-lmy_lib} or
8915 @option{-Ldir} can be added as is.
8916 For options that are not recognized by
8917 @command{gcc} as linker options, use the @command{gcc} switches
8918 @option{-Xlinker} or @option{-Wl,}.
8919
8920 Refer to the GCC documentation for
8921 details.
8922
8923 Here is an example showing how to generate a linker map:
8924
8925 @smallexample
8926 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
8927 @end smallexample
8928
8929 Using @var{linker options} it is possible to set the program stack and
8930 heap size.
8931 @ifset unw
8932 See @ref{Setting Stack Size from gnatlink} and
8933 @ref{Setting Heap Size from gnatlink}.
8934 @end ifset
8935
8936 @command{gnatlink} determines the list of objects required by the Ada
8937 program and prepends them to the list of objects passed to the linker.
8938 @command{gnatlink} also gathers any arguments set by the use of
8939 @code{pragma Linker_Options} and adds them to the list of arguments
8940 presented to the linker.
8941
8942 @ifset vms
8943 @command{gnatlink} accepts the following types of extra files on the command
8944 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
8945 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
8946 handled according to their extension.
8947 @end ifset
8948
8949 @node Switches for gnatlink
8950 @section Switches for @command{gnatlink}
8951
8952 @noindent
8953 The following switches are available with the @command{gnatlink} utility:
8954
8955 @table @option
8956 @c !sort!
8957
8958 @item --version
8959 @cindex @option{--version} @command{gnatlink}
8960 Display Copyright and version, then exit disregarding all other options.
8961
8962 @item --help
8963 @cindex @option{--help} @command{gnatlink}
8964 If @option{--version} was not used, display usage, then exit disregarding
8965 all other options.
8966
8967 @item ^-f^/FORCE_OBJECT_FILE_LIST^
8968 @cindex Command line length
8969 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
8970 On some targets, the command line length is limited, and @command{gnatlink}
8971 will generate a separate file for the linker if the list of object files
8972 is too long.
8973 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
8974 to be generated even if
8975 the limit is not exceeded. This is useful in some cases to deal with
8976 special situations where the command line length is exceeded.
8977
8978 @item ^-g^/DEBUG^
8979 @cindex Debugging information, including
8980 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
8981 The option to include debugging information causes the Ada bind file (in
8982 other words, @file{b~@var{mainprog}.adb}) to be compiled with
8983 @option{^-g^/DEBUG^}.
8984 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
8985 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
8986 Without @option{^-g^/DEBUG^}, the binder removes these files by
8987 default. The same procedure apply if a C bind file was generated using
8988 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
8989 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
8990
8991 @item ^-n^/NOCOMPILE^
8992 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
8993 Do not compile the file generated by the binder. This may be used when
8994 a link is rerun with different options, but there is no need to recompile
8995 the binder file.
8996
8997 @item ^-v^/VERBOSE^
8998 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
8999 Causes additional information to be output, including a full list of the
9000 included object files. This switch option is most useful when you want
9001 to see what set of object files are being used in the link step.
9002
9003 @item ^-v -v^/VERBOSE/VERBOSE^
9004 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9005 Very verbose mode. Requests that the compiler operate in verbose mode when
9006 it compiles the binder file, and that the system linker run in verbose mode.
9007
9008 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9009 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9010 @var{exec-name} specifies an alternate name for the generated
9011 executable program. If this switch is omitted, the executable has the same
9012 name as the main unit. For example, @code{gnatlink try.ali} creates
9013 an executable called @file{^try^TRY.EXE^}.
9014
9015 @ifclear vms
9016 @item -b @var{target}
9017 @cindex @option{-b} (@command{gnatlink})
9018 Compile your program to run on @var{target}, which is the name of a
9019 system configuration. You must have a GNAT cross-compiler built if
9020 @var{target} is not the same as your host system.
9021
9022 @item -B@var{dir}
9023 @cindex @option{-B} (@command{gnatlink})
9024 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9025 from @var{dir} instead of the default location. Only use this switch
9026 when multiple versions of the GNAT compiler are available.
9027 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9028 for further details. You would normally use the @option{-b} or
9029 @option{-V} switch instead.
9030
9031 @item -M
9032 When linking an executable, create a map file. The name of the map file
9033 has the same name as the executable with extension ".map".
9034
9035 @item -M=mapfile
9036 When linking an executable, create a map file. The name of the map file is
9037 "mapfile".
9038
9039 @item --GCC=@var{compiler_name}
9040 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9041 Program used for compiling the binder file. The default is
9042 @command{gcc}. You need to use quotes around @var{compiler_name} if
9043 @code{compiler_name} contains spaces or other separator characters.
9044 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9045 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9046 inserted after your command name. Thus in the above example the compiler
9047 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9048 A limitation of this syntax is that the name and path name of the executable
9049 itself must not include any embedded spaces. If the compiler executable is
9050 different from the default one (gcc or <prefix>-gcc), then the back-end
9051 switches in the ALI file are not used to compile the binder generated source.
9052 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9053 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9054 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9055 is taken into account. However, all the additional switches are also taken
9056 into account. Thus,
9057 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9058 @option{--GCC="bar -x -y -z -t"}.
9059
9060 @item --LINK=@var{name}
9061 @cindex @option{--LINK=} (@command{gnatlink})
9062 @var{name} is the name of the linker to be invoked. This is especially
9063 useful in mixed language programs since languages such as C++ require
9064 their own linker to be used. When this switch is omitted, the default
9065 name for the linker is @command{gcc}. When this switch is used, the
9066 specified linker is called instead of @command{gcc} with exactly the same
9067 parameters that would have been passed to @command{gcc} so if the desired
9068 linker requires different parameters it is necessary to use a wrapper
9069 script that massages the parameters before invoking the real linker. It
9070 may be useful to control the exact invocation by using the verbose
9071 switch.
9072
9073 @end ifclear
9074
9075 @ifset vms
9076 @item /DEBUG=TRACEBACK
9077 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9078 This qualifier causes sufficient information to be included in the
9079 executable file to allow a traceback, but does not include the full
9080 symbol information needed by the debugger.
9081
9082 @item /IDENTIFICATION="<string>"
9083 @code{"<string>"} specifies the string to be stored in the image file
9084 identification field in the image header.
9085 It overrides any pragma @code{Ident} specified string.
9086
9087 @item /NOINHIBIT-EXEC
9088 Generate the executable file even if there are linker warnings.
9089
9090 @item /NOSTART_FILES
9091 Don't link in the object file containing the ``main'' transfer address.
9092 Used when linking with a foreign language main program compiled with an
9093 HP compiler.
9094
9095 @item /STATIC
9096 Prefer linking with object libraries over sharable images, even without
9097 /DEBUG.
9098 @end ifset
9099
9100 @end table
9101
9102 @node The GNAT Make Program gnatmake
9103 @chapter The GNAT Make Program @command{gnatmake}
9104 @findex gnatmake
9105
9106 @menu
9107 * Running gnatmake::
9108 * Switches for gnatmake::
9109 * Mode Switches for gnatmake::
9110 * Notes on the Command Line::
9111 * How gnatmake Works::
9112 * Examples of gnatmake Usage::
9113 @end menu
9114 @noindent
9115 A typical development cycle when working on an Ada program consists of
9116 the following steps:
9117
9118 @enumerate
9119 @item
9120 Edit some sources to fix bugs.
9121
9122 @item
9123 Add enhancements.
9124
9125 @item
9126 Compile all sources affected.
9127
9128 @item
9129 Rebind and relink.
9130
9131 @item
9132 Test.
9133 @end enumerate
9134
9135 @noindent
9136 The third step can be tricky, because not only do the modified files
9137 @cindex Dependency rules
9138 have to be compiled, but any files depending on these files must also be
9139 recompiled. The dependency rules in Ada can be quite complex, especially
9140 in the presence of overloading, @code{use} clauses, generics and inlined
9141 subprograms.
9142
9143 @command{gnatmake} automatically takes care of the third and fourth steps
9144 of this process. It determines which sources need to be compiled,
9145 compiles them, and binds and links the resulting object files.
9146
9147 Unlike some other Ada make programs, the dependencies are always
9148 accurately recomputed from the new sources. The source based approach of
9149 the GNAT compilation model makes this possible. This means that if
9150 changes to the source program cause corresponding changes in
9151 dependencies, they will always be tracked exactly correctly by
9152 @command{gnatmake}.
9153
9154 @node Running gnatmake
9155 @section Running @command{gnatmake}
9156
9157 @noindent
9158 The usual form of the @command{gnatmake} command is
9159
9160 @smallexample
9161 @c $ gnatmake @ovar{switches} @var{file_name}
9162 @c @ovar{file_names} @ovar{mode_switches}
9163 @c Expanding @ovar macro inline (explanation in macro def comments)
9164 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9165 @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9166 @end smallexample
9167
9168 @noindent
9169 The only required argument is one @var{file_name}, which specifies
9170 a compilation unit that is a main program. Several @var{file_names} can be
9171 specified: this will result in several executables being built.
9172 If @code{switches} are present, they can be placed before the first
9173 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9174 If @var{mode_switches} are present, they must always be placed after
9175 the last @var{file_name} and all @code{switches}.
9176
9177 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9178 extension may be omitted from the @var{file_name} arguments. However, if
9179 you are using non-standard extensions, then it is required that the
9180 extension be given. A relative or absolute directory path can be
9181 specified in a @var{file_name}, in which case, the input source file will
9182 be searched for in the specified directory only. Otherwise, the input
9183 source file will first be searched in the directory where
9184 @command{gnatmake} was invoked and if it is not found, it will be search on
9185 the source path of the compiler as described in
9186 @ref{Search Paths and the Run-Time Library (RTL)}.
9187
9188 All @command{gnatmake} output (except when you specify
9189 @option{^-M^/DEPENDENCIES_LIST^}) is to
9190 @file{stderr}. The output produced by the
9191 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9192 @file{stdout}.
9193
9194 @node Switches for gnatmake
9195 @section Switches for @command{gnatmake}
9196
9197 @noindent
9198 You may specify any of the following switches to @command{gnatmake}:
9199
9200 @table @option
9201 @c !sort!
9202
9203 @item --version
9204 @cindex @option{--version} @command{gnatmake}
9205 Display Copyright and version, then exit disregarding all other options.
9206
9207 @item --help
9208 @cindex @option{--help} @command{gnatmake}
9209 If @option{--version} was not used, display usage, then exit disregarding
9210 all other options.
9211
9212 @ifclear vms
9213 @item --GCC=@var{compiler_name}
9214 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9215 Program used for compiling. The default is `@command{gcc}'. You need to use
9216 quotes around @var{compiler_name} if @code{compiler_name} contains
9217 spaces or other separator characters. As an example @option{--GCC="foo -x
9218 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9219 compiler. A limitation of this syntax is that the name and path name of
9220 the executable itself must not include any embedded spaces. Note that
9221 switch @option{-c} is always inserted after your command name. Thus in the
9222 above example the compiler command that will be used by @command{gnatmake}
9223 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9224 used, only the last @var{compiler_name} is taken into account. However,
9225 all the additional switches are also taken into account. Thus,
9226 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9227 @option{--GCC="bar -x -y -z -t"}.
9228
9229 @item --GNATBIND=@var{binder_name}
9230 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9231 Program used for binding. The default is `@code{gnatbind}'. You need to
9232 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9233 or other separator characters. As an example @option{--GNATBIND="bar -x
9234 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9235 binder. Binder switches that are normally appended by @command{gnatmake}
9236 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9237 A limitation of this syntax is that the name and path name of the executable
9238 itself must not include any embedded spaces.
9239
9240 @item --GNATLINK=@var{linker_name}
9241 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9242 Program used for linking. The default is `@command{gnatlink}'. You need to
9243 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9244 or other separator characters. As an example @option{--GNATLINK="lan -x
9245 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9246 linker. Linker switches that are normally appended by @command{gnatmake} to
9247 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9248 A limitation of this syntax is that the name and path name of the executable
9249 itself must not include any embedded spaces.
9250
9251 @end ifclear
9252
9253 @item ^--subdirs^/SUBDIRS^=subdir
9254 Actual object directory of each project file is the subdirectory subdir of the
9255 object directory specified or defaulted in the project file.
9256
9257 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9258 Disallow simultaneous compilations in the same object directory when
9259 project files are used.
9260
9261 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9262 By default, shared library projects are not allowed to import static library
9263 projects. When this switch is used on the command line, this restriction is
9264 relaxed.
9265
9266 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9267 Specify a source info file. This switch is active only when project files
9268 are used. If the source info file is specified as a relative path, then it is
9269 relative to the object directory of the main project. If the source info file
9270 does not exist, then after the Project Manager has successfully parsed and
9271 processed the project files and found the sources, it creates the source info
9272 file. If the source info file already exists and can be read successfully,
9273 then the Project Manager will get all the needed information about the sources
9274 from the source info file and will not look for them. This reduces the time
9275 to process the project files, especially when looking for sources that take a
9276 long time. If the source info file exists but cannot be parsed successfully,
9277 the Project Manager will attempt to recreate it. If the Project Manager fails
9278 to create the source info file, a message is issued, but gnatmake does not
9279 fail. @command{gnatmake} "trusts" the source info file. This means that
9280 if the source files have changed (addition, deletion, moving to a different
9281 source directory), then the source info file need to be deleted and recreated.
9282
9283 @ifclear vms
9284 @item --create-map-file
9285 When linking an executable, create a map file. The name of the map file
9286 has the same name as the executable with extension ".map".
9287
9288 @item --create-map-file=mapfile
9289 When linking an executable, create a map file. The name of the map file is
9290 "mapfile".
9291
9292 @end ifclear
9293
9294 @item ^-a^/ALL_FILES^
9295 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9296 Consider all files in the make process, even the GNAT internal system
9297 files (for example, the predefined Ada library files), as well as any
9298 locked files. Locked files are files whose ALI file is write-protected.
9299 By default,
9300 @command{gnatmake} does not check these files,
9301 because the assumption is that the GNAT internal files are properly up
9302 to date, and also that any write protected ALI files have been properly
9303 installed. Note that if there is an installation problem, such that one
9304 of these files is not up to date, it will be properly caught by the
9305 binder.
9306 You may have to specify this switch if you are working on GNAT
9307 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9308 in conjunction with @option{^-f^/FORCE_COMPILE^}
9309 if you need to recompile an entire application,
9310 including run-time files, using special configuration pragmas,
9311 such as a @code{Normalize_Scalars} pragma.
9312
9313 By default
9314 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9315 internal files with
9316 @ifclear vms
9317 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9318 @end ifclear
9319 @ifset vms
9320 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9321 @end ifset
9322
9323 @item ^-b^/ACTIONS=BIND^
9324 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9325 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9326 compilation and binding, but no link.
9327 Can be combined with @option{^-l^/ACTIONS=LINK^}
9328 to do binding and linking. When not combined with
9329 @option{^-c^/ACTIONS=COMPILE^}
9330 all the units in the closure of the main program must have been previously
9331 compiled and must be up to date. The root unit specified by @var{file_name}
9332 may be given without extension, with the source extension or, if no GNAT
9333 Project File is specified, with the ALI file extension.
9334
9335 @item ^-c^/ACTIONS=COMPILE^
9336 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9337 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9338 is also specified. Do not perform linking, except if both
9339 @option{^-b^/ACTIONS=BIND^} and
9340 @option{^-l^/ACTIONS=LINK^} are also specified.
9341 If the root unit specified by @var{file_name} is not a main unit, this is the
9342 default. Otherwise @command{gnatmake} will attempt binding and linking
9343 unless all objects are up to date and the executable is more recent than
9344 the objects.
9345
9346 @item ^-C^/MAPPING^
9347 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9348 Use a temporary mapping file. A mapping file is a way to communicate
9349 to the compiler two mappings: from unit names to file names (without
9350 any directory information) and from file names to path names (with
9351 full directory information). A mapping file can make the compiler's
9352 file searches faster, especially if there are many source directories,
9353 or the sources are read over a slow network connection. If
9354 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9355 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9356 is initially populated based on the project file. If
9357 @option{^-C^/MAPPING^} is used without
9358 @option{^-P^/PROJECT_FILE^},
9359 the mapping file is initially empty. Each invocation of the compiler
9360 will add any newly accessed sources to the mapping file.
9361
9362 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9363 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9364 Use a specific mapping file. The file, specified as a path name (absolute or
9365 relative) by this switch, should already exist, otherwise the switch is
9366 ineffective. The specified mapping file will be communicated to the compiler.
9367 This switch is not compatible with a project file
9368 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9369 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9370
9371 @item ^-d^/DISPLAY_PROGRESS^
9372 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9373 Display progress for each source, up to date or not, as a single line
9374
9375 @smallexample
9376 completed x out of y (zz%)
9377 @end smallexample
9378
9379 If the file needs to be compiled this is displayed after the invocation of
9380 the compiler. These lines are displayed even in quiet output mode.
9381
9382 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9383 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9384 Put all object files and ALI file in directory @var{dir}.
9385 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9386 and ALI files go in the current working directory.
9387
9388 This switch cannot be used when using a project file.
9389
9390 @item -eInnn
9391 @cindex @option{-eI} (@command{gnatmake})
9392 Indicates that the main source is a multi-unit source and the rank of the unit
9393 in the source file is nnn. nnn needs to be a positive number and a valid
9394 index in the source. This switch cannot be used when @command{gnatmake} is
9395 invoked for several mains.
9396
9397 @ifclear vms
9398 @item -eL
9399 @cindex @option{-eL} (@command{gnatmake})
9400 @cindex symbolic links
9401 Follow all symbolic links when processing project files.
9402 This should be used if your project uses symbolic links for files or
9403 directories, but is not needed in other cases.
9404
9405 @cindex naming scheme
9406 This also assumes that no directory matches the naming scheme for files (for
9407 instance that you do not have a directory called "sources.ads" when using the
9408 default GNAT naming scheme).
9409
9410 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9411 save a lot of system calls (several per source file and object file), which
9412 can result in a significant speed up to load and manipulate a project file,
9413 especially when using source files from a remote system.
9414
9415 @end ifclear
9416
9417 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9418 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9419 Output the commands for the compiler, the binder and the linker
9420 on ^standard output^SYS$OUTPUT^,
9421 instead of ^standard error^SYS$ERROR^.
9422
9423 @item ^-f^/FORCE_COMPILE^
9424 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9425 Force recompilations. Recompile all sources, even though some object
9426 files may be up to date, but don't recompile predefined or GNAT internal
9427 files or locked files (files with a write-protected ALI file),
9428 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9429
9430 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9431 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9432 When using project files, if some errors or warnings are detected during
9433 parsing and verbose mode is not in effect (no use of switch
9434 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9435 file, rather than its simple file name.
9436
9437 @item ^-g^/DEBUG^
9438 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9439 Enable debugging. This switch is simply passed to the compiler and to the
9440 linker.
9441
9442 @item ^-i^/IN_PLACE^
9443 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9444 In normal mode, @command{gnatmake} compiles all object files and ALI files
9445 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9446 then instead object files and ALI files that already exist are overwritten
9447 in place. This means that once a large project is organized into separate
9448 directories in the desired manner, then @command{gnatmake} will automatically
9449 maintain and update this organization. If no ALI files are found on the
9450 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9451 the new object and ALI files are created in the
9452 directory containing the source being compiled. If another organization
9453 is desired, where objects and sources are kept in different directories,
9454 a useful technique is to create dummy ALI files in the desired directories.
9455 When detecting such a dummy file, @command{gnatmake} will be forced to
9456 recompile the corresponding source file, and it will be put the resulting
9457 object and ALI files in the directory where it found the dummy file.
9458
9459 @item ^-j^/PROCESSES=^@var{n}
9460 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9461 @cindex Parallel make
9462 Use @var{n} processes to carry out the (re)compilations. On a multiprocessor
9463 machine compilations will occur in parallel. If @var{n} is 0, then the
9464 maximum number of parallel compilations is the number of core processors
9465 on the platform. In the event of compilation errors, messages from various
9466 compilations might get interspersed (but @command{gnatmake} will give you the
9467 full ordered list of failing compiles at the end). If this is problematic,
9468 rerun the make process with n set to 1 to get a clean list of messages.
9469
9470 @item ^-k^/CONTINUE_ON_ERROR^
9471 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9472 Keep going. Continue as much as possible after a compilation error. To
9473 ease the programmer's task in case of compilation errors, the list of
9474 sources for which the compile fails is given when @command{gnatmake}
9475 terminates.
9476
9477 If @command{gnatmake} is invoked with several @file{file_names} and with this
9478 switch, if there are compilation errors when building an executable,
9479 @command{gnatmake} will not attempt to build the following executables.
9480
9481 @item ^-l^/ACTIONS=LINK^
9482 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9483 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9484 and linking. Linking will not be performed if combined with
9485 @option{^-c^/ACTIONS=COMPILE^}
9486 but not with @option{^-b^/ACTIONS=BIND^}.
9487 When not combined with @option{^-b^/ACTIONS=BIND^}
9488 all the units in the closure of the main program must have been previously
9489 compiled and must be up to date, and the main program needs to have been bound.
9490 The root unit specified by @var{file_name}
9491 may be given without extension, with the source extension or, if no GNAT
9492 Project File is specified, with the ALI file extension.
9493
9494 @item ^-m^/MINIMAL_RECOMPILATION^
9495 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9496 Specify that the minimum necessary amount of recompilations
9497 be performed. In this mode @command{gnatmake} ignores time
9498 stamp differences when the only
9499 modifications to a source file consist in adding/removing comments,
9500 empty lines, spaces or tabs. This means that if you have changed the
9501 comments in a source file or have simply reformatted it, using this
9502 switch will tell @command{gnatmake} not to recompile files that depend on it
9503 (provided other sources on which these files depend have undergone no
9504 semantic modifications). Note that the debugging information may be
9505 out of date with respect to the sources if the @option{-m} switch causes
9506 a compilation to be switched, so the use of this switch represents a
9507 trade-off between compilation time and accurate debugging information.
9508
9509 @item ^-M^/DEPENDENCIES_LIST^
9510 @cindex Dependencies, producing list
9511 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9512 Check if all objects are up to date. If they are, output the object
9513 dependences to @file{stdout} in a form that can be directly exploited in
9514 a @file{Makefile}. By default, each source file is prefixed with its
9515 (relative or absolute) directory name. This name is whatever you
9516 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9517 and @option{^-I^/SEARCH^} switches. If you use
9518 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9519 @option{^-q^/QUIET^}
9520 (see below), only the source file names,
9521 without relative paths, are output. If you just specify the
9522 @option{^-M^/DEPENDENCIES_LIST^}
9523 switch, dependencies of the GNAT internal system files are omitted. This
9524 is typically what you want. If you also specify
9525 the @option{^-a^/ALL_FILES^} switch,
9526 dependencies of the GNAT internal files are also listed. Note that
9527 dependencies of the objects in external Ada libraries (see switch
9528 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9529 are never reported.
9530
9531 @item ^-n^/DO_OBJECT_CHECK^
9532 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9533 Don't compile, bind, or link. Checks if all objects are up to date.
9534 If they are not, the full name of the first file that needs to be
9535 recompiled is printed.
9536 Repeated use of this option, followed by compiling the indicated source
9537 file, will eventually result in recompiling all required units.
9538
9539 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9540 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9541 Output executable name. The name of the final executable program will be
9542 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9543 name for the executable will be the name of the input file in appropriate form
9544 for an executable file on the host system.
9545
9546 This switch cannot be used when invoking @command{gnatmake} with several
9547 @file{file_names}.
9548
9549 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9550 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9551 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9552 automatically missing object directories, library directories and exec
9553 directories.
9554
9555 @item ^-P^/PROJECT_FILE=^@var{project}
9556 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9557 Use project file @var{project}. Only one such switch can be used.
9558 @xref{gnatmake and Project Files}.
9559
9560 @item ^-q^/QUIET^
9561 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9562 Quiet. When this flag is not set, the commands carried out by
9563 @command{gnatmake} are displayed.
9564
9565 @item ^-s^/SWITCH_CHECK/^
9566 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9567 Recompile if compiler switches have changed since last compilation.
9568 All compiler switches but -I and -o are taken into account in the
9569 following way:
9570 orders between different ``first letter'' switches are ignored, but
9571 orders between same switches are taken into account. For example,
9572 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9573 is equivalent to @option{-O -g}.
9574
9575 This switch is recommended when Integrated Preprocessing is used.
9576
9577 @item ^-u^/UNIQUE^
9578 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9579 Unique. Recompile at most the main files. It implies -c. Combined with
9580 -f, it is equivalent to calling the compiler directly. Note that using
9581 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9582 (@pxref{Project Files and Main Subprograms}).
9583
9584 @item ^-U^/ALL_PROJECTS^
9585 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9586 When used without a project file or with one or several mains on the command
9587 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9588 on the command line, all sources of all project files are checked and compiled
9589 if not up to date, and libraries are rebuilt, if necessary.
9590
9591 @item ^-v^/REASONS^
9592 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9593 Verbose. Display the reason for all recompilations @command{gnatmake}
9594 decides are necessary, with the highest verbosity level.
9595
9596 @item ^-vl^/LOW_VERBOSITY^
9597 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9598 Verbosity level Low. Display fewer lines than in verbosity Medium.
9599
9600 @item ^-vm^/MEDIUM_VERBOSITY^
9601 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9602 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9603
9604 @item ^-vh^/HIGH_VERBOSITY^
9605 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9606 Verbosity level High. Equivalent to ^-v^/REASONS^.
9607
9608 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9609 Indicate the verbosity of the parsing of GNAT project files.
9610 @xref{Switches Related to Project Files}.
9611
9612 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9613 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9614 Indicate that sources that are not part of any Project File may be compiled.
9615 Normally, when using Project Files, only sources that are part of a Project
9616 File may be compile. When this switch is used, a source outside of all Project
9617 Files may be compiled. The ALI file and the object file will be put in the
9618 object directory of the main Project. The compilation switches used will only
9619 be those specified on the command line. Even when
9620 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9621 command line need to be sources of a project file.
9622
9623 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9624 Indicate that external variable @var{name} has the value @var{value}.
9625 The Project Manager will use this value for occurrences of
9626 @code{external(name)} when parsing the project file.
9627 @xref{Switches Related to Project Files}.
9628
9629 @item ^-z^/NOMAIN^
9630 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9631 No main subprogram. Bind and link the program even if the unit name
9632 given on the command line is a package name. The resulting executable
9633 will execute the elaboration routines of the package and its closure,
9634 then the finalization routines.
9635
9636 @end table
9637
9638 @table @asis
9639 @item @command{gcc} @asis{switches}
9640 @ifclear vms
9641 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9642 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9643 @end ifclear
9644 @ifset vms
9645 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9646 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9647 automatically treated as a compiler switch, and passed on to all
9648 compilations that are carried out.
9649 @end ifset
9650 @end table
9651
9652 @noindent
9653 Source and library search path switches:
9654
9655 @table @option
9656 @c !sort!
9657 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9658 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9659 When looking for source files also look in directory @var{dir}.
9660 The order in which source files search is undertaken is
9661 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9662
9663 @item ^-aL^/SKIP_MISSING=^@var{dir}
9664 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9665 Consider @var{dir} as being an externally provided Ada library.
9666 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9667 files have been located in directory @var{dir}. This allows you to have
9668 missing bodies for the units in @var{dir} and to ignore out of date bodies
9669 for the same units. You still need to specify
9670 the location of the specs for these units by using the switches
9671 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9672 or @option{^-I^/SEARCH=^@var{dir}}.
9673 Note: this switch is provided for compatibility with previous versions
9674 of @command{gnatmake}. The easier method of causing standard libraries
9675 to be excluded from consideration is to write-protect the corresponding
9676 ALI files.
9677
9678 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9679 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9680 When searching for library and object files, look in directory
9681 @var{dir}. The order in which library files are searched is described in
9682 @ref{Search Paths for gnatbind}.
9683
9684 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9685 @cindex Search paths, for @command{gnatmake}
9686 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9687 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9688 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9689
9690 @item ^-I^/SEARCH=^@var{dir}
9691 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9692 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9693 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9694
9695 @item ^-I-^/NOCURRENT_DIRECTORY^
9696 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9697 @cindex Source files, suppressing search
9698 Do not look for source files in the directory containing the source
9699 file named in the command line.
9700 Do not look for ALI or object files in the directory
9701 where @command{gnatmake} was invoked.
9702
9703 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
9704 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
9705 @cindex Linker libraries
9706 Add directory @var{dir} to the list of directories in which the linker
9707 will search for libraries. This is equivalent to
9708 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
9709 @ifclear vms
9710 Furthermore, under Windows, the sources pointed to by the libraries path
9711 set in the registry are not searched for.
9712 @end ifclear
9713
9714 @item -nostdinc
9715 @cindex @option{-nostdinc} (@command{gnatmake})
9716 Do not look for source files in the system default directory.
9717
9718 @item -nostdlib
9719 @cindex @option{-nostdlib} (@command{gnatmake})
9720 Do not look for library files in the system default directory.
9721
9722 @item --RTS=@var{rts-path}
9723 @cindex @option{--RTS} (@command{gnatmake})
9724 Specifies the default location of the runtime library. GNAT looks for the
9725 runtime
9726 in the following directories, and stops as soon as a valid runtime is found
9727 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
9728 @file{ada_object_path} present):
9729
9730 @itemize @bullet
9731 @item <current directory>/$rts_path
9732
9733 @item <default-search-dir>/$rts_path
9734
9735 @item <default-search-dir>/rts-$rts_path
9736 @end itemize
9737
9738 @noindent
9739 The selected path is handled like a normal RTS path.
9740
9741 @end table
9742
9743 @node Mode Switches for gnatmake
9744 @section Mode Switches for @command{gnatmake}
9745
9746 @noindent
9747 The mode switches (referred to as @code{mode_switches}) allow the
9748 inclusion of switches that are to be passed to the compiler itself, the
9749 binder or the linker. The effect of a mode switch is to cause all
9750 subsequent switches up to the end of the switch list, or up to the next
9751 mode switch, to be interpreted as switches to be passed on to the
9752 designated component of GNAT.
9753
9754 @table @option
9755 @c !sort!
9756 @item -cargs @var{switches}
9757 @cindex @option{-cargs} (@command{gnatmake})
9758 Compiler switches. Here @var{switches} is a list of switches
9759 that are valid switches for @command{gcc}. They will be passed on to
9760 all compile steps performed by @command{gnatmake}.
9761
9762 @item -bargs @var{switches}
9763 @cindex @option{-bargs} (@command{gnatmake})
9764 Binder switches. Here @var{switches} is a list of switches
9765 that are valid switches for @code{gnatbind}. They will be passed on to
9766 all bind steps performed by @command{gnatmake}.
9767
9768 @item -largs @var{switches}
9769 @cindex @option{-largs} (@command{gnatmake})
9770 Linker switches. Here @var{switches} is a list of switches
9771 that are valid switches for @command{gnatlink}. They will be passed on to
9772 all link steps performed by @command{gnatmake}.
9773
9774 @item -margs @var{switches}
9775 @cindex @option{-margs} (@command{gnatmake})
9776 Make switches. The switches are directly interpreted by @command{gnatmake},
9777 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
9778 or @option{-largs}.
9779 @end table
9780
9781 @node Notes on the Command Line
9782 @section Notes on the Command Line
9783
9784 @noindent
9785 This section contains some additional useful notes on the operation
9786 of the @command{gnatmake} command.
9787
9788 @itemize @bullet
9789 @item
9790 @cindex Recompilation, by @command{gnatmake}
9791 If @command{gnatmake} finds no ALI files, it recompiles the main program
9792 and all other units required by the main program.
9793 This means that @command{gnatmake}
9794 can be used for the initial compile, as well as during subsequent steps of
9795 the development cycle.
9796
9797 @item
9798 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
9799 is a subunit or body of a generic unit, @command{gnatmake} recompiles
9800 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
9801 warning.
9802
9803 @item
9804 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
9805 is used to specify both source and
9806 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9807 instead if you just want to specify
9808 source paths only and @option{^-aO^/OBJECT_SEARCH^}
9809 if you want to specify library paths
9810 only.
9811
9812 @item
9813 @command{gnatmake} will ignore any files whose ALI file is write-protected.
9814 This may conveniently be used to exclude standard libraries from
9815 consideration and in particular it means that the use of the
9816 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
9817 unless @option{^-a^/ALL_FILES^} is also specified.
9818
9819 @item
9820 @command{gnatmake} has been designed to make the use of Ada libraries
9821 particularly convenient. Assume you have an Ada library organized
9822 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
9823 of your Ada compilation units,
9824 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
9825 specs of these units, but no bodies. Then to compile a unit
9826 stored in @code{main.adb}, which uses this Ada library you would just type
9827
9828 @smallexample
9829 @ifclear vms
9830 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
9831 @end ifclear
9832 @ifset vms
9833 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
9834 /SKIP_MISSING=@i{[OBJ_DIR]} main
9835 @end ifset
9836 @end smallexample
9837
9838 @item
9839 Using @command{gnatmake} along with the
9840 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
9841 switch provides a mechanism for avoiding unnecessary recompilations. Using
9842 this switch,
9843 you can update the comments/format of your
9844 source files without having to recompile everything. Note, however, that
9845 adding or deleting lines in a source files may render its debugging
9846 info obsolete. If the file in question is a spec, the impact is rather
9847 limited, as that debugging info will only be useful during the
9848 elaboration phase of your program. For bodies the impact can be more
9849 significant. In all events, your debugger will warn you if a source file
9850 is more recent than the corresponding object, and alert you to the fact
9851 that the debugging information may be out of date.
9852 @end itemize
9853
9854 @node How gnatmake Works
9855 @section How @command{gnatmake} Works
9856
9857 @noindent
9858 Generally @command{gnatmake} automatically performs all necessary
9859 recompilations and you don't need to worry about how it works. However,
9860 it may be useful to have some basic understanding of the @command{gnatmake}
9861 approach and in particular to understand how it uses the results of
9862 previous compilations without incorrectly depending on them.
9863
9864 First a definition: an object file is considered @dfn{up to date} if the
9865 corresponding ALI file exists and if all the source files listed in the
9866 dependency section of this ALI file have time stamps matching those in
9867 the ALI file. This means that neither the source file itself nor any
9868 files that it depends on have been modified, and hence there is no need
9869 to recompile this file.
9870
9871 @command{gnatmake} works by first checking if the specified main unit is up
9872 to date. If so, no compilations are required for the main unit. If not,
9873 @command{gnatmake} compiles the main program to build a new ALI file that
9874 reflects the latest sources. Then the ALI file of the main unit is
9875 examined to find all the source files on which the main program depends,
9876 and @command{gnatmake} recursively applies the above procedure on all these
9877 files.
9878
9879 This process ensures that @command{gnatmake} only trusts the dependencies
9880 in an existing ALI file if they are known to be correct. Otherwise it
9881 always recompiles to determine a new, guaranteed accurate set of
9882 dependencies. As a result the program is compiled ``upside down'' from what may
9883 be more familiar as the required order of compilation in some other Ada
9884 systems. In particular, clients are compiled before the units on which
9885 they depend. The ability of GNAT to compile in any order is critical in
9886 allowing an order of compilation to be chosen that guarantees that
9887 @command{gnatmake} will recompute a correct set of new dependencies if
9888 necessary.
9889
9890 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
9891 imported by several of the executables, it will be recompiled at most once.
9892
9893 Note: when using non-standard naming conventions
9894 (@pxref{Using Other File Names}), changing through a configuration pragmas
9895 file the version of a source and invoking @command{gnatmake} to recompile may
9896 have no effect, if the previous version of the source is still accessible
9897 by @command{gnatmake}. It may be necessary to use the switch
9898 ^-f^/FORCE_COMPILE^.
9899
9900 @node Examples of gnatmake Usage
9901 @section Examples of @command{gnatmake} Usage
9902
9903 @table @code
9904 @item gnatmake hello.adb
9905 Compile all files necessary to bind and link the main program
9906 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
9907 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
9908
9909 @item gnatmake main1 main2 main3
9910 Compile all files necessary to bind and link the main programs
9911 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
9912 (containing unit @code{Main2}) and @file{main3.adb}
9913 (containing unit @code{Main3}) and bind and link the resulting object files
9914 to generate three executable files @file{^main1^MAIN1.EXE^},
9915 @file{^main2^MAIN2.EXE^}
9916 and @file{^main3^MAIN3.EXE^}.
9917
9918 @ifclear vms
9919 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
9920 @end ifclear
9921
9922 @ifset vms
9923 @item gnatmake Main_Unit /QUIET
9924 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
9925 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
9926 @end ifset
9927 Compile all files necessary to bind and link the main program unit
9928 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
9929 be done with optimization level 2 and the order of elaboration will be
9930 listed by the binder. @command{gnatmake} will operate in quiet mode, not
9931 displaying commands it is executing.
9932 @end table
9933
9934 @c *************************
9935 @node Improving Performance
9936 @chapter Improving Performance
9937 @cindex Improving performance
9938
9939 @noindent
9940 This chapter presents several topics related to program performance.
9941 It first describes some of the tradeoffs that need to be considered
9942 and some of the techniques for making your program run faster.
9943 It then documents the @command{gnatelim} tool and unused subprogram/data
9944 elimination feature, which can reduce the size of program executables.
9945
9946 @ifnottex
9947 @menu
9948 * Performance Considerations::
9949 * Text_IO Suggestions::
9950 * Reducing Size of Ada Executables with gnatelim::
9951 * Reducing Size of Executables with unused subprogram/data elimination::
9952 @end menu
9953 @end ifnottex
9954
9955 @c *****************************
9956 @node Performance Considerations
9957 @section Performance Considerations
9958
9959 @noindent
9960 The GNAT system provides a number of options that allow a trade-off
9961 between
9962
9963 @itemize @bullet
9964 @item
9965 performance of the generated code
9966
9967 @item
9968 speed of compilation
9969
9970 @item
9971 minimization of dependences and recompilation
9972
9973 @item
9974 the degree of run-time checking.
9975 @end itemize
9976
9977 @noindent
9978 The defaults (if no options are selected) aim at improving the speed
9979 of compilation and minimizing dependences, at the expense of performance
9980 of the generated code:
9981
9982 @itemize @bullet
9983 @item
9984 no optimization
9985
9986 @item
9987 no inlining of subprogram calls
9988
9989 @item
9990 all run-time checks enabled except overflow and elaboration checks
9991 @end itemize
9992
9993 @noindent
9994 These options are suitable for most program development purposes. This
9995 chapter describes how you can modify these choices, and also provides
9996 some guidelines on debugging optimized code.
9997
9998 @menu
9999 * Controlling Run-Time Checks::
10000 * Use of Restrictions::
10001 * Optimization Levels::
10002 * Debugging Optimized Code::
10003 * Inlining of Subprograms::
10004 * Vectorization of loops::
10005 * Other Optimization Switches::
10006 * Optimization and Strict Aliasing::
10007 * Aliased Variables and Optimization::
10008
10009 @ifset vms
10010 * Coverage Analysis::
10011 @end ifset
10012 @end menu
10013
10014 @node Controlling Run-Time Checks
10015 @subsection Controlling Run-Time Checks
10016
10017 @noindent
10018 By default, GNAT generates all run-time checks, except integer overflow
10019 checks, stack overflow checks, and checks for access before elaboration on
10020 subprogram calls. The latter are not required in default mode, because all
10021 necessary checking is done at compile time.
10022 @cindex @option{-gnatp} (@command{gcc})
10023 @cindex @option{-gnato} (@command{gcc})
10024 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10025 be modified. @xref{Run-Time Checks}.
10026
10027 Our experience is that the default is suitable for most development
10028 purposes.
10029
10030 We treat integer overflow specially because these
10031 are quite expensive and in our experience are not as important as other
10032 run-time checks in the development process. Note that division by zero
10033 is not considered an overflow check, and divide by zero checks are
10034 generated where required by default.
10035
10036 Elaboration checks are off by default, and also not needed by default, since
10037 GNAT uses a static elaboration analysis approach that avoids the need for
10038 run-time checking. This manual contains a full chapter discussing the issue
10039 of elaboration checks, and if the default is not satisfactory for your use,
10040 you should read this chapter.
10041
10042 For validity checks, the minimal checks required by the Ada Reference
10043 Manual (for case statements and assignments to array elements) are on
10044 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10045 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10046 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10047 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10048 are also suppressed entirely if @option{-gnatp} is used.
10049
10050 @cindex Overflow checks
10051 @cindex Checks, overflow
10052 @findex Suppress
10053 @findex Unsuppress
10054 @cindex pragma Suppress
10055 @cindex pragma Unsuppress
10056 Note that the setting of the switches controls the default setting of
10057 the checks. They may be modified using either @code{pragma Suppress} (to
10058 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10059 checks) in the program source.
10060
10061 @node Use of Restrictions
10062 @subsection Use of Restrictions
10063
10064 @noindent
10065 The use of pragma Restrictions allows you to control which features are
10066 permitted in your program. Apart from the obvious point that if you avoid
10067 relatively expensive features like finalization (enforceable by the use
10068 of pragma Restrictions (No_Finalization), the use of this pragma does not
10069 affect the generated code in most cases.
10070
10071 One notable exception to this rule is that the possibility of task abort
10072 results in some distributed overhead, particularly if finalization or
10073 exception handlers are used. The reason is that certain sections of code
10074 have to be marked as non-abortable.
10075
10076 If you use neither the @code{abort} statement, nor asynchronous transfer
10077 of control (@code{select @dots{} then abort}), then this distributed overhead
10078 is removed, which may have a general positive effect in improving
10079 overall performance. Especially code involving frequent use of tasking
10080 constructs and controlled types will show much improved performance.
10081 The relevant restrictions pragmas are
10082
10083 @smallexample @c ada
10084 pragma Restrictions (No_Abort_Statements);
10085 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10086 @end smallexample
10087
10088 @noindent
10089 It is recommended that these restriction pragmas be used if possible. Note
10090 that this also means that you can write code without worrying about the
10091 possibility of an immediate abort at any point.
10092
10093 @node Optimization Levels
10094 @subsection Optimization Levels
10095 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10096
10097 @noindent
10098 Without any optimization ^option,^qualifier,^
10099 the compiler's goal is to reduce the cost of
10100 compilation and to make debugging produce the expected results.
10101 Statements are independent: if you stop the program with a breakpoint between
10102 statements, you can then assign a new value to any variable or change
10103 the program counter to any other statement in the subprogram and get exactly
10104 the results you would expect from the source code.
10105
10106 Turning on optimization makes the compiler attempt to improve the
10107 performance and/or code size at the expense of compilation time and
10108 possibly the ability to debug the program.
10109
10110 If you use multiple
10111 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10112 the last such option is the one that is effective.
10113
10114 @noindent
10115 The default is optimization off. This results in the fastest compile
10116 times, but GNAT makes absolutely no attempt to optimize, and the
10117 generated programs are considerably larger and slower than when
10118 optimization is enabled. You can use the
10119 @ifclear vms
10120 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10121 @option{-O2}, @option{-O3}, and @option{-Os})
10122 @end ifclear
10123 @ifset vms
10124 @code{OPTIMIZE} qualifier
10125 @end ifset
10126 to @command{gcc} to control the optimization level:
10127
10128 @table @option
10129 @item ^-O0^/OPTIMIZE=NONE^
10130 No optimization (the default);
10131 generates unoptimized code but has
10132 the fastest compilation time.
10133
10134 Note that many other compilers do fairly extensive optimization
10135 even if ``no optimization'' is specified. With gcc, it is
10136 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10137 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10138 really does mean no optimization at all. This difference between
10139 gcc and other compilers should be kept in mind when doing
10140 performance comparisons.
10141
10142 @item ^-O1^/OPTIMIZE=SOME^
10143 Moderate optimization;
10144 optimizes reasonably well but does not
10145 degrade compilation time significantly.
10146
10147 @item ^-O2^/OPTIMIZE=ALL^
10148 @ifset vms
10149 @itemx /OPTIMIZE=DEVELOPMENT
10150 @end ifset
10151 Full optimization;
10152 generates highly optimized code and has
10153 the slowest compilation time.
10154
10155 @item ^-O3^/OPTIMIZE=INLINING^
10156 Full optimization as in @option{-O2};
10157 also uses more aggressive automatic inlining of subprograms within a unit
10158 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10159
10160 @item ^-Os^/OPTIMIZE=SPACE^
10161 Optimize space usage (code and data) of resulting program.
10162 @end table
10163
10164 @noindent
10165 Higher optimization levels perform more global transformations on the
10166 program and apply more expensive analysis algorithms in order to generate
10167 faster and more compact code. The price in compilation time, and the
10168 resulting improvement in execution time,
10169 both depend on the particular application and the hardware environment.
10170 You should experiment to find the best level for your application.
10171
10172 Since the precise set of optimizations done at each level will vary from
10173 release to release (and sometime from target to target), it is best to think
10174 of the optimization settings in general terms.
10175 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10176 the GNU Compiler Collection (GCC)}, for details about
10177 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10178 individually enable or disable specific optimizations.
10179
10180 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10181 been tested extensively at all optimization levels. There are some bugs
10182 which appear only with optimization turned on, but there have also been
10183 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10184 level of optimization does not improve the reliability of the code
10185 generator, which in practice is highly reliable at all optimization
10186 levels.
10187
10188 Note regarding the use of @option{-O3}: The use of this optimization level
10189 is generally discouraged with GNAT, since it often results in larger
10190 executables which may run more slowly. See further discussion of this point
10191 in @ref{Inlining of Subprograms}.
10192
10193 @node Debugging Optimized Code
10194 @subsection Debugging Optimized Code
10195 @cindex Debugging optimized code
10196 @cindex Optimization and debugging
10197
10198 @noindent
10199 Although it is possible to do a reasonable amount of debugging at
10200 @ifclear vms
10201 nonzero optimization levels,
10202 the higher the level the more likely that
10203 @end ifclear
10204 @ifset vms
10205 @option{/OPTIMIZE} settings other than @code{NONE},
10206 such settings will make it more likely that
10207 @end ifset
10208 source-level constructs will have been eliminated by optimization.
10209 For example, if a loop is strength-reduced, the loop
10210 control variable may be completely eliminated and thus cannot be
10211 displayed in the debugger.
10212 This can only happen at @option{-O2} or @option{-O3}.
10213 Explicit temporary variables that you code might be eliminated at
10214 ^level^setting^ @option{-O1} or higher.
10215
10216 The use of the @option{^-g^/DEBUG^} switch,
10217 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10218 which is needed for source-level debugging,
10219 affects the size of the program executable on disk,
10220 and indeed the debugging information can be quite large.
10221 However, it has no effect on the generated code (and thus does not
10222 degrade performance)
10223
10224 Since the compiler generates debugging tables for a compilation unit before
10225 it performs optimizations, the optimizing transformations may invalidate some
10226 of the debugging data. You therefore need to anticipate certain
10227 anomalous situations that may arise while debugging optimized code.
10228 These are the most common cases:
10229
10230 @enumerate
10231 @item
10232 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
10233 commands show
10234 the PC bouncing back and forth in the code. This may result from any of
10235 the following optimizations:
10236
10237 @itemize @bullet
10238 @item
10239 @i{Common subexpression elimination:} using a single instance of code for a
10240 quantity that the source computes several times. As a result you
10241 may not be able to stop on what looks like a statement.
10242
10243 @item
10244 @i{Invariant code motion:} moving an expression that does not change within a
10245 loop, to the beginning of the loop.
10246
10247 @item
10248 @i{Instruction scheduling:} moving instructions so as to
10249 overlap loads and stores (typically) with other code, or in
10250 general to move computations of values closer to their uses. Often
10251 this causes you to pass an assignment statement without the assignment
10252 happening and then later bounce back to the statement when the
10253 value is actually needed. Placing a breakpoint on a line of code
10254 and then stepping over it may, therefore, not always cause all the
10255 expected side-effects.
10256 @end itemize
10257
10258 @item
10259 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10260 two identical pieces of code are merged and the program counter suddenly
10261 jumps to a statement that is not supposed to be executed, simply because
10262 it (and the code following) translates to the same thing as the code
10263 that @emph{was} supposed to be executed. This effect is typically seen in
10264 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10265 a @code{break} in a C @code{^switch^switch^} statement.
10266
10267 @item
10268 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10269 There are various reasons for this effect:
10270
10271 @itemize @bullet
10272 @item
10273 In a subprogram prologue, a parameter may not yet have been moved to its
10274 ``home''.
10275
10276 @item
10277 A variable may be dead, and its register re-used. This is
10278 probably the most common cause.
10279
10280 @item
10281 As mentioned above, the assignment of a value to a variable may
10282 have been moved.
10283
10284 @item
10285 A variable may be eliminated entirely by value propagation or
10286 other means. In this case, GCC may incorrectly generate debugging
10287 information for the variable
10288 @end itemize
10289
10290 @noindent
10291 In general, when an unexpected value appears for a local variable or parameter
10292 you should first ascertain if that value was actually computed by
10293 your program, as opposed to being incorrectly reported by the debugger.
10294 Record fields or
10295 array elements in an object designated by an access value
10296 are generally less of a problem, once you have ascertained that the access
10297 value is sensible.
10298 Typically, this means checking variables in the preceding code and in the
10299 calling subprogram to verify that the value observed is explainable from other
10300 values (one must apply the procedure recursively to those
10301 other values); or re-running the code and stopping a little earlier
10302 (perhaps before the call) and stepping to better see how the variable obtained
10303 the value in question; or continuing to step @emph{from} the point of the
10304 strange value to see if code motion had simply moved the variable's
10305 assignments later.
10306 @end enumerate
10307
10308 @noindent
10309 In light of such anomalies, a recommended technique is to use @option{-O0}
10310 early in the software development cycle, when extensive debugging capabilities
10311 are most needed, and then move to @option{-O1} and later @option{-O2} as
10312 the debugger becomes less critical.
10313 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10314 a release management issue.
10315 @ifclear vms
10316 Note that if you use @option{-g} you can then use the @command{strip} program
10317 on the resulting executable,
10318 which removes both debugging information and global symbols.
10319 @end ifclear
10320
10321 @node Inlining of Subprograms
10322 @subsection Inlining of Subprograms
10323
10324 @noindent
10325 A call to a subprogram in the current unit is inlined if all the
10326 following conditions are met:
10327
10328 @itemize @bullet
10329 @item
10330 The optimization level is at least @option{-O1}.
10331
10332 @item
10333 The called subprogram is suitable for inlining: It must be small enough
10334 and not contain something that @command{gcc} cannot support in inlined
10335 subprograms.
10336
10337 @item
10338 @cindex pragma Inline
10339 @findex Inline
10340 Any one of the following applies: @code{pragma Inline} is applied to the
10341 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10342 subprogram is local to the unit and called once from within it; the
10343 subprogram is small and optimization level @option{-O2} is specified;
10344 optimization level @option{-O3} is specified.
10345 @end itemize
10346
10347 @noindent
10348 Calls to subprograms in @code{with}'ed units are normally not inlined.
10349 To achieve actual inlining (that is, replacement of the call by the code
10350 in the body of the subprogram), the following conditions must all be true:
10351
10352 @itemize @bullet
10353 @item
10354 The optimization level is at least @option{-O1}.
10355
10356 @item
10357 The called subprogram is suitable for inlining: It must be small enough
10358 and not contain something that @command{gcc} cannot support in inlined
10359 subprograms.
10360
10361 @item
10362 The call appears in a body (not in a package spec).
10363
10364 @item
10365 There is a @code{pragma Inline} for the subprogram.
10366
10367 @item
10368 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10369 @end itemize
10370
10371 Even if all these conditions are met, it may not be possible for
10372 the compiler to inline the call, due to the length of the body,
10373 or features in the body that make it impossible for the compiler
10374 to do the inlining.
10375
10376 Note that specifying the @option{-gnatn} switch causes additional
10377 compilation dependencies. Consider the following:
10378
10379 @smallexample @c ada
10380 @cartouche
10381 package R is
10382 procedure Q;
10383 pragma Inline (Q);
10384 end R;
10385 package body R is
10386 @dots{}
10387 end R;
10388
10389 with R;
10390 procedure Main is
10391 begin
10392 @dots{}
10393 R.Q;
10394 end Main;
10395 @end cartouche
10396 @end smallexample
10397
10398 @noindent
10399 With the default behavior (no @option{-gnatn} switch specified), the
10400 compilation of the @code{Main} procedure depends only on its own source,
10401 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10402 means that editing the body of @code{R} does not require recompiling
10403 @code{Main}.
10404
10405 On the other hand, the call @code{R.Q} is not inlined under these
10406 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10407 is compiled, the call will be inlined if the body of @code{Q} is small
10408 enough, but now @code{Main} depends on the body of @code{R} in
10409 @file{r.adb} as well as on the spec. This means that if this body is edited,
10410 the main program must be recompiled. Note that this extra dependency
10411 occurs whether or not the call is in fact inlined by @command{gcc}.
10412
10413 The use of front end inlining with @option{-gnatN} generates similar
10414 additional dependencies.
10415
10416 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10417 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10418 can be used to prevent
10419 all inlining. This switch overrides all other conditions and ensures
10420 that no inlining occurs. The extra dependences resulting from
10421 @option{-gnatn} will still be active, even if
10422 this switch is used to suppress the resulting inlining actions.
10423
10424 @cindex @option{-fno-inline-functions} (@command{gcc})
10425 Note: The @option{-fno-inline-functions} switch can be used to prevent
10426 automatic inlining of subprograms if @option{-O3} is used.
10427
10428 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10429 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10430 automatic inlining of small subprograms if @option{-O2} is used.
10431
10432 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10433 Note: The @option{-fno-inline-functions-called-once} switch
10434 can be used to prevent inlining of subprograms local to the unit
10435 and called once from within it if @option{-O1} is used.
10436
10437 Note regarding the use of @option{-O3}: @option{-gnatn} is made up of two
10438 sub-switches @option{-gnatn1} and @option{-gnatn2} that can be directly
10439 specified in lieu of it, @option{-gnatn} being translated into one of them
10440 based on the optimization level. With @option{-O2} or below, @option{-gnatn}
10441 is equivalent to @option{-gnatn1} which activates pragma @code{Inline} with
10442 moderate inlining across modules. With @option{-O3}, @option{-gnatn} is
10443 equivalent to @option{-gnatn2} which activates pragma @code{Inline} with
10444 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
10445 effect of inlining subprograms you did not think should be inlined. We have
10446 found that the use of @option{-O3} may slow down the compilation and increase
10447 the code size by performing excessive inlining, leading to increased
10448 instruction cache pressure from the increased code size and thus minor
10449 performance improvements. So the bottom line here is that you should not
10450 automatically assume that @option{-O3} is better than @option{-O2}, and
10451 indeed you should use @option{-O3} only if tests show that it actually
10452 improves performance for your program.
10453
10454 @node Vectorization of loops
10455 @subsection Vectorization of loops
10456 @cindex Optimization Switches
10457
10458 You can take advantage of the auto-vectorizer present in the @command{gcc}
10459 back end to vectorize loops with GNAT. The corresponding command line switch
10460 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10461 and other aggressive optimizations helpful for vectorization also are enabled
10462 by default at this level, using @option{-O3} directly is recommended.
10463
10464 You also need to make sure that the target architecture features a supported
10465 SIMD instruction set. For example, for the x86 architecture, you should at
10466 least specify @option{-msse2} to get significant vectorization (but you don't
10467 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10468 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10469
10470 The preferred loop form for vectorization is the @code{for} iteration scheme.
10471 Loops with a @code{while} iteration scheme can also be vectorized if they are
10472 very simple, but the vectorizer will quickly give up otherwise. With either
10473 iteration scheme, the flow of control must be straight, in particular no
10474 @code{exit} statement may appear in the loop body. The loop may however
10475 contain a single nested loop, if it can be vectorized when considered alone:
10476
10477 @smallexample @c ada
10478 @cartouche
10479 A : array (1..4, 1..4) of Long_Float;
10480 S : array (1..4) of Long_Float;
10481
10482 procedure Sum is
10483 begin
10484 for I in A'Range(1) loop
10485 for J in A'Range(2) loop
10486 S (I) := S (I) + A (I, J);
10487 end loop;
10488 end loop;
10489 end Sum;
10490 @end cartouche
10491 @end smallexample
10492
10493 The vectorizable operations depend on the targeted SIMD instruction set, but
10494 the adding and some of the multiplying operators are generally supported, as
10495 well as the logical operators for modular types. Note that, in the former
10496 case, enabling overflow checks, for example with @option{-gnato}, totally
10497 disables vectorization. The other checks are not supposed to have the same
10498 definitive effect, although compiling with @option{-gnatp} might well reveal
10499 cases where some checks do thwart vectorization.
10500
10501 Type conversions may also prevent vectorization if they involve semantics that
10502 are not directly supported by the code generator or the SIMD instruction set.
10503 A typical example is direct conversion from floating-point to integer types.
10504 The solution in this case is to use the following idiom:
10505
10506 @smallexample @c ada
10507 Integer (S'Truncation (F))
10508 @end smallexample
10509
10510 @noindent
10511 if @code{S} is the subtype of floating-point object @code{F}.
10512
10513 In most cases, the vectorizable loops are loops that iterate over arrays.
10514 All kinds of array types are supported, i.e. constrained array types with
10515 static bounds:
10516
10517 @smallexample @c ada
10518 type Array_Type is array (1 .. 4) of Long_Float;
10519 @end smallexample
10520
10521 @noindent
10522 constrained array types with dynamic bounds:
10523
10524 @smallexample @c ada
10525 type Array_Type is array (1 .. Q.N) of Long_Float;
10526
10527 type Array_Type is array (Q.K .. 4) of Long_Float;
10528
10529 type Array_Type is array (Q.K .. Q.N) of Long_Float;
10530 @end smallexample
10531
10532 @noindent
10533 or unconstrained array types:
10534
10535 @smallexample @c ada
10536 type Array_Type is array (Positive range <>) of Long_Float;
10537 @end smallexample
10538
10539 @noindent
10540 The quality of the generated code decreases when the dynamic aspect of the
10541 array type increases, the worst code being generated for unconstrained array
10542 types. This is so because, the less information the compiler has about the
10543 bounds of the array, the more fallback code it needs to generate in order to
10544 fix things up at run time.
10545
10546 It is possible to specify that a given loop should be subject to vectorization
10547 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
10548
10549 @smallexample @c ada
10550 pragma Loop_Optimize (Vector);
10551 @end smallexample
10552
10553 @noindent
10554 placed immediately within the loop will convey the appropriate hint to the
10555 compiler for this loop.
10556
10557 You can obtain information about the vectorization performed by the compiler
10558 by specifying @option{-ftree-vectorizer-verbose=N}. For more details of
10559 this switch, see @ref{Debugging Options,,Options for Debugging Your Program
10560 or GCC, gcc, Using the GNU Compiler Collection (GCC)}.
10561
10562 @node Other Optimization Switches
10563 @subsection Other Optimization Switches
10564 @cindex Optimization Switches
10565
10566 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10567 @command{gcc} optimization switches are potentially usable. These switches
10568 have not been extensively tested with GNAT but can generally be expected
10569 to work. Examples of switches in this category are @option{-funroll-loops}
10570 and the various target-specific @option{-m} options (in particular, it has
10571 been observed that @option{-march=xxx} can significantly improve performance
10572 on appropriate machines). For full details of these switches, see
10573 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10574 the GNU Compiler Collection (GCC)}.
10575
10576 @node Optimization and Strict Aliasing
10577 @subsection Optimization and Strict Aliasing
10578 @cindex Aliasing
10579 @cindex Strict Aliasing
10580 @cindex No_Strict_Aliasing
10581
10582 @noindent
10583 The strong typing capabilities of Ada allow an optimizer to generate
10584 efficient code in situations where other languages would be forced to
10585 make worst case assumptions preventing such optimizations. Consider
10586 the following example:
10587
10588 @smallexample @c ada
10589 @cartouche
10590 procedure R is
10591 type Int1 is new Integer;
10592 type Int2 is new Integer;
10593 type Int1A is access Int1;
10594 type Int2A is access Int2;
10595 Int1V : Int1A;
10596 Int2V : Int2A;
10597 @dots{}
10598
10599 begin
10600 @dots{}
10601 for J in Data'Range loop
10602 if Data (J) = Int1V.all then
10603 Int2V.all := Int2V.all + 1;
10604 end if;
10605 end loop;
10606 @dots{}
10607 end R;
10608 @end cartouche
10609 @end smallexample
10610
10611 @noindent
10612 In this example, since the variable @code{Int1V} can only access objects
10613 of type @code{Int1}, and @code{Int2V} can only access objects of type
10614 @code{Int2}, there is no possibility that the assignment to
10615 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10616 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10617 for all iterations of the loop and avoid the extra memory reference
10618 required to dereference it each time through the loop.
10619
10620 This kind of optimization, called strict aliasing analysis, is
10621 triggered by specifying an optimization level of @option{-O2} or
10622 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10623 when access values are involved.
10624
10625 However, although this optimization is always correct in terms of
10626 the formal semantics of the Ada Reference Manual, difficulties can
10627 arise if features like @code{Unchecked_Conversion} are used to break
10628 the typing system. Consider the following complete program example:
10629
10630 @smallexample @c ada
10631 @cartouche
10632 package p1 is
10633 type int1 is new integer;
10634 type int2 is new integer;
10635 type a1 is access int1;
10636 type a2 is access int2;
10637 end p1;
10638
10639 with p1; use p1;
10640 package p2 is
10641 function to_a2 (Input : a1) return a2;
10642 end p2;
10643
10644 with Unchecked_Conversion;
10645 package body p2 is
10646 function to_a2 (Input : a1) return a2 is
10647 function to_a2u is
10648 new Unchecked_Conversion (a1, a2);
10649 begin
10650 return to_a2u (Input);
10651 end to_a2;
10652 end p2;
10653
10654 with p2; use p2;
10655 with p1; use p1;
10656 with Text_IO; use Text_IO;
10657 procedure m is
10658 v1 : a1 := new int1;
10659 v2 : a2 := to_a2 (v1);
10660 begin
10661 v1.all := 1;
10662 v2.all := 0;
10663 put_line (int1'image (v1.all));
10664 end;
10665 @end cartouche
10666 @end smallexample
10667
10668 @noindent
10669 This program prints out 0 in @option{-O0} or @option{-O1}
10670 mode, but it prints out 1 in @option{-O2} mode. That's
10671 because in strict aliasing mode, the compiler can and
10672 does assume that the assignment to @code{v2.all} could not
10673 affect the value of @code{v1.all}, since different types
10674 are involved.
10675
10676 This behavior is not a case of non-conformance with the standard, since
10677 the Ada RM specifies that an unchecked conversion where the resulting
10678 bit pattern is not a correct value of the target type can result in an
10679 abnormal value and attempting to reference an abnormal value makes the
10680 execution of a program erroneous. That's the case here since the result
10681 does not point to an object of type @code{int2}. This means that the
10682 effect is entirely unpredictable.
10683
10684 However, although that explanation may satisfy a language
10685 lawyer, in practice an applications programmer expects an
10686 unchecked conversion involving pointers to create true
10687 aliases and the behavior of printing 1 seems plain wrong.
10688 In this case, the strict aliasing optimization is unwelcome.
10689
10690 Indeed the compiler recognizes this possibility, and the
10691 unchecked conversion generates a warning:
10692
10693 @smallexample
10694 p2.adb:5:07: warning: possible aliasing problem with type "a2"
10695 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
10696 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
10697 @end smallexample
10698
10699 @noindent
10700 Unfortunately the problem is recognized when compiling the body of
10701 package @code{p2}, but the actual "bad" code is generated while
10702 compiling the body of @code{m} and this latter compilation does not see
10703 the suspicious @code{Unchecked_Conversion}.
10704
10705 As implied by the warning message, there are approaches you can use to
10706 avoid the unwanted strict aliasing optimization in a case like this.
10707
10708 One possibility is to simply avoid the use of @option{-O2}, but
10709 that is a bit drastic, since it throws away a number of useful
10710 optimizations that do not involve strict aliasing assumptions.
10711
10712 A less drastic approach is to compile the program using the
10713 option @option{-fno-strict-aliasing}. Actually it is only the
10714 unit containing the dereferencing of the suspicious pointer
10715 that needs to be compiled. So in this case, if we compile
10716 unit @code{m} with this switch, then we get the expected
10717 value of zero printed. Analyzing which units might need
10718 the switch can be painful, so a more reasonable approach
10719 is to compile the entire program with options @option{-O2}
10720 and @option{-fno-strict-aliasing}. If the performance is
10721 satisfactory with this combination of options, then the
10722 advantage is that the entire issue of possible "wrong"
10723 optimization due to strict aliasing is avoided.
10724
10725 To avoid the use of compiler switches, the configuration
10726 pragma @code{No_Strict_Aliasing} with no parameters may be
10727 used to specify that for all access types, the strict
10728 aliasing optimization should be suppressed.
10729
10730 However, these approaches are still overkill, in that they causes
10731 all manipulations of all access values to be deoptimized. A more
10732 refined approach is to concentrate attention on the specific
10733 access type identified as problematic.
10734
10735 First, if a careful analysis of uses of the pointer shows
10736 that there are no possible problematic references, then
10737 the warning can be suppressed by bracketing the
10738 instantiation of @code{Unchecked_Conversion} to turn
10739 the warning off:
10740
10741 @smallexample @c ada
10742 pragma Warnings (Off);
10743 function to_a2u is
10744 new Unchecked_Conversion (a1, a2);
10745 pragma Warnings (On);
10746 @end smallexample
10747
10748 @noindent
10749 Of course that approach is not appropriate for this particular
10750 example, since indeed there is a problematic reference. In this
10751 case we can take one of two other approaches.
10752
10753 The first possibility is to move the instantiation of unchecked
10754 conversion to the unit in which the type is declared. In
10755 this example, we would move the instantiation of
10756 @code{Unchecked_Conversion} from the body of package
10757 @code{p2} to the spec of package @code{p1}. Now the
10758 warning disappears. That's because any use of the
10759 access type knows there is a suspicious unchecked
10760 conversion, and the strict aliasing optimization
10761 is automatically suppressed for the type.
10762
10763 If it is not practical to move the unchecked conversion to the same unit
10764 in which the destination access type is declared (perhaps because the
10765 source type is not visible in that unit), you may use pragma
10766 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
10767 same declarative sequence as the declaration of the access type:
10768
10769 @smallexample @c ada
10770 type a2 is access int2;
10771 pragma No_Strict_Aliasing (a2);
10772 @end smallexample
10773
10774 @noindent
10775 Here again, the compiler now knows that the strict aliasing optimization
10776 should be suppressed for any reference to type @code{a2} and the
10777 expected behavior is obtained.
10778
10779 Finally, note that although the compiler can generate warnings for
10780 simple cases of unchecked conversions, there are tricker and more
10781 indirect ways of creating type incorrect aliases which the compiler
10782 cannot detect. Examples are the use of address overlays and unchecked
10783 conversions involving composite types containing access types as
10784 components. In such cases, no warnings are generated, but there can
10785 still be aliasing problems. One safe coding practice is to forbid the
10786 use of address clauses for type overlaying, and to allow unchecked
10787 conversion only for primitive types. This is not really a significant
10788 restriction since any possible desired effect can be achieved by
10789 unchecked conversion of access values.
10790
10791 The aliasing analysis done in strict aliasing mode can certainly
10792 have significant benefits. We have seen cases of large scale
10793 application code where the time is increased by up to 5% by turning
10794 this optimization off. If you have code that includes significant
10795 usage of unchecked conversion, you might want to just stick with
10796 @option{-O1} and avoid the entire issue. If you get adequate
10797 performance at this level of optimization level, that's probably
10798 the safest approach. If tests show that you really need higher
10799 levels of optimization, then you can experiment with @option{-O2}
10800 and @option{-O2 -fno-strict-aliasing} to see how much effect this
10801 has on size and speed of the code. If you really need to use
10802 @option{-O2} with strict aliasing in effect, then you should
10803 review any uses of unchecked conversion of access types,
10804 particularly if you are getting the warnings described above.
10805
10806 @node Aliased Variables and Optimization
10807 @subsection Aliased Variables and Optimization
10808 @cindex Aliasing
10809 There are scenarios in which programs may
10810 use low level techniques to modify variables
10811 that otherwise might be considered to be unassigned. For example,
10812 a variable can be passed to a procedure by reference, which takes
10813 the address of the parameter and uses the address to modify the
10814 variable's value, even though it is passed as an IN parameter.
10815 Consider the following example:
10816
10817 @smallexample @c ada
10818 procedure P is
10819 Max_Length : constant Natural := 16;
10820 type Char_Ptr is access all Character;
10821
10822 procedure Get_String(Buffer: Char_Ptr; Size : Integer);
10823 pragma Import (C, Get_String, "get_string");
10824
10825 Name : aliased String (1 .. Max_Length) := (others => ' ');
10826 Temp : Char_Ptr;
10827
10828 function Addr (S : String) return Char_Ptr is
10829 function To_Char_Ptr is
10830 new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
10831 begin
10832 return To_Char_Ptr (S (S'First)'Address);
10833 end;
10834
10835 begin
10836 Temp := Addr (Name);
10837 Get_String (Temp, Max_Length);
10838 end;
10839 @end smallexample
10840
10841 @noindent
10842 where Get_String is a C function that uses the address in Temp to
10843 modify the variable @code{Name}. This code is dubious, and arguably
10844 erroneous, and the compiler would be entitled to assume that
10845 @code{Name} is never modified, and generate code accordingly.
10846
10847 However, in practice, this would cause some existing code that
10848 seems to work with no optimization to start failing at high
10849 levels of optimzization.
10850
10851 What the compiler does for such cases is to assume that marking
10852 a variable as aliased indicates that some "funny business" may
10853 be going on. The optimizer recognizes the aliased keyword and
10854 inhibits optimizations that assume the value cannot be assigned.
10855 This means that the above example will in fact "work" reliably,
10856 that is, it will produce the expected results.
10857
10858 @ifset vms
10859 @node Coverage Analysis
10860 @subsection Coverage Analysis
10861
10862 @noindent
10863 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
10864 the user to determine the distribution of execution time across a program,
10865 @pxref{Profiling} for details of usage.
10866 @end ifset
10867
10868
10869 @node Text_IO Suggestions
10870 @section @code{Text_IO} Suggestions
10871 @cindex @code{Text_IO} and performance
10872
10873 @noindent
10874 The @code{Ada.Text_IO} package has fairly high overheads due in part to
10875 the requirement of maintaining page and line counts. If performance
10876 is critical, a recommendation is to use @code{Stream_IO} instead of
10877 @code{Text_IO} for volume output, since this package has less overhead.
10878
10879 If @code{Text_IO} must be used, note that by default output to the standard
10880 output and standard error files is unbuffered (this provides better
10881 behavior when output statements are used for debugging, or if the
10882 progress of a program is observed by tracking the output, e.g. by
10883 using the Unix @command{tail -f} command to watch redirected output.
10884
10885 If you are generating large volumes of output with @code{Text_IO} and
10886 performance is an important factor, use a designated file instead
10887 of the standard output file, or change the standard output file to
10888 be buffered using @code{Interfaces.C_Streams.setvbuf}.
10889
10890
10891
10892 @node Reducing Size of Ada Executables with gnatelim
10893 @section Reducing Size of Ada Executables with @code{gnatelim}
10894 @findex gnatelim
10895
10896 @noindent
10897 This section describes @command{gnatelim}, a tool which detects unused
10898 subprograms and helps the compiler to create a smaller executable for your
10899 program.
10900
10901 @menu
10902 * About gnatelim::
10903 * Running gnatelim::
10904 * Processing Precompiled Libraries::
10905 * Correcting the List of Eliminate Pragmas::
10906 * Making Your Executables Smaller::
10907 * Summary of the gnatelim Usage Cycle::
10908 @end menu
10909
10910 @node About gnatelim
10911 @subsection About @code{gnatelim}
10912
10913 @noindent
10914 When a program shares a set of Ada
10915 packages with other programs, it may happen that this program uses
10916 only a fraction of the subprograms defined in these packages. The code
10917 created for these unused subprograms increases the size of the executable.
10918
10919 @code{gnatelim} tracks unused subprograms in an Ada program and
10920 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
10921 subprograms that are declared but never called. By placing the list of
10922 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
10923 recompiling your program, you may decrease the size of its executable,
10924 because the compiler will not generate the code for 'eliminated' subprograms.
10925 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
10926 information about this pragma.
10927
10928 @code{gnatelim} needs as its input data the name of the main subprogram.
10929
10930 If a set of source files is specified as @code{gnatelim} arguments, it
10931 treats these files as a complete set of sources making up a program to
10932 analyse, and analyses only these sources.
10933
10934 After a full successful build of the main subprogram @code{gnatelim} can be
10935 called without specifying sources to analyse, in this case it computes
10936 the source closure of the main unit from the @file{ALI} files.
10937
10938 The following command will create the set of @file{ALI} files needed for
10939 @code{gnatelim}:
10940
10941 @smallexample
10942 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
10943 @end smallexample
10944
10945 Note that @code{gnatelim} does not need object files.
10946
10947 @node Running gnatelim
10948 @subsection Running @code{gnatelim}
10949
10950 @noindent
10951 @code{gnatelim} has the following command-line interface:
10952
10953 @smallexample
10954 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
10955 @end smallexample
10956
10957 @noindent
10958 @var{main_unit_name} should be a name of a source file that contains the main
10959 subprogram of a program (partition).
10960
10961 Each @var{filename} is the name (including the extension) of a source
10962 file to process. ``Wildcards'' are allowed, and
10963 the file name may contain path information.
10964
10965 @samp{@var{gcc_switches}} is a list of switches for
10966 @command{gcc}. They will be passed on to all compiler invocations made by
10967 @command{gnatelim} to generate the ASIS trees. Here you can provide
10968 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
10969 use the @option{-gnatec} switch to set the configuration file,
10970 use the @option{-gnat05} switch if sources should be compiled in
10971 Ada 2005 mode etc.
10972
10973 @code{gnatelim} has the following switches:
10974
10975 @table @option
10976 @c !sort!
10977 @item --version
10978 @cindex @option{--version} @command{gnatelim}
10979 Display Copyright and version, then exit disregarding all other options.
10980
10981 @item --help
10982 @cindex @option{--help} @command{gnatelim}
10983 Display usage, then exit disregarding all other options.
10984
10985 @item ^-files^/FILES^=@var{filename}
10986 @cindex @option{^-files^/FILES^} (@code{gnatelim})
10987 Take the argument source files from the specified file. This file should be an
10988 ordinary text file containing file names separated by spaces or
10989 line breaks. You can use this switch more than once in the same call to
10990 @command{gnatelim}. You also can combine this switch with
10991 an explicit list of files.
10992
10993 @item ^-log^/LOG^
10994 @cindex @option{^-log^/LOG^} (@command{gnatelim})
10995 Duplicate all the output sent to @file{stderr} into a log file. The log file
10996 is named @file{gnatelim.log} and is located in the current directory.
10997
10998 @item ^-log^/LOGFILE^=@var{filename}
10999 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
11000 Duplicate all the output sent to @file{stderr} into a specified log file.
11001
11002 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
11003 @item ^--no-elim-dispatch^/NO_DISPATCH^
11004 Do not generate pragmas for dispatching operations.
11005
11006 @item ^--ignore^/IGNORE^=@var{filename}
11007 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
11008 Do not generate pragmas for subprograms declared in the sources
11009 listed in a specified file
11010
11011 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
11012 @item ^-o^/OUTPUT^=@var{report_file}
11013 Put @command{gnatelim} output into a specified file. If this file already exists,
11014 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
11015 into @file{stderr}
11016
11017 @item ^-q^/QUIET^
11018 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
11019 Quiet mode: by default @code{gnatelim} outputs to the standard error
11020 stream the number of program units left to be processed. This option turns
11021 this trace off.
11022
11023 @cindex @option{^-t^/TIME^} (@command{gnatelim})
11024 @item ^-t^/TIME^
11025 Print out execution time.
11026
11027 @item ^-v^/VERBOSE^
11028 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
11029 Verbose mode: @code{gnatelim} version information is printed as Ada
11030 comments to the standard output stream. Also, in addition to the number of
11031 program units left @code{gnatelim} will output the name of the current unit
11032 being processed.
11033
11034 @item ^-wq^/WARNINGS=QUIET^
11035 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
11036 Quiet warning mode - some warnings are suppressed. In particular warnings that
11037 indicate that the analysed set of sources is incomplete to make up a
11038 partition and that some subprogram bodies are missing are not generated.
11039 @end table
11040
11041 @noindent
11042 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11043 driver (see @ref{The GNAT Driver and Project Files}).
11044
11045 @node Processing Precompiled Libraries
11046 @subsection Processing Precompiled Libraries
11047
11048 @noindent
11049 If some program uses a precompiled Ada library, it can be processed by
11050 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11051 Eliminate pragma for a subprogram if the body of this subprogram has not
11052 been analysed, this is a typical case for subprograms from precompiled
11053 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11054 warnings about missing source files and non-analyzed subprogram bodies
11055 that can be generated when processing precompiled Ada libraries.
11056
11057 @node Correcting the List of Eliminate Pragmas
11058 @subsection Correcting the List of Eliminate Pragmas
11059
11060 @noindent
11061 In some rare cases @code{gnatelim} may try to eliminate
11062 subprograms that are actually called in the program. In this case, the
11063 compiler will generate an error message of the form:
11064
11065 @smallexample
11066 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11067 @end smallexample
11068
11069 @noindent
11070 You will need to manually remove the wrong @code{Eliminate} pragmas from
11071 the configuration file indicated in the error message. You should recompile
11072 your program from scratch after that, because you need a consistent
11073 configuration file(s) during the entire compilation.
11074
11075 @node Making Your Executables Smaller
11076 @subsection Making Your Executables Smaller
11077
11078 @noindent
11079 In order to get a smaller executable for your program you now have to
11080 recompile the program completely with the configuration file containing
11081 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11082 @file{gnat.adc} file located in your current directory, just do:
11083
11084 @smallexample
11085 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11086 @end smallexample
11087
11088 @noindent
11089 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11090 recompile everything
11091 with the set of pragmas @code{Eliminate} that you have obtained with
11092 @command{gnatelim}).
11093
11094 Be aware that the set of @code{Eliminate} pragmas is specific to each
11095 program. It is not recommended to merge sets of @code{Eliminate}
11096 pragmas created for different programs in one configuration file.
11097
11098 @node Summary of the gnatelim Usage Cycle
11099 @subsection Summary of the @code{gnatelim} Usage Cycle
11100
11101 @noindent
11102 Here is a quick summary of the steps to be taken in order to reduce
11103 the size of your executables with @code{gnatelim}. You may use
11104 other GNAT options to control the optimization level,
11105 to produce the debugging information, to set search path, etc.
11106
11107 @enumerate
11108 @item
11109 Create a complete set of @file{ALI} files (if the program has not been
11110 built already)
11111
11112 @smallexample
11113 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11114 @end smallexample
11115
11116 @item
11117 Generate a list of @code{Eliminate} pragmas in default configuration file
11118 @file{gnat.adc} in the current directory
11119 @smallexample
11120 @ifset vms
11121 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11122 @end ifset
11123 @ifclear vms
11124 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11125 @end ifclear
11126 @end smallexample
11127
11128 @item
11129 Recompile the application
11130
11131 @smallexample
11132 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11133 @end smallexample
11134
11135 @end enumerate
11136
11137 @node Reducing Size of Executables with unused subprogram/data elimination
11138 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11139 @findex unused subprogram/data elimination
11140
11141 @noindent
11142 This section describes how you can eliminate unused subprograms and data from
11143 your executable just by setting options at compilation time.
11144
11145 @menu
11146 * About unused subprogram/data elimination::
11147 * Compilation options::
11148 * Example of unused subprogram/data elimination::
11149 @end menu
11150
11151 @node About unused subprogram/data elimination
11152 @subsection About unused subprogram/data elimination
11153
11154 @noindent
11155 By default, an executable contains all code and data of its composing objects
11156 (directly linked or coming from statically linked libraries), even data or code
11157 never used by this executable.
11158
11159 This feature will allow you to eliminate such unused code from your
11160 executable, making it smaller (in disk and in memory).
11161
11162 This functionality is available on all Linux platforms except for the IA-64
11163 architecture and on all cross platforms using the ELF binary file format.
11164 In both cases GNU binutils version 2.16 or later are required to enable it.
11165
11166 @node Compilation options
11167 @subsection Compilation options
11168
11169 @noindent
11170 The operation of eliminating the unused code and data from the final executable
11171 is directly performed by the linker.
11172
11173 In order to do this, it has to work with objects compiled with the
11174 following options:
11175 @option{-ffunction-sections} @option{-fdata-sections}.
11176 @cindex @option{-ffunction-sections} (@command{gcc})
11177 @cindex @option{-fdata-sections} (@command{gcc})
11178 These options are usable with C and Ada files.
11179 They will place respectively each
11180 function or data in a separate section in the resulting object file.
11181
11182 Once the objects and static libraries are created with these options, the
11183 linker can perform the dead code elimination. You can do this by setting
11184 the @option{-Wl,--gc-sections} option to gcc command or in the
11185 @option{-largs} section of @command{gnatmake}. This will perform a
11186 garbage collection of code and data never referenced.
11187
11188 If the linker performs a partial link (@option{-r} ld linker option), then you
11189 will need to provide one or several entry point using the
11190 @option{-e} / @option{--entry} ld option.
11191
11192 Note that objects compiled without the @option{-ffunction-sections} and
11193 @option{-fdata-sections} options can still be linked with the executable.
11194 However, no dead code elimination will be performed on those objects (they will
11195 be linked as is).
11196
11197 The GNAT static library is now compiled with -ffunction-sections and
11198 -fdata-sections on some platforms. This allows you to eliminate the unused code
11199 and data of the GNAT library from your executable.
11200
11201 @node Example of unused subprogram/data elimination
11202 @subsection Example of unused subprogram/data elimination
11203
11204 @noindent
11205 Here is a simple example:
11206
11207 @smallexample @c ada
11208 with Aux;
11209
11210 procedure Test is
11211 begin
11212 Aux.Used (10);
11213 end Test;
11214
11215 package Aux is
11216 Used_Data : Integer;
11217 Unused_Data : Integer;
11218
11219 procedure Used (Data : Integer);
11220 procedure Unused (Data : Integer);
11221 end Aux;
11222
11223 package body Aux is
11224 procedure Used (Data : Integer) is
11225 begin
11226 Used_Data := Data;
11227 end Used;
11228
11229 procedure Unused (Data : Integer) is
11230 begin
11231 Unused_Data := Data;
11232 end Unused;
11233 end Aux;
11234 @end smallexample
11235
11236 @noindent
11237 @code{Unused} and @code{Unused_Data} are never referenced in this code
11238 excerpt, and hence they may be safely removed from the final executable.
11239
11240 @smallexample
11241 $ gnatmake test
11242
11243 $ nm test | grep used
11244 020015f0 T aux__unused
11245 02005d88 B aux__unused_data
11246 020015cc T aux__used
11247 02005d84 B aux__used_data
11248
11249 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11250 -largs -Wl,--gc-sections
11251
11252 $ nm test | grep used
11253 02005350 T aux__used
11254 0201ffe0 B aux__used_data
11255 @end smallexample
11256
11257 @noindent
11258 It can be observed that the procedure @code{Unused} and the object
11259 @code{Unused_Data} are removed by the linker when using the
11260 appropriate options.
11261
11262 @c ********************************
11263 @node Renaming Files with gnatchop
11264 @chapter Renaming Files with @code{gnatchop}
11265 @findex gnatchop
11266
11267 @noindent
11268 This chapter discusses how to handle files with multiple units by using
11269 the @code{gnatchop} utility. This utility is also useful in renaming
11270 files to meet the standard GNAT default file naming conventions.
11271
11272 @menu
11273 * Handling Files with Multiple Units::
11274 * Operating gnatchop in Compilation Mode::
11275 * Command Line for gnatchop::
11276 * Switches for gnatchop::
11277 * Examples of gnatchop Usage::
11278 @end menu
11279
11280 @node Handling Files with Multiple Units
11281 @section Handling Files with Multiple Units
11282
11283 @noindent
11284 The basic compilation model of GNAT requires that a file submitted to the
11285 compiler have only one unit and there be a strict correspondence
11286 between the file name and the unit name.
11287
11288 The @code{gnatchop} utility allows both of these rules to be relaxed,
11289 allowing GNAT to process files which contain multiple compilation units
11290 and files with arbitrary file names. @code{gnatchop}
11291 reads the specified file and generates one or more output files,
11292 containing one unit per file. The unit and the file name correspond,
11293 as required by GNAT.
11294
11295 If you want to permanently restructure a set of ``foreign'' files so that
11296 they match the GNAT rules, and do the remaining development using the
11297 GNAT structure, you can simply use @command{gnatchop} once, generate the
11298 new set of files and work with them from that point on.
11299
11300 Alternatively, if you want to keep your files in the ``foreign'' format,
11301 perhaps to maintain compatibility with some other Ada compilation
11302 system, you can set up a procedure where you use @command{gnatchop} each
11303 time you compile, regarding the source files that it writes as temporary
11304 files that you throw away.
11305
11306 Note that if your file containing multiple units starts with a byte order
11307 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11308 will each start with a copy of this BOM, meaning that they can be compiled
11309 automatically in UTF-8 mode without needing to specify an explicit encoding.
11310
11311 @node Operating gnatchop in Compilation Mode
11312 @section Operating gnatchop in Compilation Mode
11313
11314 @noindent
11315 The basic function of @code{gnatchop} is to take a file with multiple units
11316 and split it into separate files. The boundary between files is reasonably
11317 clear, except for the issue of comments and pragmas. In default mode, the
11318 rule is that any pragmas between units belong to the previous unit, except
11319 that configuration pragmas always belong to the following unit. Any comments
11320 belong to the following unit. These rules
11321 almost always result in the right choice of
11322 the split point without needing to mark it explicitly and most users will
11323 find this default to be what they want. In this default mode it is incorrect to
11324 submit a file containing only configuration pragmas, or one that ends in
11325 configuration pragmas, to @code{gnatchop}.
11326
11327 However, using a special option to activate ``compilation mode'',
11328 @code{gnatchop}
11329 can perform another function, which is to provide exactly the semantics
11330 required by the RM for handling of configuration pragmas in a compilation.
11331 In the absence of configuration pragmas (at the main file level), this
11332 option has no effect, but it causes such configuration pragmas to be handled
11333 in a quite different manner.
11334
11335 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11336 only configuration pragmas, then this file is appended to the
11337 @file{gnat.adc} file in the current directory. This behavior provides
11338 the required behavior described in the RM for the actions to be taken
11339 on submitting such a file to the compiler, namely that these pragmas
11340 should apply to all subsequent compilations in the same compilation
11341 environment. Using GNAT, the current directory, possibly containing a
11342 @file{gnat.adc} file is the representation
11343 of a compilation environment. For more information on the
11344 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11345
11346 Second, in compilation mode, if @code{gnatchop}
11347 is given a file that starts with
11348 configuration pragmas, and contains one or more units, then these
11349 configuration pragmas are prepended to each of the chopped files. This
11350 behavior provides the required behavior described in the RM for the
11351 actions to be taken on compiling such a file, namely that the pragmas
11352 apply to all units in the compilation, but not to subsequently compiled
11353 units.
11354
11355 Finally, if configuration pragmas appear between units, they are appended
11356 to the previous unit. This results in the previous unit being illegal,
11357 since the compiler does not accept configuration pragmas that follow
11358 a unit. This provides the required RM behavior that forbids configuration
11359 pragmas other than those preceding the first compilation unit of a
11360 compilation.
11361
11362 For most purposes, @code{gnatchop} will be used in default mode. The
11363 compilation mode described above is used only if you need exactly
11364 accurate behavior with respect to compilations, and you have files
11365 that contain multiple units and configuration pragmas. In this
11366 circumstance the use of @code{gnatchop} with the compilation mode
11367 switch provides the required behavior, and is for example the mode
11368 in which GNAT processes the ACVC tests.
11369
11370 @node Command Line for gnatchop
11371 @section Command Line for @code{gnatchop}
11372
11373 @noindent
11374 The @code{gnatchop} command has the form:
11375
11376 @smallexample
11377 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11378 @c @ovar{directory}
11379 @c Expanding @ovar macro inline (explanation in macro def comments)
11380 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11381 @r{[}@var{directory}@r{]}
11382 @end smallexample
11383
11384 @noindent
11385 The only required argument is the file name of the file to be chopped.
11386 There are no restrictions on the form of this file name. The file itself
11387 contains one or more Ada units, in normal GNAT format, concatenated
11388 together. As shown, more than one file may be presented to be chopped.
11389
11390 When run in default mode, @code{gnatchop} generates one output file in
11391 the current directory for each unit in each of the files.
11392
11393 @var{directory}, if specified, gives the name of the directory to which
11394 the output files will be written. If it is not specified, all files are
11395 written to the current directory.
11396
11397 For example, given a
11398 file called @file{hellofiles} containing
11399
11400 @smallexample @c ada
11401 @group
11402 @cartouche
11403 procedure hello;
11404
11405 with Text_IO; use Text_IO;
11406 procedure hello is
11407 begin
11408 Put_Line ("Hello");
11409 end hello;
11410 @end cartouche
11411 @end group
11412 @end smallexample
11413
11414 @noindent
11415 the command
11416
11417 @smallexample
11418 $ gnatchop ^hellofiles^HELLOFILES.^
11419 @end smallexample
11420
11421 @noindent
11422 generates two files in the current directory, one called
11423 @file{hello.ads} containing the single line that is the procedure spec,
11424 and the other called @file{hello.adb} containing the remaining text. The
11425 original file is not affected. The generated files can be compiled in
11426 the normal manner.
11427
11428 @noindent
11429 When gnatchop is invoked on a file that is empty or that contains only empty
11430 lines and/or comments, gnatchop will not fail, but will not produce any
11431 new sources.
11432
11433 For example, given a
11434 file called @file{toto.txt} containing
11435
11436 @smallexample @c ada
11437 @group
11438 @cartouche
11439 -- Just a comment
11440 @end cartouche
11441 @end group
11442 @end smallexample
11443
11444 @noindent
11445 the command
11446
11447 @smallexample
11448 $ gnatchop ^toto.txt^TOT.TXT^
11449 @end smallexample
11450
11451 @noindent
11452 will not produce any new file and will result in the following warnings:
11453
11454 @smallexample
11455 toto.txt:1:01: warning: empty file, contains no compilation units
11456 no compilation units found
11457 no source files written
11458 @end smallexample
11459
11460 @node Switches for gnatchop
11461 @section Switches for @code{gnatchop}
11462
11463 @noindent
11464 @command{gnatchop} recognizes the following switches:
11465
11466 @table @option
11467 @c !sort!
11468
11469 @item --version
11470 @cindex @option{--version} @command{gnatchop}
11471 Display Copyright and version, then exit disregarding all other options.
11472
11473 @item --help
11474 @cindex @option{--help} @command{gnatchop}
11475 If @option{--version} was not used, display usage, then exit disregarding
11476 all other options.
11477
11478 @item ^-c^/COMPILATION^
11479 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11480 Causes @code{gnatchop} to operate in compilation mode, in which
11481 configuration pragmas are handled according to strict RM rules. See
11482 previous section for a full description of this mode.
11483
11484 @ifclear vms
11485 @item -gnat@var{xxx}
11486 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11487 used to parse the given file. Not all @var{xxx} options make sense,
11488 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11489 process a source file that uses Latin-2 coding for identifiers.
11490 @end ifclear
11491
11492 @item ^-h^/HELP^
11493 Causes @code{gnatchop} to generate a brief help summary to the standard
11494 output file showing usage information.
11495
11496 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11497 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11498 Limit generated file names to the specified number @code{mm}
11499 of characters.
11500 This is useful if the
11501 resulting set of files is required to be interoperable with systems
11502 which limit the length of file names.
11503 @ifset vms
11504 If no value is given, or
11505 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11506 a default of 39, suitable for OpenVMS Alpha
11507 Systems, is assumed
11508 @end ifset
11509 @ifclear vms
11510 No space is allowed between the @option{-k} and the numeric value. The numeric
11511 value may be omitted in which case a default of @option{-k8},
11512 suitable for use
11513 with DOS-like file systems, is used. If no @option{-k} switch
11514 is present then
11515 there is no limit on the length of file names.
11516 @end ifclear
11517
11518 @item ^-p^/PRESERVE^
11519 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11520 Causes the file ^modification^creation^ time stamp of the input file to be
11521 preserved and used for the time stamp of the output file(s). This may be
11522 useful for preserving coherency of time stamps in an environment where
11523 @code{gnatchop} is used as part of a standard build process.
11524
11525 @item ^-q^/QUIET^
11526 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11527 Causes output of informational messages indicating the set of generated
11528 files to be suppressed. Warnings and error messages are unaffected.
11529
11530 @item ^-r^/REFERENCE^
11531 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
11532 @findex Source_Reference
11533 Generate @code{Source_Reference} pragmas. Use this switch if the output
11534 files are regarded as temporary and development is to be done in terms
11535 of the original unchopped file. This switch causes
11536 @code{Source_Reference} pragmas to be inserted into each of the
11537 generated files to refers back to the original file name and line number.
11538 The result is that all error messages refer back to the original
11539 unchopped file.
11540 In addition, the debugging information placed into the object file (when
11541 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
11542 specified)
11543 also refers back to this original file so that tools like profilers and
11544 debuggers will give information in terms of the original unchopped file.
11545
11546 If the original file to be chopped itself contains
11547 a @code{Source_Reference}
11548 pragma referencing a third file, then gnatchop respects
11549 this pragma, and the generated @code{Source_Reference} pragmas
11550 in the chopped file refer to the original file, with appropriate
11551 line numbers. This is particularly useful when @code{gnatchop}
11552 is used in conjunction with @code{gnatprep} to compile files that
11553 contain preprocessing statements and multiple units.
11554
11555 @item ^-v^/VERBOSE^
11556 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
11557 Causes @code{gnatchop} to operate in verbose mode. The version
11558 number and copyright notice are output, as well as exact copies of
11559 the gnat1 commands spawned to obtain the chop control information.
11560
11561 @item ^-w^/OVERWRITE^
11562 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
11563 Overwrite existing file names. Normally @code{gnatchop} regards it as a
11564 fatal error if there is already a file with the same name as a
11565 file it would otherwise output, in other words if the files to be
11566 chopped contain duplicated units. This switch bypasses this
11567 check, and causes all but the last instance of such duplicated
11568 units to be skipped.
11569
11570 @ifclear vms
11571 @item --GCC=@var{xxxx}
11572 @cindex @option{--GCC=} (@code{gnatchop})
11573 Specify the path of the GNAT parser to be used. When this switch is used,
11574 no attempt is made to add the prefix to the GNAT parser executable.
11575 @end ifclear
11576 @end table
11577
11578 @node Examples of gnatchop Usage
11579 @section Examples of @code{gnatchop} Usage
11580
11581 @table @code
11582 @ifset vms
11583 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
11584 @end ifset
11585 @ifclear vms
11586 @item gnatchop -w hello_s.ada prerelease/files
11587 @end ifclear
11588
11589 Chops the source file @file{hello_s.ada}. The output files will be
11590 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
11591 overwriting any
11592 files with matching names in that directory (no files in the current
11593 directory are modified).
11594
11595 @item gnatchop ^archive^ARCHIVE.^
11596 Chops the source file @file{^archive^ARCHIVE.^}
11597 into the current directory. One
11598 useful application of @code{gnatchop} is in sending sets of sources
11599 around, for example in email messages. The required sources are simply
11600 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
11601 command), and then
11602 @command{gnatchop} is used at the other end to reconstitute the original
11603 file names.
11604
11605 @item gnatchop file1 file2 file3 direc
11606 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
11607 the resulting files in the directory @file{direc}. Note that if any units
11608 occur more than once anywhere within this set of files, an error message
11609 is generated, and no files are written. To override this check, use the
11610 @option{^-w^/OVERWRITE^} switch,
11611 in which case the last occurrence in the last file will
11612 be the one that is output, and earlier duplicate occurrences for a given
11613 unit will be skipped.
11614 @end table
11615
11616 @node Configuration Pragmas
11617 @chapter Configuration Pragmas
11618 @cindex Configuration pragmas
11619 @cindex Pragmas, configuration
11620
11621 @menu
11622 * Handling of Configuration Pragmas::
11623 * The Configuration Pragmas Files::
11624 @end menu
11625
11626 @noindent
11627 Configuration pragmas include those pragmas described as
11628 such in the Ada Reference Manual, as well as
11629 implementation-dependent pragmas that are configuration pragmas.
11630 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
11631 for details on these additional GNAT-specific configuration pragmas.
11632 Most notably, the pragma @code{Source_File_Name}, which allows
11633 specifying non-default names for source files, is a configuration
11634 pragma. The following is a complete list of configuration pragmas
11635 recognized by GNAT:
11636
11637 @smallexample
11638 Ada_83
11639 Ada_95
11640 Ada_05
11641 Ada_2005
11642 Ada_12
11643 Ada_2012
11644 Annotate
11645 Assertion_Policy
11646 Assume_No_Invalid_Values
11647 C_Pass_By_Copy
11648 Check_Name
11649 Check_Policy
11650 Compile_Time_Error
11651 Compile_Time_Warning
11652 Compiler_Unit
11653 Component_Alignment
11654 Convention_Identifier
11655 Debug_Policy
11656 Detect_Blocking
11657 Default_Storage_Pool
11658 Discard_Names
11659 Elaboration_Checks
11660 Eliminate
11661 Extend_System
11662 Extensions_Allowed
11663 External_Name_Casing
11664 Fast_Math
11665 Favor_Top_Level
11666 Float_Representation
11667 Implicit_Packing
11668 Initialize_Scalars
11669 Interrupt_State
11670 License
11671 Locking_Policy
11672 Long_Float
11673 No_Run_Time
11674 No_Strict_Aliasing
11675 Normalize_Scalars
11676 Optimize_Alignment
11677 Persistent_BSS
11678 Polling
11679 Priority_Specific_Dispatching
11680 Profile
11681 Profile_Warnings
11682 Propagate_Exceptions
11683 Queuing_Policy
11684 Ravenscar
11685 Restricted_Run_Time
11686 Restrictions
11687 Restrictions_Warnings
11688 Reviewable
11689 Short_Circuit_And_Or
11690 Source_File_Name
11691 Source_File_Name_Project
11692 SPARK_Mode
11693 Style_Checks
11694 Suppress
11695 Suppress_Exception_Locations
11696 Task_Dispatching_Policy
11697 Universal_Data
11698 Unsuppress
11699 Use_VADS_Size
11700 Validity_Checks
11701 Warnings
11702 Wide_Character_Encoding
11703 @end smallexample
11704
11705 @node Handling of Configuration Pragmas
11706 @section Handling of Configuration Pragmas
11707
11708 Configuration pragmas may either appear at the start of a compilation
11709 unit, or they can appear in a configuration pragma file to apply to
11710 all compilations performed in a given compilation environment.
11711
11712 GNAT also provides the @code{gnatchop} utility to provide an automatic
11713 way to handle configuration pragmas following the semantics for
11714 compilations (that is, files with multiple units), described in the RM.
11715 See @ref{Operating gnatchop in Compilation Mode} for details.
11716 However, for most purposes, it will be more convenient to edit the
11717 @file{gnat.adc} file that contains configuration pragmas directly,
11718 as described in the following section.
11719
11720 In the case of @code{Restrictions} pragmas appearing as configuration
11721 pragmas in individual compilation units, the exact handling depends on
11722 the type of restriction.
11723
11724 Restrictions that require partition-wide consistency (like
11725 @code{No_Tasking}) are
11726 recognized wherever they appear
11727 and can be freely inherited, e.g. from a with'ed unit to the with'ing
11728 unit. This makes sense since the binder will in any case insist on seeing
11729 consistent use, so any unit not conforming to any restrictions that are
11730 anywhere in the partition will be rejected, and you might as well find
11731 that out at compile time rather than at bind time.
11732
11733 For restrictions that do not require partition-wide consistency, e.g.
11734 SPARK or No_Implementation_Attributes, in general the restriction applies
11735 only to the unit in which the pragma appears, and not to any other units.
11736
11737 The exception is No_Elaboration_Code which always applies to the entire
11738 object file from a compilation, i.e. to the body, spec, and all subunits.
11739 This restriction can be specified in a configuration pragma file, or it
11740 can be on the body and/or the spec (in eithe case it applies to all the
11741 relevant units). It can appear on a subunit only if it has previously
11742 appeared in the body of spec.
11743
11744 @node The Configuration Pragmas Files
11745 @section The Configuration Pragmas Files
11746 @cindex @file{gnat.adc}
11747
11748 @noindent
11749 In GNAT a compilation environment is defined by the current
11750 directory at the time that a compile command is given. This current
11751 directory is searched for a file whose name is @file{gnat.adc}. If
11752 this file is present, it is expected to contain one or more
11753 configuration pragmas that will be applied to the current compilation.
11754 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
11755 considered.
11756
11757 Configuration pragmas may be entered into the @file{gnat.adc} file
11758 either by running @code{gnatchop} on a source file that consists only of
11759 configuration pragmas, or more conveniently by
11760 direct editing of the @file{gnat.adc} file, which is a standard format
11761 source file.
11762
11763 In addition to @file{gnat.adc}, additional files containing configuration
11764 pragmas may be applied to the current compilation using the switch
11765 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
11766 contains only configuration pragmas. These configuration pragmas are
11767 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
11768 is present and switch @option{-gnatA} is not used).
11769
11770 It is allowed to specify several switches @option{-gnatec}, all of which
11771 will be taken into account.
11772
11773 If you are using project file, a separate mechanism is provided using
11774 project attributes, see @ref{Specifying Configuration Pragmas} for more
11775 details.
11776
11777 @ifset vms
11778 Of special interest to GNAT OpenVMS Alpha is the following
11779 configuration pragma:
11780
11781 @smallexample @c ada
11782 @cartouche
11783 pragma Extend_System (Aux_DEC);
11784 @end cartouche
11785 @end smallexample
11786
11787 @noindent
11788 In the presence of this pragma, GNAT adds to the definition of the
11789 predefined package SYSTEM all the additional types and subprograms that are
11790 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
11791 @end ifset
11792
11793 @node Handling Arbitrary File Naming Conventions with gnatname
11794 @chapter Handling Arbitrary File Naming Conventions with @code{gnatname}
11795 @cindex Arbitrary File Naming Conventions
11796
11797 @menu
11798 * Arbitrary File Naming Conventions::
11799 * Running gnatname::
11800 * Switches for gnatname::
11801 * Examples of gnatname Usage::
11802 @end menu
11803
11804 @node Arbitrary File Naming Conventions
11805 @section Arbitrary File Naming Conventions
11806
11807 @noindent
11808 The GNAT compiler must be able to know the source file name of a compilation
11809 unit. When using the standard GNAT default file naming conventions
11810 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
11811 does not need additional information.
11812
11813 @noindent
11814 When the source file names do not follow the standard GNAT default file naming
11815 conventions, the GNAT compiler must be given additional information through
11816 a configuration pragmas file (@pxref{Configuration Pragmas})
11817 or a project file.
11818 When the non-standard file naming conventions are well-defined,
11819 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
11820 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
11821 if the file naming conventions are irregular or arbitrary, a number
11822 of pragma @code{Source_File_Name} for individual compilation units
11823 must be defined.
11824 To help maintain the correspondence between compilation unit names and
11825 source file names within the compiler,
11826 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
11827 set of files.
11828
11829 @node Running gnatname
11830 @section Running @code{gnatname}
11831
11832 @noindent
11833 The usual form of the @code{gnatname} command is
11834
11835 @smallexample
11836 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
11837 @c @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
11838 @c Expanding @ovar macro inline (explanation in macro def comments)
11839 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
11840 @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
11841 @end smallexample
11842
11843 @noindent
11844 All of the arguments are optional. If invoked without any argument,
11845 @code{gnatname} will display its usage.
11846
11847 @noindent
11848 When used with at least one naming pattern, @code{gnatname} will attempt to
11849 find all the compilation units in files that follow at least one of the
11850 naming patterns. To find these compilation units,
11851 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
11852 regular files.
11853
11854 @noindent
11855 One or several Naming Patterns may be given as arguments to @code{gnatname}.
11856 Each Naming Pattern is enclosed between double quotes (or single
11857 quotes on Windows).
11858 A Naming Pattern is a regular expression similar to the wildcard patterns
11859 used in file names by the Unix shells or the DOS prompt.
11860
11861 @noindent
11862 @code{gnatname} may be called with several sections of directories/patterns.
11863 Sections are separated by switch @code{--and}. In each section, there must be
11864 at least one pattern. If no directory is specified in a section, the current
11865 directory (or the project directory is @code{-P} is used) is implied.
11866 The options other that the directory switches and the patterns apply globally
11867 even if they are in different sections.
11868
11869 @noindent
11870 Examples of Naming Patterns are
11871
11872 @smallexample
11873 "*.[12].ada"
11874 "*.ad[sb]*"
11875 "body_*" "spec_*"
11876 @end smallexample
11877
11878 @noindent
11879 For a more complete description of the syntax of Naming Patterns,
11880 see the second kind of regular expressions described in @file{g-regexp.ads}
11881 (the ``Glob'' regular expressions).
11882
11883 @noindent
11884 When invoked with no switch @code{-P}, @code{gnatname} will create a
11885 configuration pragmas file @file{gnat.adc} in the current working directory,
11886 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
11887 unit.
11888
11889 @node Switches for gnatname
11890 @section Switches for @code{gnatname}
11891
11892 @noindent
11893 Switches for @code{gnatname} must precede any specified Naming Pattern.
11894
11895 @noindent
11896 You may specify any of the following switches to @code{gnatname}:
11897
11898 @table @option
11899 @c !sort!
11900
11901 @item --version
11902 @cindex @option{--version} @command{gnatname}
11903 Display Copyright and version, then exit disregarding all other options.
11904
11905 @item --help
11906 @cindex @option{--help} @command{gnatname}
11907 If @option{--version} was not used, display usage, then exit disregarding
11908 all other options.
11909
11910 @item --subdirs=<dir>
11911 Real object, library or exec directories are subdirectories <dir> of the
11912 specified ones.
11913
11914 @item --no-backup
11915 Do not create a backup copy of an existing project file.
11916
11917 @item --and
11918 Start another section of directories/patterns.
11919
11920 @item ^-c^/CONFIG_FILE=^@file{file}
11921 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
11922 Create a configuration pragmas file @file{file} (instead of the default
11923 @file{gnat.adc}).
11924 @ifclear vms
11925 There may be zero, one or more space between @option{-c} and
11926 @file{file}.
11927 @end ifclear
11928 @file{file} may include directory information. @file{file} must be
11929 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
11930 When a switch @option{^-c^/CONFIG_FILE^} is
11931 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
11932
11933 @item ^-d^/SOURCE_DIRS=^@file{dir}
11934 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
11935 Look for source files in directory @file{dir}. There may be zero, one or more
11936 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
11937 @file{dir} may end with @code{/**}, that is it may be of the form
11938 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
11939 subdirectories, recursively, have to be searched for sources.
11940 When a switch @option{^-d^/SOURCE_DIRS^}
11941 is specified, the current working directory will not be searched for source
11942 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
11943 or @option{^-D^/DIR_FILES^} switch.
11944 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
11945 If @file{dir} is a relative path, it is relative to the directory of
11946 the configuration pragmas file specified with switch
11947 @option{^-c^/CONFIG_FILE^},
11948 or to the directory of the project file specified with switch
11949 @option{^-P^/PROJECT_FILE^} or,
11950 if neither switch @option{^-c^/CONFIG_FILE^}
11951 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
11952 current working directory. The directory
11953 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
11954
11955 @item ^-D^/DIRS_FILE=^@file{file}
11956 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
11957 Look for source files in all directories listed in text file @file{file}.
11958 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
11959 and @file{file}.
11960 @file{file} must be an existing, readable text file.
11961 Each nonempty line in @file{file} must be a directory.
11962 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
11963 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
11964 @file{file}.
11965
11966 @item -eL
11967 Follow symbolic links when processing project files.
11968
11969 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
11970 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
11971 Foreign patterns. Using this switch, it is possible to add sources of languages
11972 other than Ada to the list of sources of a project file.
11973 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
11974 For example,
11975 @smallexample
11976 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
11977 @end smallexample
11978 @noindent
11979 will look for Ada units in all files with the @file{.ada} extension,
11980 and will add to the list of file for project @file{prj.gpr} the C files
11981 with extension @file{.^c^C^}.
11982
11983 @item ^-h^/HELP^
11984 @cindex @option{^-h^/HELP^} (@code{gnatname})
11985 Output usage (help) information. The output is written to @file{stdout}.
11986
11987 @item ^-P^/PROJECT_FILE=^@file{proj}
11988 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
11989 Create or update project file @file{proj}. There may be zero, one or more space
11990 between @option{-P} and @file{proj}. @file{proj} may include directory
11991 information. @file{proj} must be writable.
11992 There may be only one switch @option{^-P^/PROJECT_FILE^}.
11993 When a switch @option{^-P^/PROJECT_FILE^} is specified,
11994 no switch @option{^-c^/CONFIG_FILE^} may be specified.
11995 On all platforms, except on VMS, when @code{gnatname} is invoked for an
11996 existing project file <proj>.gpr, a backup copy of the project file is created
11997 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
11998 non negative number that makes this backup copy a new file.
11999
12000 @item ^-v^/VERBOSE^
12001 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
12002 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
12003 This includes name of the file written, the name of the directories to search
12004 and, for each file in those directories whose name matches at least one of
12005 the Naming Patterns, an indication of whether the file contains a unit,
12006 and if so the name of the unit.
12007
12008 @item ^-v -v^/VERBOSE /VERBOSE^
12009 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
12010 Very Verbose mode. In addition to the output produced in verbose mode,
12011 for each file in the searched directories whose name matches none of
12012 the Naming Patterns, an indication is given that there is no match.
12013
12014 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
12015 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
12016 Excluded patterns. Using this switch, it is possible to exclude some files
12017 that would match the name patterns. For example,
12018 @smallexample
12019 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
12020 @end smallexample
12021 @noindent
12022 will look for Ada units in all files with the @file{.ada} extension,
12023 except those whose names end with @file{_nt.ada}.
12024
12025 @end table
12026
12027 @node Examples of gnatname Usage
12028 @section Examples of @code{gnatname} Usage
12029
12030 @ifset vms
12031 @smallexample
12032 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
12033 @end smallexample
12034 @end ifset
12035
12036 @ifclear vms
12037 @smallexample
12038 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
12039 @end smallexample
12040 @end ifclear
12041
12042 @noindent
12043 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
12044 and be writable. In addition, the directory
12045 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
12046 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
12047
12048 @ifclear vms
12049 Note the optional spaces after @option{-c} and @option{-d}.
12050 @end ifclear
12051
12052 @smallexample
12053 @ifclear vms
12054 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
12055 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12056 @end ifclear
12057 @ifset vms
12058 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
12059 /EXCLUDED_PATTERN=*_nt_body.ada
12060 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
12061 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
12062 @end ifset
12063 @end smallexample
12064
12065 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
12066 even in conjunction with one or several switches
12067 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
12068 are used in this example.
12069
12070 @c *****************************************
12071 @c * G N A T P r o j e c t M a n a g e r *
12072 @c *****************************************
12073
12074 @c ------ macros for projects.texi
12075 @c These macros are needed when building the gprbuild documentation, but
12076 @c should have no effect in the gnat user's guide
12077
12078 @macro CODESAMPLE{TXT}
12079 @smallexample
12080 @group
12081 \TXT\
12082 @end group
12083 @end smallexample
12084 @end macro
12085
12086 @macro PROJECTFILE{TXT}
12087 @CODESAMPLE{\TXT\}
12088 @end macro
12089
12090 @c simulates a newline when in a @CODESAMPLE
12091 @macro NL{}
12092 @end macro
12093
12094 @macro TIP{TXT}
12095 @quotation
12096 @noindent
12097 \TXT\
12098 @end quotation
12099 @end macro
12100
12101 @macro TIPHTML{TXT}
12102 \TXT\
12103 @end macro
12104
12105 @macro IMPORTANT{TXT}
12106 @quotation
12107 @noindent
12108 \TXT\
12109 @end quotation
12110
12111 @end macro
12112
12113 @macro NOTE{TXT}
12114 @quotation
12115 @noindent
12116 \TXT\
12117 @end quotation
12118 @end macro
12119
12120 @include projects.texi
12121
12122 @c ---------------------------------------------
12123 @c Tools Supporting Project Files
12124 @c ---------------------------------------------
12125
12126 @node Tools Supporting Project Files
12127 @chapter Tools Supporting Project Files
12128
12129 @noindent
12130
12131 @menu
12132 * gnatmake and Project Files::
12133 * The GNAT Driver and Project Files::
12134 @end menu
12135
12136 @c ---------------------------------------------
12137 @node gnatmake and Project Files
12138 @section gnatmake and Project Files
12139 @c ---------------------------------------------
12140
12141 @noindent
12142 This section covers several topics related to @command{gnatmake} and
12143 project files: defining ^switches^switches^ for @command{gnatmake}
12144 and for the tools that it invokes; specifying configuration pragmas;
12145 the use of the @code{Main} attribute; building and rebuilding library project
12146 files.
12147
12148 @menu
12149 * Switches Related to Project Files::
12150 * Switches and Project Files::
12151 * Specifying Configuration Pragmas::
12152 * Project Files and Main Subprograms::
12153 * Library Project Files::
12154 @end menu
12155
12156 @c ---------------------------------------------
12157 @node Switches Related to Project Files
12158 @subsection Switches Related to Project Files
12159 @c ---------------------------------------------
12160
12161 @noindent
12162 The following switches are used by GNAT tools that support project files:
12163
12164 @table @option
12165
12166 @item ^-P^/PROJECT_FILE=^@var{project}
12167 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
12168 Indicates the name of a project file. This project file will be parsed with
12169 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12170 if any, and using the external references indicated
12171 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12172 @ifclear vms
12173 There may zero, one or more spaces between @option{-P} and @var{project}.
12174 @end ifclear
12175
12176 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12177
12178 Since the Project Manager parses the project file only after all the switches
12179 on the command line are checked, the order of the switches
12180 @option{^-P^/PROJECT_FILE^},
12181 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12182 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12183
12184 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12185 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
12186 Indicates that external variable @var{name} has the value @var{value}.
12187 The Project Manager will use this value for occurrences of
12188 @code{external(name)} when parsing the project file.
12189
12190 @ifclear vms
12191 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12192 put between quotes.
12193 @smallexample
12194 -XOS=NT
12195 -X"user=John Doe"
12196 @end smallexample
12197 @end ifclear
12198
12199 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12200 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12201 @var{name}, only the last one is used.
12202
12203 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12204 takes precedence over the value of the same name in the environment.
12205
12206 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12207 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
12208 Indicates the verbosity of the parsing of GNAT project files.
12209
12210 @ifclear vms
12211 @option{-vP0} means Default;
12212 @option{-vP1} means Medium;
12213 @option{-vP2} means High.
12214 @end ifclear
12215
12216 @ifset vms
12217 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12218 HIGH.
12219 @end ifset
12220
12221 The default is ^Default^DEFAULT^: no output for syntactically correct
12222 project files.
12223 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12224 only the last one is used.
12225
12226 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
12227 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
12228 Add directory <dir> at the beginning of the project search path, in order,
12229 after the current working directory.
12230
12231 @ifclear vms
12232 @item -eL
12233 @cindex @option{-eL} (any project-aware tool)
12234 Follow all symbolic links when processing project files.
12235 @end ifclear
12236
12237 @item ^--subdirs^/SUBDIRS^=<subdir>
12238 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
12239 This switch is recognized by @command{gnatmake} and @command{gnatclean}. It
12240 indicate that the real directories (except the source directories) are the
12241 subdirectories <subdir> of the directories specified in the project files.
12242 This applies in particular to object directories, library directories and
12243 exec directories. If the subdirectories do not exist, they are created
12244 automatically.
12245
12246 @end table
12247
12248 @c ---------------------------------------------
12249 @node Switches and Project Files
12250 @subsection Switches and Project Files
12251 @c ---------------------------------------------
12252
12253 @noindent
12254 @ifset vms
12255 It is not currently possible to specify VMS style qualifiers in the project
12256 files; only Unix style ^switches^switches^ may be specified.
12257 @end ifset
12258
12259 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12260 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12261 attribute, a @code{Switches} attribute, or both;
12262 as their names imply, these ^switch^switch^-related
12263 attributes affect the ^switches^switches^ that are used for each of these GNAT
12264 components when
12265 @command{gnatmake} is invoked. As will be explained below, these
12266 component-specific ^switches^switches^ precede
12267 the ^switches^switches^ provided on the @command{gnatmake} command line.
12268
12269 The @code{^Default_Switches^Default_Switches^} attribute is an attribute
12270 indexed by language name (case insensitive) whose value is a string list.
12271 For example:
12272
12273 @smallexample @c projectfile
12274 @group
12275 package Compiler is
12276 for ^Default_Switches^Default_Switches^ ("Ada")
12277 use ("^-gnaty^-gnaty^",
12278 "^-v^-v^");
12279 end Compiler;
12280 @end group
12281 @end smallexample
12282
12283 @noindent
12284 The @code{Switches} attribute is indexed on a file name (which may or may
12285 not be case sensitive, depending
12286 on the operating system) whose value is a string list. For example:
12287
12288 @smallexample @c projectfile
12289 @group
12290 package Builder is
12291 for Switches ("main1.adb")
12292 use ("^-O2^-O2^");
12293 for Switches ("main2.adb")
12294 use ("^-g^-g^");
12295 end Builder;
12296 @end group
12297 @end smallexample
12298
12299 @noindent
12300 For the @code{Builder} package, the file names must designate source files
12301 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
12302 file names must designate @file{ALI} or source files for main subprograms.
12303 In each case just the file name without an explicit extension is acceptable.
12304
12305 For each tool used in a program build (@command{gnatmake}, the compiler, the
12306 binder, and the linker), the corresponding package @dfn{contributes} a set of
12307 ^switches^switches^ for each file on which the tool is invoked, based on the
12308 ^switch^switch^-related attributes defined in the package.
12309 In particular, the ^switches^switches^
12310 that each of these packages contributes for a given file @var{f} comprise:
12311
12312 @itemize @bullet
12313 @item the value of attribute @code{Switches (@var{f})},
12314 if it is specified in the package for the given file,
12315 @item otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12316 if it is specified in the package.
12317
12318 @end itemize
12319
12320 @noindent
12321 If neither of these attributes is defined in the package, then the package does
12322 not contribute any ^switches^switches^ for the given file.
12323
12324 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12325 two sets, in the following order: those contributed for the file
12326 by the @code{Builder} package;
12327 and the switches passed on the command line.
12328
12329 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12330 the ^switches^switches^ passed to the tool comprise three sets,
12331 in the following order:
12332
12333 @enumerate
12334 @item
12335 the applicable ^switches^switches^ contributed for the file
12336 by the @code{Builder} package in the project file supplied on the command line;
12337
12338 @item
12339 those contributed for the file by the package (in the relevant project file --
12340 see below) corresponding to the tool; and
12341
12342 @item
12343 the applicable switches passed on the command line.
12344 @end enumerate
12345
12346 The term @emph{applicable ^switches^switches^} reflects the fact that
12347 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12348 tools, depending on the individual ^switch^switch^.
12349
12350 @command{gnatmake} may invoke the compiler on source files from different
12351 projects. The Project Manager will use the appropriate project file to
12352 determine the @code{Compiler} package for each source file being compiled.
12353 Likewise for the @code{Binder} and @code{Linker} packages.
12354
12355 As an example, consider the following package in a project file:
12356
12357 @smallexample @c projectfile
12358 @group
12359 project Proj1 is
12360 package Compiler is
12361 for ^Default_Switches^Default_Switches^ ("Ada")
12362 use ("^-g^-g^");
12363 for Switches ("a.adb")
12364 use ("^-O1^-O1^");
12365 for Switches ("b.adb")
12366 use ("^-O2^-O2^",
12367 "^-gnaty^-gnaty^");
12368 end Compiler;
12369 end Proj1;
12370 @end group
12371 @end smallexample
12372
12373 @noindent
12374 If @command{gnatmake} is invoked with this project file, and it needs to
12375 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12376 @file{a.adb} will be compiled with the ^switch^switch^
12377 @option{^-O1^-O1^},
12378 @file{b.adb} with ^switches^switches^
12379 @option{^-O2^-O2^}
12380 and @option{^-gnaty^-gnaty^},
12381 and @file{c.adb} with @option{^-g^-g^}.
12382
12383 The following example illustrates the ordering of the ^switches^switches^
12384 contributed by different packages:
12385
12386 @smallexample @c projectfile
12387 @group
12388 project Proj2 is
12389 package Builder is
12390 for Switches ("main.adb")
12391 use ("^-g^-g^",
12392 "^-O1^-)1^",
12393 "^-f^-f^");
12394 end Builder;
12395 @end group
12396
12397 @group
12398 package Compiler is
12399 for Switches ("main.adb")
12400 use ("^-O2^-O2^");
12401 end Compiler;
12402 end Proj2;
12403 @end group
12404 @end smallexample
12405
12406 @noindent
12407 If you issue the command:
12408
12409 @smallexample
12410 gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
12411 @end smallexample
12412
12413 @noindent
12414 then the compiler will be invoked on @file{main.adb} with the following
12415 sequence of ^switches^switches^
12416
12417 @smallexample
12418 ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
12419 @end smallexample
12420
12421 @noindent
12422 with the last @option{^-O^-O^}
12423 ^switch^switch^ having precedence over the earlier ones;
12424 several other ^switches^switches^
12425 (such as @option{^-c^-c^}) are added implicitly.
12426
12427 The ^switches^switches^
12428 @option{^-g^-g^}
12429 and @option{^-O1^-O1^} are contributed by package
12430 @code{Builder}, @option{^-O2^-O2^} is contributed
12431 by the package @code{Compiler}
12432 and @option{^-O0^-O0^} comes from the command line.
12433
12434 The @option{^-g^-g^}
12435 ^switch^switch^ will also be passed in the invocation of
12436 @command{Gnatlink.}
12437
12438 A final example illustrates switch contributions from packages in different
12439 project files:
12440
12441 @smallexample @c projectfile
12442 @group
12443 project Proj3 is
12444 for Source_Files use ("pack.ads", "pack.adb");
12445 package Compiler is
12446 for ^Default_Switches^Default_Switches^ ("Ada")
12447 use ("^-gnata^-gnata^");
12448 end Compiler;
12449 end Proj3;
12450 @end group
12451
12452 @group
12453 with "Proj3";
12454 project Proj4 is
12455 for Source_Files use ("foo_main.adb", "bar_main.adb");
12456 package Builder is
12457 for Switches ("foo_main.adb")
12458 use ("^-s^-s^",
12459 "^-g^-g^");
12460 end Builder;
12461 end Proj4;
12462 @end group
12463
12464 @group
12465 -- Ada source file:
12466 with Pack;
12467 procedure Foo_Main is
12468 @dots{}
12469 end Foo_Main;
12470 @end group
12471 @end smallexample
12472
12473 @noindent
12474 If the command is
12475 @smallexample
12476 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
12477 @end smallexample
12478
12479 @noindent
12480 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
12481 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
12482 @option{^-gnato^-gnato^} (passed on the command line).
12483 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
12484 are @option{^-g^-g^} from @code{Proj4.Builder},
12485 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
12486 and @option{^-gnato^-gnato^} from the command line.
12487
12488 When using @command{gnatmake} with project files, some ^switches^switches^ or
12489 arguments may be expressed as relative paths. As the working directory where
12490 compilation occurs may change, these relative paths are converted to absolute
12491 paths. For the ^switches^switches^ found in a project file, the relative paths
12492 are relative to the project file directory, for the switches on the command
12493 line, they are relative to the directory where @command{gnatmake} is invoked.
12494 The ^switches^switches^ for which this occurs are:
12495 ^-I^-I^,
12496 ^-A^-A^,
12497 ^-L^-L^,
12498 ^-aO^-aO^,
12499 ^-aL^-aL^,
12500 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
12501 ^switch^switch^
12502 ^-o^-o^, object files specified in package @code{Linker} or after
12503 -largs on the command line). The exception to this rule is the ^switch^switch^
12504 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
12505
12506 @c ---------------------------------------------
12507 @node Specifying Configuration Pragmas
12508 @subsection Specifying Configuration Pragmas
12509 @c ---------------------------------------------
12510
12511 @noindent
12512 When using @command{gnatmake} with project files, if there exists a file
12513 @file{gnat.adc} that contains configuration pragmas, this file will be
12514 ignored.
12515
12516 Configuration pragmas can be defined by means of the following attributes in
12517 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
12518 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
12519
12520 Both these attributes are single string attributes. Their values is the path
12521 name of a file containing configuration pragmas. If a path name is relative,
12522 then it is relative to the project directory of the project file where the
12523 attribute is defined.
12524
12525 When compiling a source, the configuration pragmas used are, in order,
12526 those listed in the file designated by attribute
12527 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
12528 project file, if it is specified, and those listed in the file designated by
12529 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
12530 the project file of the source, if it exists.
12531
12532 @c ---------------------------------------------
12533 @node Project Files and Main Subprograms
12534 @subsection Project Files and Main Subprograms
12535 @c ---------------------------------------------
12536
12537 @noindent
12538 When using a project file, you can invoke @command{gnatmake}
12539 with one or several main subprograms, by specifying their source files on the
12540 command line.
12541
12542 @smallexample
12543 gnatmake ^-P^/PROJECT_FILE=^prj main1.adb main2.adb main3.adb
12544 @end smallexample
12545
12546 @noindent
12547 Each of these needs to be a source file of the same project, except
12548 when the switch ^-u^/UNIQUE^ is used.
12549
12550 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
12551 same project, one of the project in the tree rooted at the project specified
12552 on the command line. The package @code{Builder} of this common project, the
12553 "main project" is the one that is considered by @command{gnatmake}.
12554
12555 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
12556 imported directly or indirectly by the project specified on the command line.
12557 Note that if such a source file is not part of the project specified on the
12558 command line, the ^switches^switches^ found in package @code{Builder} of the
12559 project specified on the command line, if any, that are transmitted
12560 to the compiler will still be used, not those found in the project file of
12561 the source file.
12562
12563 When using a project file, you can also invoke @command{gnatmake} without
12564 explicitly specifying any main, and the effect depends on whether you have
12565 defined the @code{Main} attribute. This attribute has a string list value,
12566 where each element in the list is the name of a source file (the file
12567 extension is optional) that contains a unit that can be a main subprogram.
12568
12569 If the @code{Main} attribute is defined in a project file as a non-empty
12570 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
12571 line, then invoking @command{gnatmake} with this project file but without any
12572 main on the command line is equivalent to invoking @command{gnatmake} with all
12573 the file names in the @code{Main} attribute on the command line.
12574
12575 Example:
12576 @smallexample @c projectfile
12577 @group
12578 project Prj is
12579 for Main use ("main1.adb", "main2.adb", "main3.adb");
12580 end Prj;
12581 @end group
12582 @end smallexample
12583
12584 @noindent
12585 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
12586 is equivalent to
12587 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1.adb main2.adb main3.adb"}.
12588
12589 When the project attribute @code{Main} is not specified, or is specified
12590 as an empty string list, or when the switch @option{-u} is used on the command
12591 line, then invoking @command{gnatmake} with no main on the command line will
12592 result in all immediate sources of the project file being checked, and
12593 potentially recompiled. Depending on the presence of the switch @option{-u},
12594 sources from other project files on which the immediate sources of the main
12595 project file depend are also checked and potentially recompiled. In other
12596 words, the @option{-u} switch is applied to all of the immediate sources of the
12597 main project file.
12598
12599 When no main is specified on the command line and attribute @code{Main} exists
12600 and includes several mains, or when several mains are specified on the
12601 command line, the default ^switches^switches^ in package @code{Builder} will
12602 be used for all mains, even if there are specific ^switches^switches^
12603 specified for one or several mains.
12604
12605 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
12606 the specific ^switches^switches^ for each main, if they are specified.
12607
12608 @c ---------------------------------------------
12609 @node Library Project Files
12610 @subsection Library Project Files
12611 @c ---------------------------------------------
12612
12613 @noindent
12614 When @command{gnatmake} is invoked with a main project file that is a library
12615 project file, it is not allowed to specify one or more mains on the command
12616 line.
12617
12618 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
12619 ^-l^/ACTION=LINK^ have special meanings.
12620
12621 @itemize @bullet
12622 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
12623 to @command{gnatmake} that @command{gnatbind} should be invoked for the
12624 library.
12625
12626 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
12627 to @command{gnatmake} that the binder generated file should be compiled
12628 (in the case of a stand-alone library) and that the library should be built.
12629 @end itemize
12630
12631 @c ---------------------------------------------
12632 @node The GNAT Driver and Project Files
12633 @section The GNAT Driver and Project Files
12634 @c ---------------------------------------------
12635
12636 @noindent
12637 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
12638 can benefit from project files:
12639 (@command{^gnatbind^gnatbind^},
12640 @command{^gnatcheck^gnatcheck^},
12641 @command{^gnatclean^gnatclean^},
12642 @command{^gnatelim^gnatelim^},
12643 @command{^gnatfind^gnatfind^},
12644 @command{^gnatlink^gnatlink^},
12645 @command{^gnatls^gnatls^},
12646 @command{^gnatmetric^gnatmetric^},
12647 @command{^gnatpp^gnatpp^},
12648 @command{^gnatstub^gnatstub^},
12649 and @command{^gnatxref^gnatxref^}). However, none of these tools can be invoked
12650 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
12651 They must be invoked through the @command{gnat} driver.
12652
12653 The @command{gnat} driver is a wrapper that accepts a number of commands and
12654 calls the corresponding tool. It was designed initially for VMS platforms (to
12655 convert VMS qualifiers to Unix-style switches), but it is now available on all
12656 GNAT platforms.
12657
12658 On non-VMS platforms, the @command{gnat} driver accepts the following commands
12659 (case insensitive):
12660
12661 @itemize @bullet
12662 @item BIND to invoke @command{^gnatbind^gnatbind^}
12663 @item CHOP to invoke @command{^gnatchop^gnatchop^}
12664 @item CLEAN to invoke @command{^gnatclean^gnatclean^}
12665 @item COMP or COMPILE to invoke the compiler
12666 @item ELIM to invoke @command{^gnatelim^gnatelim^}
12667 @item FIND to invoke @command{^gnatfind^gnatfind^}
12668 @item KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
12669 @item LINK to invoke @command{^gnatlink^gnatlink^}
12670 @item LS or LIST to invoke @command{^gnatls^gnatls^}
12671 @item MAKE to invoke @command{^gnatmake^gnatmake^}
12672 @item NAME to invoke @command{^gnatname^gnatname^}
12673 @item PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
12674 @item PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
12675 @item METRIC to invoke @command{^gnatmetric^gnatmetric^}
12676 @item STUB to invoke @command{^gnatstub^gnatstub^}
12677 @item XREF to invoke @command{^gnatxref^gnatxref^}
12678
12679 @end itemize
12680
12681 @noindent
12682 (note that the compiler is invoked using the command
12683 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
12684
12685 On non-VMS platforms, between @command{gnat} and the command, two
12686 special switches may be used:
12687
12688 @itemize @bullet
12689 @item @command{-v} to display the invocation of the tool.
12690 @item @command{-dn} to prevent the @command{gnat} driver from removing
12691 the temporary files it has created. These temporary files are
12692 configuration files and temporary file list files.
12693
12694 @end itemize
12695
12696 @noindent
12697 The command may be followed by switches and arguments for the invoked
12698 tool.
12699
12700 @smallexample
12701 gnat bind -C main.ali
12702 gnat ls -a main
12703 gnat chop foo.txt
12704 @end smallexample
12705
12706 @noindent
12707 Switches may also be put in text files, one switch per line, and the text
12708 files may be specified with their path name preceded by '@@'.
12709
12710 @smallexample
12711 gnat bind @@args.txt main.ali
12712 @end smallexample
12713
12714 @noindent
12715 In addition, for commands BIND, COMP or COMPILE, FIND, ELIM, LS or LIST, LINK,
12716 METRIC, PP or PRETTY, STUB and XREF, the project file related switches
12717 (@option{^-P^/PROJECT_FILE^},
12718 @option{^-X^/EXTERNAL_REFERENCE^} and
12719 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
12720 the switches of the invoking tool.
12721
12722 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
12723 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
12724 the immediate sources of the specified project file.
12725
12726 When GNAT METRIC is used with a project file, but with no source
12727 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
12728 with all the immediate sources of the specified project file and with
12729 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
12730 of the project.
12731
12732 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
12733 a project file, no source is specified on the command line and
12734 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
12735 the underlying tool (^gnatpp^gnatpp^ or
12736 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
12737 not only for the immediate sources of the main project.
12738 @ifclear vms
12739 (-U stands for Universal or Union of the project files of the project tree)
12740 @end ifclear
12741
12742 For each of the following commands, there is optionally a corresponding
12743 package in the main project.
12744
12745 @itemize @bullet
12746 @item package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
12747
12748 @item package @code{Check} for command CHECK (invoking
12749 @code{^gnatcheck^gnatcheck^})
12750
12751 @item package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
12752
12753 @item package @code{Cross_Reference} for command XREF (invoking
12754 @code{^gnatxref^gnatxref^})
12755
12756 @item package @code{Eliminate} for command ELIM (invoking
12757 @code{^gnatelim^gnatelim^})
12758
12759 @item package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
12760
12761 @item package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
12762
12763 @item package @code{Gnatstub} for command STUB
12764 (invoking @code{^gnatstub^gnatstub^})
12765
12766 @item package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
12767
12768 @item package @code{Check} for command CHECK
12769 (invoking @code{^gnatcheck^gnatcheck^})
12770
12771 @item package @code{Metrics} for command METRIC
12772 (invoking @code{^gnatmetric^gnatmetric^})
12773
12774 @item package @code{Pretty_Printer} for command PP or PRETTY
12775 (invoking @code{^gnatpp^gnatpp^})
12776
12777 @end itemize
12778
12779 @noindent
12780 Package @code{Gnatls} has a unique attribute @code{Switches},
12781 a simple variable with a string list value. It contains ^switches^switches^
12782 for the invocation of @code{^gnatls^gnatls^}.
12783
12784 @smallexample @c projectfile
12785 @group
12786 project Proj1 is
12787 package gnatls is
12788 for Switches
12789 use ("^-a^-a^",
12790 "^-v^-v^");
12791 end gnatls;
12792 end Proj1;
12793 @end group
12794 @end smallexample
12795
12796 @noindent
12797 All other packages have two attribute @code{Switches} and
12798 @code{^Default_Switches^Default_Switches^}.
12799
12800 @code{Switches} is an indexed attribute, indexed by the
12801 source file name, that has a string list value: the ^switches^switches^ to be
12802 used when the tool corresponding to the package is invoked for the specific
12803 source file.
12804
12805 @code{^Default_Switches^Default_Switches^} is an attribute,
12806 indexed by the programming language that has a string list value.
12807 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
12808 ^switches^switches^ for the invocation of the tool corresponding
12809 to the package, except if a specific @code{Switches} attribute
12810 is specified for the source file.
12811
12812 @smallexample @c projectfile
12813 @group
12814 project Proj is
12815
12816 for Source_Dirs use ("**");
12817
12818 package gnatls is
12819 for Switches use
12820 ("^-a^-a^",
12821 "^-v^-v^");
12822 end gnatls;
12823 @end group
12824 @group
12825
12826 package Compiler is
12827 for ^Default_Switches^Default_Switches^ ("Ada")
12828 use ("^-gnatv^-gnatv^",
12829 "^-gnatwa^-gnatwa^");
12830 end Binder;
12831 @end group
12832 @group
12833
12834 package Binder is
12835 for ^Default_Switches^Default_Switches^ ("Ada")
12836 use ("^-C^-C^",
12837 "^-e^-e^");
12838 end Binder;
12839 @end group
12840 @group
12841
12842 package Linker is
12843 for ^Default_Switches^Default_Switches^ ("Ada")
12844 use ("^-C^-C^");
12845 for Switches ("main.adb")
12846 use ("^-C^-C^",
12847 "^-v^-v^",
12848 "^-v^-v^");
12849 end Linker;
12850 @end group
12851 @group
12852
12853 package Finder is
12854 for ^Default_Switches^Default_Switches^ ("Ada")
12855 use ("^-a^-a^",
12856 "^-f^-f^");
12857 end Finder;
12858 @end group
12859 @group
12860
12861 package Cross_Reference is
12862 for ^Default_Switches^Default_Switches^ ("Ada")
12863 use ("^-a^-a^",
12864 "^-f^-f^",
12865 "^-d^-d^",
12866 "^-u^-u^");
12867 end Cross_Reference;
12868 end Proj;
12869 @end group
12870 @end smallexample
12871
12872 @noindent
12873 With the above project file, commands such as
12874
12875 @smallexample
12876 ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
12877 ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
12878 ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
12879 ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
12880 ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
12881 @end smallexample
12882
12883 @noindent
12884 will set up the environment properly and invoke the tool with the switches
12885 found in the package corresponding to the tool:
12886 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
12887 except @code{Switches ("main.adb")}
12888 for @code{^gnatlink^gnatlink^}.
12889 It is also possible to invoke some of the tools,
12890 (@code{^gnatcheck^gnatcheck^},
12891 @code{^gnatmetric^gnatmetric^},
12892 and @code{^gnatpp^gnatpp^})
12893 on a set of project units thanks to the combination of the switches
12894 @option{-P}, @option{-U} and possibly the main unit when one is interested
12895 in its closure. For instance,
12896 @smallexample
12897 gnat metric -Pproj
12898 @end smallexample
12899
12900 @noindent
12901 will compute the metrics for all the immediate units of project
12902 @code{proj}.
12903 @smallexample
12904 gnat metric -Pproj -U
12905 @end smallexample
12906
12907 @noindent
12908 will compute the metrics for all the units of the closure of projects
12909 rooted at @code{proj}.
12910 @smallexample
12911 gnat metric -Pproj -U main_unit
12912 @end smallexample
12913
12914 @noindent
12915 will compute the metrics for the closure of units rooted at
12916 @code{main_unit}. This last possibility relies implicitly
12917 on @command{gnatbind}'s option @option{-R}. But if the argument files for the
12918 tool invoked by the @command{gnat} driver are explicitly specified
12919 either directly or through the tool @option{-files} option, then the tool
12920 is called only for these explicitly specified files.
12921
12922 @c *****************************************
12923 @c * Cross-referencing tools
12924 @c *****************************************
12925
12926 @node The Cross-Referencing Tools gnatxref and gnatfind
12927 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
12928 @findex gnatxref
12929 @findex gnatfind
12930
12931 @noindent
12932 The compiler generates cross-referencing information (unless
12933 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
12934 This information indicates where in the source each entity is declared and
12935 referenced. Note that entities in package Standard are not included, but
12936 entities in all other predefined units are included in the output.
12937
12938 Before using any of these two tools, you need to compile successfully your
12939 application, so that GNAT gets a chance to generate the cross-referencing
12940 information.
12941
12942 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
12943 information to provide the user with the capability to easily locate the
12944 declaration and references to an entity. These tools are quite similar,
12945 the difference being that @code{gnatfind} is intended for locating
12946 definitions and/or references to a specified entity or entities, whereas
12947 @code{gnatxref} is oriented to generating a full report of all
12948 cross-references.
12949
12950 To use these tools, you must not compile your application using the
12951 @option{-gnatx} switch on the @command{gnatmake} command line
12952 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
12953 information will not be generated.
12954
12955 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
12956 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
12957
12958 @menu
12959 * Switches for gnatxref::
12960 * Switches for gnatfind::
12961 * Project Files for gnatxref and gnatfind::
12962 * Regular Expressions in gnatfind and gnatxref::
12963 * Examples of gnatxref Usage::
12964 * Examples of gnatfind Usage::
12965 @end menu
12966
12967 @node Switches for gnatxref
12968 @section @code{gnatxref} Switches
12969
12970 @noindent
12971 The command invocation for @code{gnatxref} is:
12972 @smallexample
12973 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12974 @c Expanding @ovar macro inline (explanation in macro def comments)
12975 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
12976 @end smallexample
12977
12978 @noindent
12979 where
12980
12981 @table @var
12982 @item sourcefile1
12983 @itemx sourcefile2
12984 identifies the source files for which a report is to be generated. The
12985 ``with''ed units will be processed too. You must provide at least one file.
12986
12987 These file names are considered to be regular expressions, so for instance
12988 specifying @file{source*.adb} is the same as giving every file in the current
12989 directory whose name starts with @file{source} and whose extension is
12990 @file{adb}.
12991
12992 You shouldn't specify any directory name, just base names. @command{gnatxref}
12993 and @command{gnatfind} will be able to locate these files by themselves using
12994 the source path. If you specify directories, no result is produced.
12995
12996 @end table
12997
12998 @noindent
12999 The switches can be:
13000 @table @option
13001 @c !sort!
13002 @item --version
13003 @cindex @option{--version} @command{gnatxref}
13004 Display Copyright and version, then exit disregarding all other options.
13005
13006 @item --help
13007 @cindex @option{--help} @command{gnatxref}
13008 If @option{--version} was not used, display usage, then exit disregarding
13009 all other options.
13010
13011 @item ^-a^/ALL_FILES^
13012 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13013 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13014 the read-only files found in the library search path. Otherwise, these files
13015 will be ignored. This option can be used to protect Gnat sources or your own
13016 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13017 much faster, and their output much smaller. Read-only here refers to access
13018 or permissions status in the file system for the current user.
13019
13020 @item -aIDIR
13021 @cindex @option{-aIDIR} (@command{gnatxref})
13022 When looking for source files also look in directory DIR. The order in which
13023 source file search is undertaken is the same as for @command{gnatmake}.
13024
13025 @item -aODIR
13026 @cindex @option{-aODIR} (@command{gnatxref})
13027 When searching for library and object files, look in directory
13028 DIR. The order in which library files are searched is the same as for
13029 @command{gnatmake}.
13030
13031 @item -nostdinc
13032 @cindex @option{-nostdinc} (@command{gnatxref})
13033 Do not look for sources in the system default directory.
13034
13035 @item -nostdlib
13036 @cindex @option{-nostdlib} (@command{gnatxref})
13037 Do not look for library files in the system default directory.
13038
13039 @item --ext=@var{extension}
13040 @cindex @option{--ext} (@command{gnatxref})
13041 Specify an alternate ali file extension. The default is @code{ali} and other
13042 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
13043 switch. Note that if this switch overrides the default, which means that only
13044 the new extension will be considered.
13045
13046 @item --RTS=@var{rts-path}
13047 @cindex @option{--RTS} (@command{gnatxref})
13048 Specifies the default location of the runtime library. Same meaning as the
13049 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13050
13051 @item ^-d^/DERIVED_TYPES^
13052 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13053 If this switch is set @code{gnatxref} will output the parent type
13054 reference for each matching derived types.
13055
13056 @item ^-f^/FULL_PATHNAME^
13057 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13058 If this switch is set, the output file names will be preceded by their
13059 directory (if the file was found in the search path). If this switch is
13060 not set, the directory will not be printed.
13061
13062 @item ^-g^/IGNORE_LOCALS^
13063 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13064 If this switch is set, information is output only for library-level
13065 entities, ignoring local entities. The use of this switch may accelerate
13066 @code{gnatfind} and @code{gnatxref}.
13067
13068 @item -IDIR
13069 @cindex @option{-IDIR} (@command{gnatxref})
13070 Equivalent to @samp{-aODIR -aIDIR}.
13071
13072 @item -pFILE
13073 @cindex @option{-pFILE} (@command{gnatxref})
13074 Specify a project file to use @xref{GNAT Project Manager}.
13075 If you need to use the @file{.gpr}
13076 project files, you should use gnatxref through the GNAT driver
13077 (@command{gnat xref -Pproject}).
13078
13079 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13080 project file in the current directory.
13081
13082 If a project file is either specified or found by the tools, then the content
13083 of the source directory and object directory lines are added as if they
13084 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13085 and @samp{^-aO^OBJECT_SEARCH^}.
13086 @item ^-u^/UNUSED^
13087 Output only unused symbols. This may be really useful if you give your
13088 main compilation unit on the command line, as @code{gnatxref} will then
13089 display every unused entity and 'with'ed package.
13090
13091 @ifclear vms
13092 @item -v
13093 Instead of producing the default output, @code{gnatxref} will generate a
13094 @file{tags} file that can be used by vi. For examples how to use this
13095 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
13096 to the standard output, thus you will have to redirect it to a file.
13097 @end ifclear
13098
13099 @end table
13100
13101 @noindent
13102 All these switches may be in any order on the command line, and may even
13103 appear after the file names. They need not be separated by spaces, thus
13104 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13105 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13106
13107 @node Switches for gnatfind
13108 @section @code{gnatfind} Switches
13109
13110 @noindent
13111 The command line for @code{gnatfind} is:
13112
13113 @smallexample
13114 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13115 @c @r{[}@var{file1} @var{file2} @dots{}]
13116 @c Expanding @ovar macro inline (explanation in macro def comments)
13117 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13118 @r{[}@var{file1} @var{file2} @dots{}@r{]}
13119 @end smallexample
13120
13121 @noindent
13122 where
13123
13124 @table @var
13125 @item pattern
13126 An entity will be output only if it matches the regular expression found
13127 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
13128
13129 Omitting the pattern is equivalent to specifying @samp{*}, which
13130 will match any entity. Note that if you do not provide a pattern, you
13131 have to provide both a sourcefile and a line.
13132
13133 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13134 for matching purposes. At the current time there is no support for
13135 8-bit codes other than Latin-1, or for wide characters in identifiers.
13136
13137 @item sourcefile
13138 @code{gnatfind} will look for references, bodies or declarations
13139 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
13140 and column @var{column}. See @ref{Examples of gnatfind Usage}
13141 for syntax examples.
13142
13143 @item line
13144 is a decimal integer identifying the line number containing
13145 the reference to the entity (or entities) to be located.
13146
13147 @item column
13148 is a decimal integer identifying the exact location on the
13149 line of the first character of the identifier for the
13150 entity reference. Columns are numbered from 1.
13151
13152 @item file1 file2 @dots{}
13153 The search will be restricted to these source files. If none are given, then
13154 the search will be done for every library file in the search path.
13155 These file must appear only after the pattern or sourcefile.
13156
13157 These file names are considered to be regular expressions, so for instance
13158 specifying @file{source*.adb} is the same as giving every file in the current
13159 directory whose name starts with @file{source} and whose extension is
13160 @file{adb}.
13161
13162 The location of the spec of the entity will always be displayed, even if it
13163 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{} The
13164 occurrences of the entity in the separate units of the ones given on the
13165 command line will also be displayed.
13166
13167 Note that if you specify at least one file in this part, @code{gnatfind} may
13168 sometimes not be able to find the body of the subprograms.
13169
13170 @end table
13171
13172 @noindent
13173 At least one of 'sourcefile' or 'pattern' has to be present on
13174 the command line.
13175
13176 The following switches are available:
13177 @table @option
13178 @c !sort!
13179
13180 @cindex @option{--version} @command{gnatfind}
13181 Display Copyright and version, then exit disregarding all other options.
13182
13183 @item --help
13184 @cindex @option{--help} @command{gnatfind}
13185 If @option{--version} was not used, display usage, then exit disregarding
13186 all other options.
13187
13188 @item ^-a^/ALL_FILES^
13189 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
13190 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13191 the read-only files found in the library search path. Otherwise, these files
13192 will be ignored. This option can be used to protect Gnat sources or your own
13193 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13194 much faster, and their output much smaller. Read-only here refers to access
13195 or permission status in the file system for the current user.
13196
13197 @item -aIDIR
13198 @cindex @option{-aIDIR} (@command{gnatfind})
13199 When looking for source files also look in directory DIR. The order in which
13200 source file search is undertaken is the same as for @command{gnatmake}.
13201
13202 @item -aODIR
13203 @cindex @option{-aODIR} (@command{gnatfind})
13204 When searching for library and object files, look in directory
13205 DIR. The order in which library files are searched is the same as for
13206 @command{gnatmake}.
13207
13208 @item -nostdinc
13209 @cindex @option{-nostdinc} (@command{gnatfind})
13210 Do not look for sources in the system default directory.
13211
13212 @item -nostdlib
13213 @cindex @option{-nostdlib} (@command{gnatfind})
13214 Do not look for library files in the system default directory.
13215
13216 @item --ext=@var{extension}
13217 @cindex @option{--ext} (@command{gnatfind})
13218 Specify an alternate ali file extension. The default is @code{ali} and other
13219 extensions (e.g. @code{sli} for SPARK library files) may be specified via this
13220 switch. Note that if this switch overrides the default, which means that only
13221 the new extension will be considered.
13222
13223 @item --RTS=@var{rts-path}
13224 @cindex @option{--RTS} (@command{gnatfind})
13225 Specifies the default location of the runtime library. Same meaning as the
13226 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13227
13228 @item ^-d^/DERIVED_TYPE_INFORMATION^
13229 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
13230 If this switch is set, then @code{gnatfind} will output the parent type
13231 reference for each matching derived types.
13232
13233 @item ^-e^/EXPRESSIONS^
13234 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
13235 By default, @code{gnatfind} accept the simple regular expression set for
13236 @samp{pattern}. If this switch is set, then the pattern will be
13237 considered as full Unix-style regular expression.
13238
13239 @item ^-f^/FULL_PATHNAME^
13240 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
13241 If this switch is set, the output file names will be preceded by their
13242 directory (if the file was found in the search path). If this switch is
13243 not set, the directory will not be printed.
13244
13245 @item ^-g^/IGNORE_LOCALS^
13246 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
13247 If this switch is set, information is output only for library-level
13248 entities, ignoring local entities. The use of this switch may accelerate
13249 @code{gnatfind} and @code{gnatxref}.
13250
13251 @item -IDIR
13252 @cindex @option{-IDIR} (@command{gnatfind})
13253 Equivalent to @samp{-aODIR -aIDIR}.
13254
13255 @item -pFILE
13256 @cindex @option{-pFILE} (@command{gnatfind})
13257 Specify a project file (@pxref{GNAT Project Manager}) to use.
13258 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13259 project file in the current directory.
13260
13261 If a project file is either specified or found by the tools, then the content
13262 of the source directory and object directory lines are added as if they
13263 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
13264 @samp{^-aO^/OBJECT_SEARCH^}.
13265
13266 @item ^-r^/REFERENCES^
13267 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
13268 By default, @code{gnatfind} will output only the information about the
13269 declaration, body or type completion of the entities. If this switch is
13270 set, the @code{gnatfind} will locate every reference to the entities in
13271 the files specified on the command line (or in every file in the search
13272 path if no file is given on the command line).
13273
13274 @item ^-s^/PRINT_LINES^
13275 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
13276 If this switch is set, then @code{gnatfind} will output the content
13277 of the Ada source file lines were the entity was found.
13278
13279 @item ^-t^/TYPE_HIERARCHY^
13280 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
13281 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13282 the specified type. It act like -d option but recursively from parent
13283 type to parent type. When this switch is set it is not possible to
13284 specify more than one file.
13285
13286 @end table
13287
13288 @noindent
13289 All these switches may be in any order on the command line, and may even
13290 appear after the file names. They need not be separated by spaces, thus
13291 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13292 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13293
13294 As stated previously, gnatfind will search in every directory in the
13295 search path. You can force it to look only in the current directory if
13296 you specify @code{*} at the end of the command line.
13297
13298 @node Project Files for gnatxref and gnatfind
13299 @section Project Files for @command{gnatxref} and @command{gnatfind}
13300
13301 @noindent
13302 Project files allow a programmer to specify how to compile its
13303 application, where to find sources, etc. These files are used
13304 @ifclear vms
13305 primarily by GPS, but they can also be used
13306 @end ifclear
13307 by the two tools
13308 @code{gnatxref} and @code{gnatfind}.
13309
13310 A project file name must end with @file{.gpr}. If a single one is
13311 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13312 extract the information from it. If multiple project files are found, none of
13313 them is read, and you have to use the @samp{-p} switch to specify the one
13314 you want to use.
13315
13316 The following lines can be included, even though most of them have default
13317 values which can be used in most cases.
13318 The lines can be entered in any order in the file.
13319 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
13320 each line. If you have multiple instances, only the last one is taken into
13321 account.
13322
13323 @table @code
13324 @item src_dir=DIR
13325 [default: @code{"^./^[]^"}]
13326 specifies a directory where to look for source files. Multiple @code{src_dir}
13327 lines can be specified and they will be searched in the order they
13328 are specified.
13329
13330 @item obj_dir=DIR
13331 [default: @code{"^./^[]^"}]
13332 specifies a directory where to look for object and library files. Multiple
13333 @code{obj_dir} lines can be specified, and they will be searched in the order
13334 they are specified
13335
13336 @item comp_opt=SWITCHES
13337 [default: @code{""}]
13338 creates a variable which can be referred to subsequently by using
13339 the @code{$@{comp_opt@}} notation. This is intended to store the default
13340 switches given to @command{gnatmake} and @command{gcc}.
13341
13342 @item bind_opt=SWITCHES
13343 [default: @code{""}]
13344 creates a variable which can be referred to subsequently by using
13345 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13346 switches given to @command{gnatbind}.
13347
13348 @item link_opt=SWITCHES
13349 [default: @code{""}]
13350 creates a variable which can be referred to subsequently by using
13351 the @samp{$@{link_opt@}} notation. This is intended to store the default
13352 switches given to @command{gnatlink}.
13353
13354 @item main=EXECUTABLE
13355 [default: @code{""}]
13356 specifies the name of the executable for the application. This variable can
13357 be referred to in the following lines by using the @samp{$@{main@}} notation.
13358
13359 @ifset vms
13360 @item comp_cmd=COMMAND
13361 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
13362 @end ifset
13363 @ifclear vms
13364 @item comp_cmd=COMMAND
13365 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
13366 @end ifclear
13367 specifies the command used to compile a single file in the application.
13368
13369 @ifset vms
13370 @item make_cmd=COMMAND
13371 [default: @code{"GNAT MAKE $@{main@}
13372 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
13373 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
13374 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
13375 @end ifset
13376 @ifclear vms
13377 @item make_cmd=COMMAND
13378 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
13379 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
13380 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
13381 @end ifclear
13382 specifies the command used to recompile the whole application.
13383
13384 @item run_cmd=COMMAND
13385 [default: @code{"$@{main@}"}]
13386 specifies the command used to run the application.
13387
13388 @item debug_cmd=COMMAND
13389 [default: @code{"gdb $@{main@}"}]
13390 specifies the command used to debug the application
13391
13392 @end table
13393
13394 @noindent
13395 @command{gnatxref} and @command{gnatfind} only take into account the
13396 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
13397
13398 @node Regular Expressions in gnatfind and gnatxref
13399 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
13400
13401 @noindent
13402 As specified in the section about @command{gnatfind}, the pattern can be a
13403 regular expression. Actually, there are to set of regular expressions
13404 which are recognized by the program:
13405
13406 @table @code
13407 @item globbing patterns
13408 These are the most usual regular expression. They are the same that you
13409 generally used in a Unix shell command line, or in a DOS session.
13410
13411 Here is a more formal grammar:
13412 @smallexample
13413 @group
13414 @iftex
13415 @leftskip=.5cm
13416 @end iftex
13417 regexp ::= term
13418 term ::= elmt -- matches elmt
13419 term ::= elmt elmt -- concatenation (elmt then elmt)
13420 term ::= * -- any string of 0 or more characters
13421 term ::= ? -- matches any character
13422 term ::= [char @{char@}] -- matches any character listed
13423 term ::= [char - char] -- matches any character in range
13424 @end group
13425 @end smallexample
13426
13427 @item full regular expression
13428 The second set of regular expressions is much more powerful. This is the
13429 type of regular expressions recognized by utilities such a @file{grep}.
13430
13431 The following is the form of a regular expression, expressed in Ada
13432 reference manual style BNF is as follows
13433
13434 @smallexample
13435 @iftex
13436 @leftskip=.5cm
13437 @end iftex
13438 @group
13439 regexp ::= term @{| term@} -- alternation (term or term @dots{})
13440
13441 term ::= item @{item@} -- concatenation (item then item)
13442
13443 item ::= elmt -- match elmt
13444 item ::= elmt * -- zero or more elmt's
13445 item ::= elmt + -- one or more elmt's
13446 item ::= elmt ? -- matches elmt or nothing
13447 @end group
13448 @group
13449 elmt ::= nschar -- matches given character
13450 elmt ::= [nschar @{nschar@}] -- matches any character listed
13451 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
13452 elmt ::= [char - char] -- matches chars in given range
13453 elmt ::= \ char -- matches given character
13454 elmt ::= . -- matches any single character
13455 elmt ::= ( regexp ) -- parens used for grouping
13456
13457 char ::= any character, including special characters
13458 nschar ::= any character except ()[].*+?^^^
13459 @end group
13460 @end smallexample
13461
13462 Following are a few examples:
13463
13464 @table @samp
13465 @item abcde|fghi
13466 will match any of the two strings @samp{abcde} and @samp{fghi},
13467
13468 @item abc*d
13469 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
13470 @samp{abcccd}, and so on,
13471
13472 @item [a-z]+
13473 will match any string which has only lowercase characters in it (and at
13474 least one character.
13475
13476 @end table
13477 @end table
13478
13479 @node Examples of gnatxref Usage
13480 @section Examples of @code{gnatxref} Usage
13481
13482 @subsection General Usage
13483
13484 @noindent
13485 For the following examples, we will consider the following units:
13486
13487 @smallexample @c ada
13488 @group
13489 @cartouche
13490 main.ads:
13491 1: with Bar;
13492 2: package Main is
13493 3: procedure Foo (B : in Integer);
13494 4: C : Integer;
13495 5: private
13496 6: D : Integer;
13497 7: end Main;
13498
13499 main.adb:
13500 1: package body Main is
13501 2: procedure Foo (B : in Integer) is
13502 3: begin
13503 4: C := B;
13504 5: D := B;
13505 6: Bar.Print (B);
13506 7: Bar.Print (C);
13507 8: end Foo;
13508 9: end Main;
13509
13510 bar.ads:
13511 1: package Bar is
13512 2: procedure Print (B : Integer);
13513 3: end bar;
13514 @end cartouche
13515 @end group
13516 @end smallexample
13517
13518 @table @code
13519
13520 @noindent
13521 The first thing to do is to recompile your application (for instance, in
13522 that case just by doing a @samp{gnatmake main}, so that GNAT generates
13523 the cross-referencing information.
13524 You can then issue any of the following commands:
13525
13526 @item gnatxref main.adb
13527 @code{gnatxref} generates cross-reference information for main.adb
13528 and every unit 'with'ed by main.adb.
13529
13530 The output would be:
13531 @smallexample
13532 @iftex
13533 @leftskip=0cm
13534 @end iftex
13535 B Type: Integer
13536 Decl: bar.ads 2:22
13537 B Type: Integer
13538 Decl: main.ads 3:20
13539 Body: main.adb 2:20
13540 Ref: main.adb 4:13 5:13 6:19
13541 Bar Type: Unit
13542 Decl: bar.ads 1:9
13543 Ref: main.adb 6:8 7:8
13544 main.ads 1:6
13545 C Type: Integer
13546 Decl: main.ads 4:5
13547 Modi: main.adb 4:8
13548 Ref: main.adb 7:19
13549 D Type: Integer
13550 Decl: main.ads 6:5
13551 Modi: main.adb 5:8
13552 Foo Type: Unit
13553 Decl: main.ads 3:15
13554 Body: main.adb 2:15
13555 Main Type: Unit
13556 Decl: main.ads 2:9
13557 Body: main.adb 1:14
13558 Print Type: Unit
13559 Decl: bar.ads 2:15
13560 Ref: main.adb 6:12 7:12
13561 @end smallexample
13562
13563 @noindent
13564 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
13565 its body is in main.adb, line 1, column 14 and is not referenced any where.
13566
13567 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
13568 is referenced in main.adb, line 6 column 12 and line 7 column 12.
13569
13570 @item gnatxref package1.adb package2.ads
13571 @code{gnatxref} will generates cross-reference information for
13572 package1.adb, package2.ads and any other package 'with'ed by any
13573 of these.
13574
13575 @end table
13576
13577 @ifclear vms
13578 @subsection Using gnatxref with vi
13579
13580 @code{gnatxref} can generate a tags file output, which can be used
13581 directly from @command{vi}. Note that the standard version of @command{vi}
13582 will not work properly with overloaded symbols. Consider using another
13583 free implementation of @command{vi}, such as @command{vim}.
13584
13585 @smallexample
13586 $ gnatxref -v gnatfind.adb > tags
13587 @end smallexample
13588
13589 @noindent
13590 will generate the tags file for @code{gnatfind} itself (if the sources
13591 are in the search path!).
13592
13593 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
13594 (replacing @var{entity} by whatever you are looking for), and vi will
13595 display a new file with the corresponding declaration of entity.
13596 @end ifclear
13597
13598 @node Examples of gnatfind Usage
13599 @section Examples of @code{gnatfind} Usage
13600
13601 @table @code
13602
13603 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
13604 Find declarations for all entities xyz referenced at least once in
13605 main.adb. The references are search in every library file in the search
13606 path.
13607
13608 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
13609 switch is set)
13610
13611 The output will look like:
13612 @smallexample
13613 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13614 ^directory/^[directory]^main.adb:24:10: xyz <= body
13615 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13616 @end smallexample
13617
13618 @noindent
13619 that is to say, one of the entities xyz found in main.adb is declared at
13620 line 12 of main.ads (and its body is in main.adb), and another one is
13621 declared at line 45 of foo.ads
13622
13623 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
13624 This is the same command as the previous one, instead @code{gnatfind} will
13625 display the content of the Ada source file lines.
13626
13627 The output will look like:
13628
13629 @smallexample
13630 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
13631 procedure xyz;
13632 ^directory/^[directory]^main.adb:24:10: xyz <= body
13633 procedure xyz is
13634 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
13635 xyz : Integer;
13636 @end smallexample
13637
13638 @noindent
13639 This can make it easier to find exactly the location your are looking
13640 for.
13641
13642 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
13643 Find references to all entities containing an x that are
13644 referenced on line 123 of main.ads.
13645 The references will be searched only in main.ads and foo.adb.
13646
13647 @item gnatfind main.ads:123
13648 Find declarations and bodies for all entities that are referenced on
13649 line 123 of main.ads.
13650
13651 This is the same as @code{gnatfind "*":main.adb:123}.
13652
13653 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
13654 Find the declaration for the entity referenced at column 45 in
13655 line 123 of file main.adb in directory mydir. Note that it
13656 is usual to omit the identifier name when the column is given,
13657 since the column position identifies a unique reference.
13658
13659 The column has to be the beginning of the identifier, and should not
13660 point to any character in the middle of the identifier.
13661
13662 @end table
13663
13664 @c *********************************
13665 @node The GNAT Pretty-Printer gnatpp
13666 @chapter The GNAT Pretty-Printer @command{gnatpp}
13667 @findex gnatpp
13668 @cindex Pretty-Printer
13669
13670 @menu
13671 * Switches for gnatpp::
13672 * Formatting Rules::
13673 @end menu
13674
13675 @noindent
13676 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
13677 for source reformatting / pretty-printing.
13678 It takes an Ada source file as input and generates a reformatted
13679 version as output.
13680 You can specify various style directives via switches; e.g.,
13681 identifier case conventions, rules of indentation, and comment layout.
13682
13683 To produce a reformatted file, @command{gnatpp} generates and uses the ASIS
13684 tree for the input source and thus requires the input to be syntactically and
13685 semantically legal.
13686 If this condition is not met, @command{gnatpp} will terminate with an
13687 error message; no output file will be generated.
13688
13689 @command{gnatpp} cannot process sources that contain
13690 preprocessing directives.
13691
13692 If the compilation unit
13693 contained in the input source depends semantically upon units located
13694 outside the current directory, you have to provide the source search path
13695 when invoking @command{gnatpp}, if these units are contained in files with
13696 names that do not follow the GNAT file naming rules, you have to provide
13697 the configuration file describing the corresponding naming scheme;
13698 see the description of the @command{gnatpp}
13699 switches below. Another possibility is to use a project file and to
13700 call @command{gnatpp} through the @command{gnat} driver
13701 (see @ref{The GNAT Driver and Project Files}).
13702
13703 The @command{gnatpp} command has the form
13704
13705 @smallexample
13706 @c $ gnatpp @ovar{switches} @var{filename}
13707 @c Expanding @ovar macro inline (explanation in macro def comments)
13708 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
13709 @end smallexample
13710
13711 @noindent
13712 where
13713 @itemize @bullet
13714 @item
13715 @var{switches} is an optional sequence of switches defining such properties as
13716 the formatting rules, the source search path, and the destination for the
13717 output source file
13718
13719 @item
13720 @var{filename} is the name (including the extension) of the source file to
13721 reformat; ``wildcards'' or several file names on the same gnatpp command are
13722 allowed. The file name may contain path information; it does not have to
13723 follow the GNAT file naming rules
13724
13725 @item
13726 @samp{@var{gcc_switches}} is a list of switches for
13727 @command{gcc}. They will be passed on to all compiler invocations made by
13728 @command{gnatelim} to generate the ASIS trees. Here you can provide
13729 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
13730 use the @option{-gnatec} switch to set the configuration file,
13731 use the @option{-gnat05} switch if sources should be compiled in
13732 Ada 2005 mode etc.
13733 @end itemize
13734
13735 @node Switches for gnatpp
13736 @section Switches for @command{gnatpp}
13737
13738 @noindent
13739 The following subsections describe the various switches accepted by
13740 @command{gnatpp}, organized by category.
13741
13742 @ifclear vms
13743 You specify a switch by supplying a name and generally also a value.
13744 In many cases the values for a switch with a given name are incompatible with
13745 each other
13746 (for example the switch that controls the casing of a reserved word may have
13747 exactly one value: upper case, lower case, or
13748 mixed case) and thus exactly one such switch can be in effect for an
13749 invocation of @command{gnatpp}.
13750 If more than one is supplied, the last one is used.
13751 However, some values for the same switch are mutually compatible.
13752 You may supply several such switches to @command{gnatpp}, but then
13753 each must be specified in full, with both the name and the value.
13754 Abbreviated forms (the name appearing once, followed by each value) are
13755 not permitted.
13756 For example, to set
13757 the alignment of the assignment delimiter both in declarations and in
13758 assignment statements, you must write @option{-A2A3}
13759 (or @option{-A2 -A3}), but not @option{-A23}.
13760 @end ifclear
13761
13762 @ifset vms
13763 In many cases the set of options for a given qualifier are incompatible with
13764 each other (for example the qualifier that controls the casing of a reserved
13765 word may have exactly one option, which specifies either upper case, lower
13766 case, or mixed case), and thus exactly one such option can be in effect for
13767 an invocation of @command{gnatpp}.
13768 If more than one is supplied, the last one is used.
13769 However, some qualifiers have options that are mutually compatible,
13770 and then you may then supply several such options when invoking
13771 @command{gnatpp}.
13772 @end ifset
13773
13774 In most cases, it is obvious whether or not the
13775 ^values for a switch with a given name^options for a given qualifier^
13776 are compatible with each other.
13777 When the semantics might not be evident, the summaries below explicitly
13778 indicate the effect.
13779
13780 @menu
13781 * Alignment Control::
13782 * Casing Control::
13783 * Construct Layout Control::
13784 * General Text Layout Control::
13785 * Other Formatting Options::
13786 * Setting the Source Search Path::
13787 * Output File Control::
13788 * Other gnatpp Switches::
13789 @end menu
13790
13791 @node Alignment Control
13792 @subsection Alignment Control
13793 @cindex Alignment control in @command{gnatpp}
13794
13795 @noindent
13796 Programs can be easier to read if certain constructs are vertically aligned.
13797 By default all alignments are set ON.
13798 Through the @option{^-A0^/ALIGN=OFF^} switch you may reset the default to
13799 OFF, and then use one or more of the other
13800 ^@option{-A@var{n}} switches^@option{/ALIGN} options^
13801 to activate alignment for specific constructs.
13802
13803 @table @option
13804 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
13805
13806 @ifset vms
13807 @item /ALIGN=ON
13808 Set all alignments to ON
13809 @end ifset
13810
13811 @item ^-A0^/ALIGN=OFF^
13812 Set all alignments to OFF
13813
13814 @item ^-A1^/ALIGN=COLONS^
13815 Align @code{:} in declarations
13816
13817 @item ^-A2^/ALIGN=DECLARATIONS^
13818 Align @code{:=} in initializations in declarations
13819
13820 @item ^-A3^/ALIGN=STATEMENTS^
13821 Align @code{:=} in assignment statements
13822
13823 @item ^-A4^/ALIGN=ARROWS^
13824 Align @code{=>} in associations
13825
13826 @item ^-A5^/ALIGN=COMPONENT_CLAUSES^
13827 Align @code{at} keywords in the component clauses in record
13828 representation clauses
13829 @end table
13830
13831 @noindent
13832 The @option{^-A^/ALIGN^} switches are mutually compatible; any combination
13833 is allowed.
13834
13835 @node Casing Control
13836 @subsection Casing Control
13837 @cindex Casing control in @command{gnatpp}
13838
13839 @noindent
13840 @command{gnatpp} allows you to specify the casing for reserved words,
13841 pragma names, attribute designators and identifiers.
13842 For identifiers you may define a
13843 general rule for name casing but also override this rule
13844 via a set of dictionary files.
13845
13846 Three types of casing are supported: lower case, upper case, and mixed case.
13847 Lower and upper case are self-explanatory (but since some letters in
13848 Latin1 and other GNAT-supported character sets
13849 exist only in lower-case form, an upper case conversion will have no
13850 effect on them.)
13851 ``Mixed case'' means that the first letter, and also each letter immediately
13852 following an underscore, are converted to their uppercase forms;
13853 all the other letters are converted to their lowercase forms.
13854
13855 @table @option
13856 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
13857 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
13858 Attribute designators are lower case
13859
13860 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
13861 Attribute designators are upper case
13862
13863 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
13864 Attribute designators are mixed case (this is the default)
13865
13866 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
13867 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
13868 Keywords (technically, these are known in Ada as @emph{reserved words}) are
13869 lower case (this is the default)
13870
13871 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
13872 Keywords are upper case
13873
13874 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
13875 @item ^-nD^/NAME_CASING=AS_DECLARED^
13876 Name casing for defining occurrences are as they appear in the source file
13877 (this is the default)
13878
13879 @item ^-nU^/NAME_CASING=UPPER_CASE^
13880 Names are in upper case
13881
13882 @item ^-nL^/NAME_CASING=LOWER_CASE^
13883 Names are in lower case
13884
13885 @item ^-nM^/NAME_CASING=MIXED_CASE^
13886 Names are in mixed case
13887
13888 @cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
13889 @item ^-neD^/ENUM_CASING=AS_DECLARED^
13890 Enumeration literal casing for defining occurrences are as they appear in the
13891 source file. Overrides ^-n^/NAME_CASING^ casing setting.
13892
13893 @item ^-neU^/ENUM_CASING=UPPER_CASE^
13894 Enumeration literals are in upper case. Overrides ^-n^/NAME_CASING^ casing
13895 setting.
13896
13897 @item ^-neL^/ENUM_CASING=LOWER_CASE^
13898 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
13899 setting.
13900
13901 @item ^-neM^/ENUM_CASING=MIXED_CASE^
13902 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
13903 setting.
13904
13905 @cindex @option{^-nt@var{x}^/TYPE_CASING^} (@command{gnatpp})
13906 @item ^-neD^/TYPE_CASING=AS_DECLARED^
13907 Names introduced by type and subtype declarations are always
13908 cased as they appear in the declaration in the source file.
13909 Overrides ^-n^/NAME_CASING^ casing setting.
13910
13911 @item ^-ntU^/TYPE_CASING=UPPER_CASE^
13912 Names introduced by type and subtype declarations are always in
13913 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
13914
13915 @item ^-ntL^/TYPE_CASING=LOWER_CASE^
13916 Names introduced by type and subtype declarations are always in
13917 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
13918
13919 @item ^-ntM^/TYPE_CASING=MIXED_CASE^
13920 Names introduced by type and subtype declarations are always in
13921 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
13922
13923 @item ^-nnU^/NUMBER_CASING=UPPER_CASE^
13924 Names introduced by number declarations are always in
13925 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
13926
13927 @item ^-nnL^/NUMBER_CASING=LOWER_CASE^
13928 Names introduced by number declarations are always in
13929 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
13930
13931 @item ^-nnM^/NUMBER_CASING=MIXED_CASE^
13932 Names introduced by number declarations are always in
13933 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
13934
13935 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
13936 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
13937 Pragma names are lower case
13938
13939 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
13940 Pragma names are upper case
13941
13942 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
13943 Pragma names are mixed case (this is the default)
13944
13945 @item ^-D@var{file}^/DICTIONARY=@var{file}^
13946 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
13947 Use @var{file} as a @emph{dictionary file} that defines
13948 the casing for a set of specified names,
13949 thereby overriding the effect on these names by
13950 any explicit or implicit
13951 ^-n^/NAME_CASING^ switch.
13952 To supply more than one dictionary file,
13953 use ^several @option{-D} switches^a list of files as options^.
13954
13955 @noindent
13956 @option{gnatpp} implicitly uses a @emph{default dictionary file}
13957 to define the casing for the Ada predefined names and
13958 the names declared in the GNAT libraries.
13959
13960 @item ^-D-^/SPECIFIC_CASING^
13961 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
13962 Do not use the default dictionary file;
13963 instead, use the casing
13964 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
13965 dictionary file(s)
13966 @end table
13967
13968 @noindent
13969 The structure of a dictionary file, and details on the conventions
13970 used in the default dictionary file, are defined in @ref{Name Casing}.
13971
13972 The @option{^-D-^/SPECIFIC_CASING^} and
13973 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
13974 compatible.
13975
13976 @node Construct Layout Control
13977 @subsection Construct Layout Control
13978 @cindex Layout control in @command{gnatpp}
13979
13980 @noindent
13981 This group of @command{gnatpp} switches controls the layout of comments and
13982 complex syntactic constructs. See @ref{Formatting Comments} for details
13983 on their effect.
13984
13985 @table @option
13986 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
13987 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
13988 All the comments remain unchanged
13989
13990 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
13991 GNAT-style comment line indentation (this is the default).
13992
13993 @item ^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^
13994 Reference-manual comment line indentation.
13995
13996 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
13997 GNAT-style comment beginning
13998
13999 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14000 Reformat comment blocks
14001
14002 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
14003 Keep unchanged special form comments
14004
14005 @cindex @option{^-l@var{n}^/CONSTRUCT_LAYOUT^} (@command{gnatpp})
14006 @item ^-l1^/CONSTRUCT_LAYOUT=GNAT^
14007 GNAT-style layout (this is the default)
14008
14009 @item ^-l2^/CONSTRUCT_LAYOUT=COMPACT^
14010 Compact layout
14011
14012 @item ^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^
14013 Uncompact layout
14014
14015 @cindex @option{^-N^/NOTABS^} (@command{gnatpp})
14016 @item ^-N^/NOTABS^
14017 All the VT characters are removed from the comment text. All the HT characters
14018 are expanded with the sequences of space characters to get to the next tab
14019 stops.
14020
14021 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
14022 @item ^--no-separate-is^/NO_SEPARATE_IS^
14023 Do not place the keyword @code{is} on a separate line in a subprogram body in
14024 case if the spec occupies more than one line.
14025
14026 @cindex @option{^--separate-label^/SEPARATE_LABEL^} (@command{gnatpp})
14027 @item ^--separate-label^/SEPARATE_LABEL^
14028 Place statement label(s) on a separate line, with the following statement
14029 on the next line.
14030
14031 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
14032 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
14033 Place the keyword @code{loop} in FOR and WHILE loop statements and the
14034 keyword @code{then} in IF statements on a separate line.
14035
14036 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
14037 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
14038 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
14039 keyword @code{then} in IF statements on a separate line. This option is
14040 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
14041
14042 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
14043 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
14044 Start each USE clause in a context clause from a separate line.
14045
14046 @cindex @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^} (@command{gnatpp})
14047 @item ^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^
14048 Use a separate line for a loop or block statement name, but do not use an extra
14049 indentation level for the statement itself.
14050
14051 @end table
14052
14053 @ifclear vms
14054 @noindent
14055 The @option{-c1} and @option{-c2} switches are incompatible.
14056 The @option{-c3} and @option{-c4} switches are compatible with each other and
14057 also with @option{-c1} and @option{-c2}. The @option{-c0} switch disables all
14058 the other comment formatting switches.
14059
14060 The @option{-l1}, @option{-l2}, and @option{-l3} switches are incompatible.
14061 @end ifclear
14062
14063 @ifset vms
14064 @noindent
14065 For the @option{/COMMENTS_LAYOUT} qualifier:
14066 @itemize @bullet
14067 @item
14068 The @option{DEFAULT} and @option{STANDARD_INDENT} options are incompatible.
14069 @item
14070 The @option{GNAT_BEGINNING} and @option{REFORMAT} options are compatible with
14071 each other and also with @option{DEFAULT} and @option{STANDARD_INDENT}.
14072 @end itemize
14073
14074 @noindent
14075 The @option{GNAT}, @option{COMPACT}, and @option{UNCOMPACT} options for the
14076 @option{/CONSTRUCT_LAYOUT} qualifier are incompatible.
14077 @end ifset
14078
14079 @node General Text Layout Control
14080 @subsection General Text Layout Control
14081
14082 @noindent
14083 These switches allow control over line length and indentation.
14084
14085 @table @option
14086 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
14087 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14088 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
14089
14090 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
14091 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14092 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
14093
14094 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
14095 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14096 Indentation level for continuation lines (relative to the line being
14097 continued), @var{nnn} from 1@dots{}9.
14098 The default
14099 value is one less than the (normal) indentation level, unless the
14100 indentation is set to 1 (in which case the default value for continuation
14101 line indentation is also 1)
14102 @end table
14103
14104 @node Other Formatting Options
14105 @subsection Other Formatting Options
14106
14107 @noindent
14108 These switches control the inclusion of missing end/exit labels, and
14109 the indentation level in @b{case} statements.
14110
14111 @table @option
14112 @item ^-e^/NO_MISSED_LABELS^
14113 @cindex @option{^-e^/NO_MISSED_LABELS^} (@command{gnatpp})
14114 Do not insert missing end/exit labels. An end label is the name of
14115 a construct that may optionally be repeated at the end of the
14116 construct's declaration;
14117 e.g., the names of packages, subprograms, and tasks.
14118 An exit label is the name of a loop that may appear as target
14119 of an exit statement within the loop.
14120 By default, @command{gnatpp} inserts these end/exit labels when
14121 they are absent from the original source. This option suppresses such
14122 insertion, so that the formatted source reflects the original.
14123
14124 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14125 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14126 Insert a Form Feed character after a pragma Page.
14127
14128 @item ^-T@var{nnn}^/MAX_INDENT=@var{nnn}^
14129 @cindex @option{^-T^/MAX_INDENT^} (@command{gnatpp})
14130 Do not use an additional indentation level for @b{case} alternatives
14131 and variants if there are @var{nnn} or more (the default
14132 value is 10).
14133 If @var{nnn} is 0, an additional indentation level is
14134 used for @b{case} alternatives and variants regardless of their number.
14135
14136 @item ^--call_threshold=@var{nnn}^/MAX_ACT=@var{nnn}^
14137 @cindex @option{^--call_threshold^/MAX_ACT^} (@command{gnatpp})
14138 If the number of parameter associations is greater than @var{nnn} and if at
14139 least one association uses named notation, start each association from
14140 a new line. If @var{nnn} is 0, no check for the number of associations
14141 is made, this is the default.
14142
14143 @item ^--par_threshold=@var{nnn}^/MAX_PAR=@var{nnn}^
14144 @cindex @option{^--par_threshold^/MAX_PAR^} (@command{gnatpp})
14145 If the number of parameter specifications is greater than @var{nnn}
14146 (or equal to @var{nnn} in case of a function), start each specification from
14147 a new line. The default for @var{nnn} is 3.
14148 @end table
14149
14150 @node Setting the Source Search Path
14151 @subsection Setting the Source Search Path
14152
14153 @noindent
14154 To define the search path for the input source file, @command{gnatpp}
14155 uses the same switches as the GNAT compiler, with the same effects.
14156
14157 @table @option
14158 @item ^-I^/SEARCH=^@var{dir}
14159 @cindex @option{^-I^/SEARCH^} (@code{gnatpp})
14160 The same as the corresponding gcc switch
14161
14162 @item ^-I-^/NOCURRENT_DIRECTORY^
14163 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatpp})
14164 The same as the corresponding gcc switch
14165
14166 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14167 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@code{gnatpp})
14168 The same as the corresponding gcc switch
14169
14170 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14171 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@code{gnatpp})
14172 The same as the corresponding gcc switch
14173
14174 @end table
14175
14176 @node Output File Control
14177 @subsection Output File Control
14178
14179 @noindent
14180 By default the output is sent to the file whose name is obtained by appending
14181 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file
14182 (if the file with this name already exists, it is unconditionally overwritten).
14183 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14184 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14185 as output file.
14186 The output may be redirected by the following switches:
14187
14188 @table @option
14189 @item ^-pipe^/STANDARD_OUTPUT^
14190 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@code{gnatpp})
14191 Send the output to @code{Standard_Output}
14192
14193 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14194 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14195 Write the output into @var{output_file}.
14196 If @var{output_file} already exists, @command{gnatpp} terminates without
14197 reading or processing the input file.
14198
14199 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14200 @cindex @option{^-of^/FORCED_OUTPUT^} (@code{gnatpp})
14201 Write the output into @var{output_file}, overwriting the existing file
14202 (if one is present).
14203
14204 @item ^-r^/REPLACE^
14205 @cindex @option{^-r^/REPLACE^} (@code{gnatpp})
14206 Replace the input source file with the reformatted output, and copy the
14207 original input source into the file whose name is obtained by appending the
14208 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14209 If a file with this name already exists, @command{gnatpp} terminates without
14210 reading or processing the input file.
14211
14212 @item ^-rf^/OVERRIDING_REPLACE^
14213 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14214 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14215 already exists, it is overwritten.
14216
14217 @item ^-rnb^/REPLACE_NO_BACKUP^
14218 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@code{gnatpp})
14219 Replace the input source file with the reformatted output without
14220 creating any backup copy of the input source.
14221
14222 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
14223 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
14224 Specifies the format of the reformatted output file. The @var{xxx}
14225 ^string specified with the switch^option^ may be either
14226 @itemize @bullet
14227 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
14228 @item ``@option{^crlf^CRLF^}''
14229 the same as @option{^crlf^CRLF^}
14230 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
14231 @item ``@option{^lf^LF^}''
14232 the same as @option{^unix^UNIX^}
14233 @end itemize
14234
14235 @item ^-W^/RESULT_ENCODING=^@var{e}
14236 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
14237 Specify the wide character encoding method used to write the code in the
14238 result file
14239 @var{e} is one of the following:
14240
14241 @itemize @bullet
14242
14243 @item ^h^HEX^
14244 Hex encoding
14245
14246 @item ^u^UPPER^
14247 Upper half encoding
14248
14249 @item ^s^SHIFT_JIS^
14250 Shift/JIS encoding
14251
14252 @item ^e^EUC^
14253 EUC encoding
14254
14255 @item ^8^UTF8^
14256 UTF-8 encoding
14257
14258 @item ^b^BRACKETS^
14259 Brackets encoding (default value)
14260 @end itemize
14261
14262 @end table
14263
14264 @noindent
14265 Options @option{^-pipe^/STANDARD_OUTPUT^},
14266 @option{^-o^/OUTPUT^} and
14267 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14268 contains only one file to reformat.
14269 Option
14270 @option{^--eol^/END_OF_LINE^}
14271 and
14272 @option{^-W^/RESULT_ENCODING^}
14273 cannot be used together
14274 with @option{^-pipe^/STANDARD_OUTPUT^} option.
14275
14276 @node Other gnatpp Switches
14277 @subsection Other @code{gnatpp} Switches
14278
14279 @noindent
14280 The additional @command{gnatpp} switches are defined in this subsection.
14281
14282 @table @option
14283 @item --version
14284 @cindex @option{--version} @command{gnatpp}
14285 Display Copyright and version, then exit disregarding all other options.
14286
14287 @item --help
14288 @cindex @option{--help} @command{gnatpp}
14289 Display usage, then exit disregarding all other options.
14290
14291 @item ^-files @var{filename}^/FILES=@var{filename}^
14292 @cindex @option{^-files^/FILES^} (@code{gnatpp})
14293 Take the argument source files from the specified file. This file should be an
14294 ordinary text file containing file names separated by spaces or
14295 line breaks. You can use this switch more than once in the same call to
14296 @command{gnatpp}. You also can combine this switch with an explicit list of
14297 files.
14298
14299 @item ^-v^/VERBOSE^
14300 @cindex @option{^-v^/VERBOSE^} (@code{gnatpp})
14301 Verbose mode;
14302 @command{gnatpp} generates version information and then
14303 a trace of the actions it takes to produce or obtain the ASIS tree.
14304
14305 @item ^-w^/WARNINGS^
14306 @cindex @option{^-w^/WARNINGS^} (@code{gnatpp})
14307 Warning mode;
14308 @command{gnatpp} generates a warning whenever it cannot provide
14309 a required layout in the result source.
14310 @end table
14311
14312 @node Formatting Rules
14313 @section Formatting Rules
14314
14315 @noindent
14316 The following subsections show how @command{gnatpp} treats ``white space'',
14317 comments, program layout, and name casing.
14318 They provide the detailed descriptions of the switches shown above.
14319
14320 @menu
14321 * White Space and Empty Lines::
14322 * Formatting Comments::
14323 * Construct Layout::
14324 * Name Casing::
14325 @end menu
14326
14327 @node White Space and Empty Lines
14328 @subsection White Space and Empty Lines
14329
14330 @noindent
14331 @command{gnatpp} does not have an option to control space characters.
14332 It will add or remove spaces according to the style illustrated by the
14333 examples in the @cite{Ada Reference Manual}.
14334
14335 The only format effectors
14336 (see @cite{Ada Reference Manual}, paragraph 2.1(13))
14337 that will appear in the output file are platform-specific line breaks,
14338 and also format effectors within (but not at the end of) comments.
14339 In particular, each horizontal tab character that is not inside
14340 a comment will be treated as a space and thus will appear in the
14341 output file as zero or more spaces depending on
14342 the reformatting of the line in which it appears.
14343 The only exception is a Form Feed character, which is inserted after a
14344 pragma @code{Page} when @option{-ff} is set.
14345
14346 The output file will contain no lines with trailing ``white space'' (spaces,
14347 format effectors).
14348
14349 Empty lines in the original source are preserved
14350 only if they separate declarations or statements.
14351 In such contexts, a
14352 sequence of two or more empty lines is replaced by exactly one empty line.
14353 Note that a blank line will be removed if it separates two ``comment blocks''
14354 (a comment block is a sequence of whole-line comments).
14355 In order to preserve a visual separation between comment blocks, use an
14356 ``empty comment'' (a line comprising only hyphens) rather than an empty line.
14357 Likewise, if for some reason you wish to have a sequence of empty lines,
14358 use a sequence of empty comments instead.
14359
14360 @node Formatting Comments
14361 @subsection Formatting Comments
14362
14363 @noindent
14364 Comments in Ada code are of two kinds:
14365 @itemize @bullet
14366 @item
14367 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14368 ``white space'') on a line
14369
14370 @item
14371 an @emph{end-of-line comment}, which follows some other Ada lexical element
14372 on the same line.
14373 @end itemize
14374
14375 @noindent
14376 The indentation of a whole-line comment is that of either
14377 the preceding or following line in
14378 the formatted source, depending on switch settings as will be described below.
14379
14380 For an end-of-line comment, @command{gnatpp} leaves the same number of spaces
14381 between the end of the preceding Ada lexical element and the beginning
14382 of the comment as appear in the original source,
14383 unless either the comment has to be split to
14384 satisfy the line length limitation, or else the next line contains a
14385 whole line comment that is considered a continuation of this end-of-line
14386 comment (because it starts at the same position).
14387 In the latter two
14388 cases, the start of the end-of-line comment is moved right to the nearest
14389 multiple of the indentation level.
14390 This may result in a ``line overflow'' (the right-shifted comment extending
14391 beyond the maximum line length), in which case the comment is split as
14392 described below.
14393
14394 There is a difference between @option{^-c1^/COMMENTS_LAYOUT=DEFAULT^}
14395 (GNAT-style comment line indentation)
14396 and @option{^-c2^/COMMENTS_LAYOUT=STANDARD_INDENT^}
14397 (reference-manual comment line indentation).
14398 With reference-manual style, a whole-line comment is indented as if it
14399 were a declaration or statement at the same place
14400 (i.e., according to the indentation of the preceding line(s)).
14401 With GNAT style, a whole-line comment that is immediately followed by an
14402 @b{if} or @b{case} statement alternative, a record variant, or the reserved
14403 word @b{begin}, is indented based on the construct that follows it.
14404
14405 For example:
14406 @smallexample @c ada
14407 @cartouche
14408 if A then
14409 null;
14410 -- some comment
14411 else
14412 null;
14413 end if;
14414 @end cartouche
14415 @end smallexample
14416
14417 @noindent
14418 Reference-manual indentation produces:
14419
14420 @smallexample @c ada
14421 @cartouche
14422 if A then
14423 null;
14424 -- some comment
14425 else
14426 null;
14427 end if;
14428 @end cartouche
14429 @end smallexample
14430
14431 @noindent
14432 while GNAT-style indentation produces:
14433
14434 @smallexample @c ada
14435 @cartouche
14436 if A then
14437 null;
14438 -- some comment
14439 else
14440 null;
14441 end if;
14442 @end cartouche
14443 @end smallexample
14444
14445 @noindent
14446 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
14447 (GNAT style comment beginning) has the following
14448 effect:
14449
14450 @itemize @bullet
14451 @item
14452 For each whole-line comment that does not end with two hyphens,
14453 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
14454 to ensure that there are at least two spaces between these hyphens and the
14455 first non-blank character of the comment.
14456 @end itemize
14457
14458 @noindent
14459 For an end-of-line comment, if in the original source the next line is a
14460 whole-line comment that starts at the same position
14461 as the end-of-line comment,
14462 then the whole-line comment (and all whole-line comments
14463 that follow it and that start at the same position)
14464 will start at this position in the output file.
14465
14466 @noindent
14467 That is, if in the original source we have:
14468
14469 @smallexample @c ada
14470 @cartouche
14471 begin
14472 A := B + C; -- B must be in the range Low1..High1
14473 -- C must be in the range Low2..High2
14474 --B+C will be in the range Low1+Low2..High1+High2
14475 X := X + 1;
14476 @end cartouche
14477 @end smallexample
14478
14479 @noindent
14480 Then in the formatted source we get
14481
14482 @smallexample @c ada
14483 @cartouche
14484 begin
14485 A := B + C; -- B must be in the range Low1..High1
14486 -- C must be in the range Low2..High2
14487 -- B+C will be in the range Low1+Low2..High1+High2
14488 X := X + 1;
14489 @end cartouche
14490 @end smallexample
14491
14492 @noindent
14493 A comment that exceeds the line length limit will be split.
14494 Unless switch
14495 @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} (reformat comment blocks) is set and
14496 the line belongs to a reformattable block, splitting the line generates a
14497 @command{gnatpp} warning.
14498 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that whole-line
14499 comments may be reformatted in typical
14500 word processor style (that is, moving words between lines and putting as
14501 many words in a line as possible).
14502
14503 @noindent
14504 The @option{^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^} switch specifies, that comments
14505 that has a special format (that is, a character that is neither a letter nor digit
14506 not white space nor line break immediately following the leading @code{--} of
14507 the comment) should be without any change moved from the argument source
14508 into reformatted source. This switch allows to preserve comments that are used
14509 as a special marks in the code (e.g.@: SPARK annotation).
14510
14511 @node Construct Layout
14512 @subsection Construct Layout
14513
14514 @noindent
14515 In several cases the suggested layout in the Ada Reference Manual includes
14516 an extra level of indentation that many programmers prefer to avoid. The
14517 affected cases include:
14518
14519 @itemize @bullet
14520
14521 @item Record type declaration (RM 3.8)
14522
14523 @item Record representation clause (RM 13.5.1)
14524
14525 @item Loop statement in case if a loop has a statement identifier (RM 5.6)
14526
14527 @item Block statement in case if a block has a statement identifier (RM 5.6)
14528 @end itemize
14529
14530 @noindent
14531 In compact mode (when GNAT style layout or compact layout is set),
14532 the pretty printer uses one level of indentation instead
14533 of two. This is achieved in the record definition and record representation
14534 clause cases by putting the @code{record} keyword on the same line as the
14535 start of the declaration or representation clause, and in the block and loop
14536 case by putting the block or loop header on the same line as the statement
14537 identifier.
14538
14539 @noindent
14540 The difference between GNAT style @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^}
14541 and compact @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^}
14542 layout on the one hand, and uncompact layout
14543 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} on the other hand,
14544 can be illustrated by the following examples:
14545
14546 @iftex
14547 @cartouche
14548 @multitable @columnfractions .5 .5
14549 @item @i{GNAT style, compact layout} @tab @i{Uncompact layout}
14550
14551 @item
14552 @smallexample @c ada
14553 type q is record
14554 a : integer;
14555 b : integer;
14556 end record;
14557 @end smallexample
14558 @tab
14559 @smallexample @c ada
14560 type q is
14561 record
14562 a : integer;
14563 b : integer;
14564 end record;
14565 @end smallexample
14566
14567 @item
14568 @smallexample @c ada
14569 for q use record
14570 a at 0 range 0 .. 31;
14571 b at 4 range 0 .. 31;
14572 end record;
14573 @end smallexample
14574 @tab
14575 @smallexample @c ada
14576 for q use
14577 record
14578 a at 0 range 0 .. 31;
14579 b at 4 range 0 .. 31;
14580 end record;
14581 @end smallexample
14582
14583 @item
14584 @smallexample @c ada
14585 Block : declare
14586 A : Integer := 3;
14587 begin
14588 Proc (A, A);
14589 end Block;
14590 @end smallexample
14591 @tab
14592 @smallexample @c ada
14593 Block :
14594 declare
14595 A : Integer := 3;
14596 begin
14597 Proc (A, A);
14598 end Block;
14599 @end smallexample
14600
14601 @item
14602 @smallexample @c ada
14603 Clear : for J in 1 .. 10 loop
14604 A (J) := 0;
14605 end loop Clear;
14606 @end smallexample
14607 @tab
14608 @smallexample @c ada
14609 Clear :
14610 for J in 1 .. 10 loop
14611 A (J) := 0;
14612 end loop Clear;
14613 @end smallexample
14614 @end multitable
14615 @end cartouche
14616 @end iftex
14617
14618 @ifnottex
14619 @smallexample
14620 @cartouche
14621 GNAT style, compact layout Uncompact layout
14622
14623 type q is record type q is
14624 a : integer; record
14625 b : integer; a : integer;
14626 end record; b : integer;
14627 end record;
14628
14629 for q use record for q use
14630 a at 0 range 0 .. 31; record
14631 b at 4 range 0 .. 31; a at 0 range 0 .. 31;
14632 end record; b at 4 range 0 .. 31;
14633 end record;
14634
14635 Block : declare Block :
14636 A : Integer := 3; declare
14637 begin A : Integer := 3;
14638 Proc (A, A); begin
14639 end Block; Proc (A, A);
14640 end Block;
14641
14642 Clear : for J in 1 .. 10 loop Clear :
14643 A (J) := 0; for J in 1 .. 10 loop
14644 end loop Clear; A (J) := 0;
14645 end loop Clear;
14646 @end cartouche
14647 @end smallexample
14648 @end ifnottex
14649
14650 @noindent
14651 A further difference between GNAT style layout and compact layout is that
14652 GNAT style layout inserts empty lines as separation for
14653 compound statements, return statements and bodies.
14654
14655 Note that the layout specified by
14656 @option{^--separate-stmt-name^/STMT_NAME_ON_NEW_LINE^}
14657 for named block and loop statements overrides the layout defined by these
14658 constructs by @option{^-l1^/CONSTRUCT_LAYOUT=GNAT^},
14659 @option{^-l2^/CONSTRUCT_LAYOUT=COMPACT^} or
14660 @option{^-l3^/CONSTRUCT_LAYOUT=UNCOMPACT^} option.
14661
14662 @node Name Casing
14663 @subsection Name Casing
14664
14665 @noindent
14666 @command{gnatpp} always converts the usage occurrence of a (simple) name to
14667 the same casing as the corresponding defining identifier.
14668
14669 You control the casing for defining occurrences via the
14670 @option{^-n^/NAME_CASING^} switch.
14671 @ifclear vms
14672 With @option{-nD} (``as declared'', which is the default),
14673 @end ifclear
14674 @ifset vms
14675 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
14676 @end ifset
14677 defining occurrences appear exactly as in the source file
14678 where they are declared.
14679 The other ^values for this switch^options for this qualifier^ ---
14680 @option{^-nU^UPPER_CASE^},
14681 @option{^-nL^LOWER_CASE^},
14682 @option{^-nM^MIXED_CASE^} ---
14683 result in
14684 ^upper, lower, or mixed case, respectively^the corresponding casing^.
14685 If @command{gnatpp} changes the casing of a defining
14686 occurrence, it analogously changes the casing of all the
14687 usage occurrences of this name.
14688
14689 If the defining occurrence of a name is not in the source compilation unit
14690 currently being processed by @command{gnatpp}, the casing of each reference to
14691 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
14692 switch (subject to the dictionary file mechanism described below).
14693 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
14694 had affected the
14695 casing for the defining occurrence of the name.
14696
14697 Some names may need to be spelled with casing conventions that are not
14698 covered by the upper-, lower-, and mixed-case transformations.
14699 You can arrange correct casing by placing such names in a
14700 @emph{dictionary file},
14701 and then supplying a @option{^-D^/DICTIONARY^} switch.
14702 The casing of names from dictionary files overrides
14703 any @option{^-n^/NAME_CASING^} switch.
14704
14705 To handle the casing of Ada predefined names and the names from GNAT libraries,
14706 @command{gnatpp} assumes a default dictionary file.
14707 The name of each predefined entity is spelled with the same casing as is used
14708 for the entity in the @cite{Ada Reference Manual}.
14709 The name of each entity in the GNAT libraries is spelled with the same casing
14710 as is used in the declaration of that entity.
14711
14712 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of the
14713 default dictionary file.
14714 Instead, the casing for predefined and GNAT-defined names will be established
14715 by the @option{^-n^/NAME_CASING^} switch or explicit dictionary files.
14716 For example, by default the names @code{Ada.Text_IO} and @code{GNAT.OS_Lib}
14717 will appear as just shown,
14718 even in the presence of a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch.
14719 To ensure that even such names are rendered in uppercase,
14720 additionally supply the @w{@option{^-D-^/SPECIFIC_CASING^}} switch
14721 (or else, less conveniently, place these names in upper case in a dictionary
14722 file).
14723
14724 A dictionary file is
14725 a plain text file; each line in this file can be either a blank line
14726 (containing only space characters and ASCII.HT characters), an Ada comment
14727 line, or the specification of exactly one @emph{casing schema}.
14728
14729 A casing schema is a string that has the following syntax:
14730
14731 @smallexample
14732 @cartouche
14733 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
14734
14735 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
14736 @end cartouche
14737 @end smallexample
14738
14739 @noindent
14740 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
14741 @var{identifier} lexical element and the @var{letter_or_digit} category.)
14742
14743 The casing schema string can be followed by white space and/or an Ada-style
14744 comment; any amount of white space is allowed before the string.
14745
14746 If a dictionary file is passed as
14747 @ifclear vms
14748 the value of a @option{-D@var{file}} switch
14749 @end ifclear
14750 @ifset vms
14751 an option to the @option{/DICTIONARY} qualifier
14752 @end ifset
14753 then for every
14754 simple name and every identifier, @command{gnatpp} checks if the dictionary
14755 defines the casing for the name or for some of its parts (the term ``subword''
14756 is used below to denote the part of a name which is delimited by ``_'' or by
14757 the beginning or end of the word and which does not contain any ``_'' inside):
14758
14759 @itemize @bullet
14760 @item
14761 if the whole name is in the dictionary, @command{gnatpp} uses for this name
14762 the casing defined by the dictionary; no subwords are checked for this word
14763
14764 @item
14765 for every subword @command{gnatpp} checks if the dictionary contains the
14766 corresponding string of the form @code{*@var{simple_identifier}*},
14767 and if it does, the casing of this @var{simple_identifier} is used
14768 for this subword
14769
14770 @item
14771 if the whole name does not contain any ``_'' inside, and if for this name
14772 the dictionary contains two entries - one of the form @var{identifier},
14773 and another - of the form *@var{simple_identifier}*, then the first one
14774 is applied to define the casing of this name
14775
14776 @item
14777 if more than one dictionary file is passed as @command{gnatpp} switches, each
14778 dictionary adds new casing exceptions and overrides all the existing casing
14779 exceptions set by the previous dictionaries
14780
14781 @item
14782 when @command{gnatpp} checks if the word or subword is in the dictionary,
14783 this check is not case sensitive
14784 @end itemize
14785
14786 @noindent
14787 For example, suppose we have the following source to reformat:
14788
14789 @smallexample @c ada
14790 @cartouche
14791 procedure test is
14792 name1 : integer := 1;
14793 name4_name3_name2 : integer := 2;
14794 name2_name3_name4 : Boolean;
14795 name1_var : Float;
14796 begin
14797 name2_name3_name4 := name4_name3_name2 > name1;
14798 end;
14799 @end cartouche
14800 @end smallexample
14801
14802 @noindent
14803 And suppose we have two dictionaries:
14804
14805 @smallexample
14806 @cartouche
14807 @i{dict1:}
14808 NAME1
14809 *NaMe3*
14810 *Name1*
14811 @end cartouche
14812
14813 @cartouche
14814 @i{dict2:}
14815 *NAME3*
14816 @end cartouche
14817 @end smallexample
14818
14819 @noindent
14820 If @command{gnatpp} is called with the following switches:
14821
14822 @smallexample
14823 @ifclear vms
14824 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
14825 @end ifclear
14826 @ifset vms
14827 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
14828 @end ifset
14829 @end smallexample
14830
14831 @noindent
14832 then we will get the following name casing in the @command{gnatpp} output:
14833
14834 @smallexample @c ada
14835 @cartouche
14836 procedure Test is
14837 NAME1 : Integer := 1;
14838 Name4_NAME3_Name2 : Integer := 2;
14839 Name2_NAME3_Name4 : Boolean;
14840 Name1_Var : Float;
14841 begin
14842 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
14843 end Test;
14844 @end cartouche
14845 @end smallexample
14846
14847 @ifclear vms
14848 @c *********************************
14849 @node The Ada-to-XML converter gnat2xml
14850 @chapter The Ada-to-XML converter @command{gnat2xml}
14851 @findex gnat2xml
14852 @cindex XML generation
14853
14854 @noindent
14855 The @command{gnat2xml} tool is an ASIS-based utility that converts
14856 Ada source code into XML.
14857
14858 @menu
14859 * Switches for gnat2xml::
14860 * Driving gnat2xml with gnatmake or gprbuild::
14861 * Other Programs::
14862 * Structure of the XML::
14863 @end menu
14864
14865 @node Switches for gnat2xml
14866 @section Switches for @command{gnat2xml}
14867
14868 @noindent
14869 @command{gnat2xml} takes Ada source code as input, and produces XML
14870 that conforms to the schema.
14871
14872 Usage:
14873
14874 @smallexample
14875 gnat2xml [options] files
14876 @end smallexample
14877
14878 ``files'' are the Ada source file names.
14879
14880 @noindent
14881 Options:
14882 @smallexample
14883 -h
14884 --help -- generate usage information and quit, ignoring all other options
14885
14886 -mdir -- generate one .xml file for each Ada source file, in directory
14887 @file{dir}. (Default is to generate the XML to standard output.)
14888
14889 -q -- debugging version, with interspersed source, and a more
14890 compact representation of "sloc". This version does not conform
14891 to any schema.
14892
14893 -I <include-dir>
14894 directories to search for dependencies
14895 You can also set the ADA_INCLUDE_PATH environment variable for this.
14896
14897 -v -- verbose (print out the command line options, and the names of
14898 output files as they are generated).
14899
14900 -t -- do not delete tree files when done (they are deleted by default).
14901
14902 -cargs ... -- options to pass to gcc
14903 @end smallexample
14904
14905 @noindent
14906 You can generate the ``tree files'' ahead of time using the -gnatct switch:
14907
14908 @smallexample
14909 gnatmake -gnat2012 -gnatct *.ad[sb]
14910 @end smallexample
14911
14912 @noindent
14913 If tree files do not exist, @command{gnat2xml} will create them by running gcc.
14914 See the ASIS documentation for more information on tree files.
14915
14916 Example:
14917
14918 @smallexample
14919 mkdir xml-files
14920 gnat2xml -v -mxml-files *.ad[sb] -cargs -gnat2012
14921 @end smallexample
14922
14923 @noindent
14924 The above will create *.xml files in the @file{xml-files} subdirectory.
14925 For example, if there is an Ada package Mumble.Dumble, whose spec and
14926 body source code lives in mumble-dumble.ads and mumble-dumble.adb,
14927 the above will produce xml-files/mumble-dumble.ads.xml and
14928 xml-files/mumble-dumble.adb.xml.
14929
14930 @node Driving gnat2xml with gnatmake or gprbuild
14931 @section Driving @command{gnat2xml} with @command{gnatmake} or @command{gprbuild}
14932
14933 @noindent
14934 You can use gnatmake or gprbuild to drive @command{gnat2xml} to get
14935 incremental updates of the XML files on a per-source-file basis. For
14936 example, if you already have a bunch of XML files, and then you change
14937 one source file, it will regenerate XML files only for that source
14938 file, and other source files that depend on it. Gnatmake and gprbuild
14939 take care of tracking inter-file dependencies. For example, if
14940 this.adb says @code{with That;}, then this.adb depends on that.ads.
14941
14942 To do this, you tell gnatmake/gprbuild to pretend that
14943 @command{gnat2xml} is the Ada compiler (instead of using gcc as the
14944 Ada compiler, as is normal).
14945
14946 To tell gnatmake to use @command{gnat2xml} instead of gcc as the
14947 ``compiler'', for example:
14948
14949 @smallexample
14950 gnatmake -gnatc *.adb --GCC="gnat2xml -t -mxml"
14951 @end smallexample
14952
14953 @noindent
14954 The @option{--GCC=} switch tells gnatmake that the ``compiler'' to run
14955 is @command{gnat2xml -t -mxml}. The @option{-t} switch means to keep the tree
14956 files, so they can be reused on the next run. (@command{gnat2xml}
14957 deletes them by default.) As usual, @option{-mxml} means to put the
14958 XML files in the @file{xml} subdirectory.
14959
14960 You must give the @option{-gnatc} switch to gnatmake, which means
14961 ``compile only; do not generate object code''. Otherwise, gnatmake will
14962 complain about missing object (*.o) files; @command{gnat2xml} of
14963 course does not generate *.o files.
14964
14965 Using gprbuild is similar: you tell it to use @command{gnat2xml}
14966 instead of gcc. First write a project file, such as my_project.gpr:
14967
14968 @smallexample @c projectfile
14969 project My_Project is
14970
14971 package Compiler is
14972 for Driver ("ada") use "gnat2xml";
14973 -- Use gnat2xml instead of the usual gcc.
14974
14975 for Default_Switches ("ada") use ("-t", "-mxml");
14976 -- Same switches as in the gnatmake case.
14977 end Compiler;
14978
14979 end My_Project;
14980 @end smallexample
14981
14982 @noindent
14983 Then:
14984
14985 @smallexample @c projectfile
14986 gprbuild --no-object-check -P my_project.gpr
14987 @end smallexample
14988
14989 @noindent
14990 The @option{--no-object-check} switch serves the same purpose as
14991 @option{-gnatc} in the gnatmake case --- it tells gprbuild not to
14992 expect that the ``compiler'' (really @command{gnat2xml}) will produce
14993 *.o files.
14994
14995 See the gprbuild documentation for information on many other things
14996 you can put in the project file, such as telling it where to find
14997 the source files.
14998
14999 @node Other Programs
15000 @section Other Programs
15001
15002 @noindent
15003 The distribution includes two other programs that are related to
15004 @command{gnat2xml}:
15005
15006 @command{gnat2xsd} is the schema generator, which generates the schema
15007 to standard output, based on the structure of Ada as encoded by
15008 ASIS. You don't need to run @command{gnat2xsd} in order to use
15009 @command{gnat2xml}. To generate the schema, type:
15010
15011 @smallexample
15012 gnat2xsd > ada-schema.xsd
15013 @end smallexample
15014
15015 @noindent
15016 @command{gnat2xml} generates XML files that will validate against
15017 @file{ada-schema.xsd}.
15018
15019 @command{xml2gnat} is a back-translator that translates the XML back
15020 into Ada source code. The Ada generated by @command{xml2gnat} has
15021 identical semantics to the original Ada code passed to
15022 @command{gnat2xml}. It is not textually identical, however --- for
15023 example, no attempt is made to preserve the original indentation.
15024
15025 @node Structure of the XML
15026 @section Structure of the XML
15027
15028 @noindent
15029 The primary documentation for the structure of the XML generated by
15030 @command{gnat2xml} is the schema (see @command{gnat2xsd} above). The
15031 following documentation gives additional details needed to understand
15032 the schema and therefore the XML.
15033
15034 The elements listed under Defining Occurrences, Usage Occurrences, and
15035 Other Elements represent the syntactic structure of the Ada program.
15036 Element names are given in lower case, with the corresponding element
15037 type Capitalized_Like_This. The element and element type names are
15038 derived directly from the ASIS enumeration type Flat_Element_Kinds,
15039 declared in Asis.Extensions.Flat_Kinds, with the leading ``An_'' or ``A_''
15040 removed. For example, the ASIS enumeration literal
15041 An_Assignment_Statement corresponds to the XML element
15042 assignment_statement of XML type Assignment_Statement.
15043
15044 To understand the details of the schema and the corresponding XML, it is
15045 necessary to understand the ASIS standard, as well as the GNAT-specific
15046 extension to ASIS.
15047
15048 A defining occurrence is an identifier (or character literal or operator
15049 symbol) declared by a declaration. A usage occurrence is an identifier
15050 (or ...) that references such a declared entity. For example, in:
15051
15052 @smallexample
15053 type T is range 1..10;
15054 X, Y : constant T := 1;
15055 @end smallexample
15056
15057 @noindent
15058 The first ``T'' is the defining occurrence of a type. The ``X'' is the
15059 defining occurrence of a constant, as is the ``Y'', and the second ``T'' is
15060 a usage occurrence referring to the defining occurrence of T.
15061
15062 Each element has a 'sloc' (source location), and subelements for each
15063 syntactic subtree, reflecting the Ada grammar as implemented by ASIS.
15064 The types of subelements are as defined in the ASIS standard. For
15065 example, for the right-hand side of an assignment_statement we have
15066 the following comment in asis-statements.ads:
15067
15068 @smallexample
15069 ------------------------------------------------------------------------------
15070 -- 18.3 function Assignment_Expression
15071 ------------------------------------------------------------------------------
15072
15073 function Assignment_Expression
15074 (Statement : Asis.Statement)
15075 return Asis.Expression;
15076
15077 ------------------------------------------------------------------------------
15078 ...
15079 -- Returns the expression from the right hand side of the assignment.
15080 ...
15081 -- Returns Element_Kinds:
15082 -- An_Expression
15083 @end smallexample
15084
15085 @noindent
15086 The corresponding sub-element of type Assignment_Statement is:
15087
15088 @smallexample
15089 <xsd:element name="assignment_expression_q" type="Expression_Class"/>
15090 @end smallexample
15091
15092 @noindent
15093 where Expression_Class is defined by an xsd:choice of all the
15094 various kinds of expression.
15095
15096 The 'sloc' of each element indicates the starting and ending line and
15097 column numbers. Column numbers are character counts; that is, a tab
15098 counts as 1, not as however many spaces it might expand to.
15099
15100 Subelements of type Element have names ending in ``_q'' (for ASIS
15101 ``Query''), and those of type Element_List end in ``_ql'' (``Query returning
15102 List'').
15103
15104 Some subelements are ``Boolean''. For example, Private_Type_Definition
15105 has has_abstract_q and has_limited_q, to indicate whether those
15106 keywords are present, as in @code{type T is abstract limited
15107 private;}. False is represented by a Nil_Element. True is represented
15108 by an element type specific to that query (for example, Abstract and
15109 Limited).
15110
15111 The root of the tree is a Compilation_Unit, with attributes:
15112
15113 @itemize @bullet
15114 @item
15115 unit_kind, unit_class, and unit_origin. These are strings that match the
15116 enumeration literals of types Unit_Kinds, Unit_Classes, and Unit_Origins
15117 in package Asis.
15118
15119 @item
15120 unit_full_name is the full expanded name of the unit, starting from a
15121 root library unit. So for @code{package P.Q.R is ...},
15122 @code{unit_full_name="P.Q.R"}. Same for @code{separate (P.Q) package R is ...}.
15123
15124 @item
15125 def_name is the same as unit_full_name for library units; for subunits,
15126 it is just the simple name.
15127
15128 @item
15129 source_file is the name of the Ada source file. For example, for
15130 the spec of @code{P.Q.R}, @code{source_file="p-q-r.ads"}. This allows one to
15131 interpret the source locations --- the ``sloc'' of all elements
15132 within this Compilation_Unit refers to line and column numbers
15133 within the named file.
15134 @end itemize
15135
15136 @noindent
15137 Defining occurrences have these attributes:
15138
15139 @itemize @bullet
15140 @item
15141 def_name is the simple name of the declared entity, as written in the Ada
15142 source code.
15143
15144 @item
15145 def is a unique URI of the form:
15146
15147 ada://kind/fully/qualified/name
15148
15149 where:
15150
15151 kind indicates the kind of Ada entity being declared (see below), and
15152
15153 fully/qualified/name, is the fully qualified name of the Ada
15154 entity, with each of ``fully'', ``qualified'', and ``name'' being
15155 mangled for uniqueness. We do not document the mangling
15156 algorithm, which is subject to change; we just guarantee that the
15157 names are unique in the face of overloading.
15158
15159 @item
15160 type is the type of the declared object, or @code{null} for
15161 declarations of things other than objects.
15162 @end itemize
15163
15164 @noindent
15165 Usage occurrences have these attributes:
15166
15167 @itemize @bullet
15168 @item
15169 ref_name is the same as the def_name of the corresponding defining
15170 occurrence. This attribute is not of much use, because of
15171 overloading; use ref for lookups, instead.
15172
15173 @item
15174 ref is the same as the def of the corresponding defining
15175 occurrence.
15176 @end itemize
15177
15178 @noindent
15179 In summary, @code{def_name} and @code{ref_name} are as in the source
15180 code of the declaration, possibly overloaded, whereas @code{def} and
15181 @code{ref} are unique-ified.
15182
15183 Literal elements have this attribute:
15184
15185 @itemize @bullet
15186 @item
15187 lit_val is the value of the literal as written in the source text,
15188 appropriately escaped (e.g. @code{"} ---> @code{&quot;}). This applies
15189 only to numeric and string literals. Enumeration literals in Ada are
15190 not really "literals" in the usual sense; they are usage occurrences,
15191 and have ref_name and ref as described above. Note also that string
15192 literals used as operator symbols are treated as defining or usage
15193 occurrences, not as literals.
15194 @end itemize
15195
15196 @noindent
15197 Elements that can syntactically represent names and expressions (which
15198 includes usage occurrences, plus function calls and so forth) have this
15199 attribute:
15200
15201 @itemize @bullet
15202 @item
15203 type. If the element represents an expression or the name of an object,
15204 'type' is the 'def' for the defining occurrence of the type of that
15205 expression or name. Names of other kinds of entities, such as package
15206 names and type names, do not have a type in Ada; these have type="null"
15207 in the XML.
15208 @end itemize
15209
15210 @noindent
15211 Pragma elements have this attribute:
15212
15213 @itemize @bullet
15214 @item
15215 pragma_name is the name of the pragma. For language-defined pragmas, the
15216 pragma name is redundant with the element kind (for example, an
15217 assert_pragma element necessarily has pragma_name="Assert"). However, all
15218 implementation-defined pragmas are lumped together in ASIS as a single
15219 element kind (for example, the GNAT-specific pragma Unreferenced is
15220 represented by an implementation_defined_pragma element with
15221 pragma_name="Unreferenced").
15222 @end itemize
15223
15224 @noindent
15225 Defining occurrences of formal parameters and generic formal objects have this
15226 attribute:
15227
15228 @itemize @bullet
15229 @item
15230 mode indicates that the parameter is of mode 'in', 'in out', or 'out'.
15231 @end itemize
15232
15233 @noindent
15234 The "kind" part of the "def" and "ref" attributes is taken from the ASIS
15235 enumeration type Flat_Declaration_Kinds, declared in
15236 Asis.Extensions.Flat_Kinds, with the leading "An_" or "A_" removed, and
15237 any trailing "_Declaration" or "_Specification" removed. Thus, the
15238 possible kinds are as follows:
15239
15240 @smallexample
15241 ordinary_type
15242 task_type
15243 protected_type
15244 incomplete_type
15245 tagged_incomplete_type
15246 private_type
15247 private_extension
15248 subtype
15249 variable
15250 constant
15251 deferred_constant
15252 single_task
15253 single_protected
15254 integer_number
15255 real_number
15256 enumeration_literal
15257 discriminant
15258 component
15259 loop_parameter
15260 generalized_iterator
15261 element_iterator
15262 procedure
15263 function
15264 parameter
15265 procedure_body
15266 function_body
15267 return_variable
15268 return_constant
15269 null_procedure
15270 expression_function
15271 package
15272 package_body
15273 object_renaming
15274 exception_renaming
15275 package_renaming
15276 procedure_renaming
15277 function_renaming
15278 generic_package_renaming
15279 generic_procedure_renaming
15280 generic_function_renaming
15281 task_body
15282 protected_body
15283 entry
15284 entry_body
15285 entry_index
15286 procedure_body_stub
15287 function_body_stub
15288 package_body_stub
15289 task_body_stub
15290 protected_body_stub
15291 exception
15292 choice_parameter
15293 generic_procedure
15294 generic_function
15295 generic_package
15296 package_instantiation
15297 procedure_instantiation
15298 function_instantiation
15299 formal_object
15300 formal_type
15301 formal_incomplete_type
15302 formal_procedure
15303 formal_function
15304 formal_package
15305 formal_package_declaration_with_box
15306 @end smallexample
15307 @end ifclear
15308
15309 @c *********************************
15310 @node The GNAT Metrics Tool gnatmetric
15311 @chapter The GNAT Metrics Tool @command{gnatmetric}
15312 @findex gnatmetric
15313 @cindex Metric tool
15314
15315 @noindent
15316 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
15317 for computing various program metrics.
15318 It takes an Ada source file as input and generates a file containing the
15319 metrics data as output. Various switches control which
15320 metrics are computed and output.
15321
15322 @menu
15323 * Switches for gnatmetric::
15324 @end menu
15325
15326 @command{gnatmetric} generates and uses the ASIS
15327 tree for the input source and thus requires the input to be syntactically and
15328 semantically legal.
15329 If this condition is not met, @command{gnatmetric} will generate
15330 an error message; no metric information for this file will be
15331 computed and reported.
15332
15333 If the compilation unit contained in the input source depends semantically
15334 upon units in files located outside the current directory, you have to provide
15335 the source search path when invoking @command{gnatmetric}.
15336 If it depends semantically upon units that are contained
15337 in files with names that do not follow the GNAT file naming rules, you have to
15338 provide the configuration file describing the corresponding naming scheme (see
15339 the description of the @command{gnatmetric} switches below.)
15340 Alternatively, you may use a project file and invoke @command{gnatmetric}
15341 through the @command{gnat} driver (see @ref{The GNAT Driver and Project Files}).
15342
15343 The @command{gnatmetric} command has the form
15344
15345 @smallexample
15346 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15347 @c Expanding @ovar macro inline (explanation in macro def comments)
15348 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15349 @end smallexample
15350
15351 @noindent
15352 where
15353 @itemize @bullet
15354 @item
15355 @var{switches} specify the metrics to compute and define the destination for
15356 the output
15357
15358 @item
15359 Each @var{filename} is the name (including the extension) of a source
15360 file to process. ``Wildcards'' are allowed, and
15361 the file name may contain path information.
15362 If no @var{filename} is supplied, then the @var{switches} list must contain
15363 at least one
15364 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15365 Including both a @option{-files} switch and one or more
15366 @var{filename} arguments is permitted.
15367
15368 @item
15369 @samp{@var{gcc_switches}} is a list of switches for
15370 @command{gcc}. They will be passed on to all compiler invocations made by
15371 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15372 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
15373 and use the @option{-gnatec} switch to set the configuration file,
15374 use the @option{-gnat05} switch if sources should be compiled in
15375 Ada 2005 mode etc.
15376 @end itemize
15377
15378 @node Switches for gnatmetric
15379 @section Switches for @command{gnatmetric}
15380
15381 @noindent
15382 The following subsections describe the various switches accepted by
15383 @command{gnatmetric}, organized by category.
15384
15385 @menu
15386 * Output Files Control::
15387 * Disable Metrics For Local Units::
15388 * Specifying a set of metrics to compute::
15389 * Other gnatmetric Switches::
15390 * Generate project-wide metrics::
15391 @end menu
15392
15393 @node Output Files Control
15394 @subsection Output File Control
15395 @cindex Output file control in @command{gnatmetric}
15396
15397 @noindent
15398 @command{gnatmetric} has two output formats. It can generate a
15399 textual (human-readable) form, and also XML. By default only textual
15400 output is generated.
15401
15402 When generating the output in textual form, @command{gnatmetric} creates
15403 for each Ada source file a corresponding text file
15404 containing the computed metrics, except for the case when the set of metrics
15405 specified by gnatmetric parameters consists only of metrics that are computed
15406 for the whole set of analyzed sources, but not for each Ada source.
15407 By default, this file is placed in the same directory as where the source
15408 file is located, and its name is obtained
15409 by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the name of the
15410 input file.
15411
15412 All the output information generated in XML format is placed in a single
15413 file. By default this file is placed in the current directory and has the
15414 name ^@file{metrix.xml}^@file{METRIX$XML}^.
15415
15416 Some of the computed metrics are summed over the units passed to
15417 @command{gnatmetric}; for example, the total number of lines of code.
15418 By default this information is sent to @file{stdout}, but a file
15419 can be specified with the @option{-og} switch.
15420
15421 The following switches control the @command{gnatmetric} output:
15422
15423 @table @option
15424 @cindex @option{^-x^/XML^} (@command{gnatmetric})
15425 @item ^-x^/XML^
15426 Generate the XML output
15427
15428 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
15429 @item ^-xs^/XSD^
15430 Generate the XML output and the XML schema file that describes the structure
15431 of the XML metric report, this schema is assigned to the XML file. The schema
15432 file has the same name as the XML output file with @file{.xml} suffix replaced
15433 with @file{.xsd}
15434
15435 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
15436 @item ^-nt^/NO_TEXT^
15437 Do not generate the output in text form (implies @option{^-x^/XML^})
15438
15439 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
15440 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
15441 Put text files with detailed metrics into @var{output_dir}
15442
15443 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
15444 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
15445 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
15446 in the name of the output file.
15447
15448 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
15449 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
15450 Put global metrics into @var{file_name}
15451
15452 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
15453 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
15454 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
15455
15456 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
15457 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
15458 Use ``short'' source file names in the output. (The @command{gnatmetric}
15459 output includes the name(s) of the Ada source file(s) from which the metrics
15460 are computed. By default each name includes the absolute path. The
15461 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
15462 to exclude all directory information from the file names that are output.)
15463
15464 @end table
15465
15466 @node Disable Metrics For Local Units
15467 @subsection Disable Metrics For Local Units
15468 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15469
15470 @noindent
15471 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15472 one compilation
15473 unit per one source file. It computes line metrics for the whole source
15474 file, and it also computes syntax
15475 and complexity metrics for the file's outermost unit.
15476
15477 By default, @command{gnatmetric} will also compute all metrics for certain
15478 kinds of locally declared program units:
15479
15480 @itemize @bullet
15481 @item
15482 subprogram (and generic subprogram) bodies;
15483
15484 @item
15485 package (and generic package) specs and bodies;
15486
15487 @item
15488 task object and type specifications and bodies;
15489
15490 @item
15491 protected object and type specifications and bodies.
15492 @end itemize
15493
15494 @noindent
15495 These kinds of entities will be referred to as
15496 @emph{eligible local program units}, or simply @emph{eligible local units},
15497 @cindex Eligible local unit (for @command{gnatmetric})
15498 in the discussion below.
15499
15500 Note that a subprogram declaration, generic instantiation,
15501 or renaming declaration only receives metrics
15502 computation when it appear as the outermost entity
15503 in a source file.
15504
15505 Suppression of metrics computation for eligible local units can be
15506 obtained via the following switch:
15507
15508 @table @option
15509 @cindex @option{^-n@var{x}^/SUPPRESS^} (@command{gnatmetric})
15510 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
15511 Do not compute detailed metrics for eligible local program units
15512
15513 @end table
15514
15515 @node Specifying a set of metrics to compute
15516 @subsection Specifying a set of metrics to compute
15517
15518 @noindent
15519 By default all the metrics are computed and reported. The switches
15520 described in this subsection allow you to control, on an individual
15521 basis, whether metrics are computed and
15522 reported. If at least one positive metric
15523 switch is specified (that is, a switch that defines that a given
15524 metric or set of metrics is to be computed), then only
15525 explicitly specified metrics are reported.
15526
15527 @menu
15528 * Line Metrics Control::
15529 * Syntax Metrics Control::
15530 * Complexity Metrics Control::
15531 * Coupling Metrics Control::
15532 @end menu
15533
15534 @node Line Metrics Control
15535 @subsubsection Line Metrics Control
15536 @cindex Line metrics control in @command{gnatmetric}
15537
15538 @noindent
15539 For any (legal) source file, and for each of its
15540 eligible local program units, @command{gnatmetric} computes the following
15541 metrics:
15542
15543 @itemize @bullet
15544 @item
15545 the total number of lines;
15546
15547 @item
15548 the total number of code lines (i.e., non-blank lines that are not comments)
15549
15550 @item
15551 the number of comment lines
15552
15553 @item
15554 the number of code lines containing end-of-line comments;
15555
15556 @item
15557 the comment percentage: the ratio between the number of lines that contain
15558 comments and the number of all non-blank lines, expressed as a percentage;
15559
15560 @item
15561 the number of empty lines and lines containing only space characters and/or
15562 format effectors (blank lines)
15563
15564 @item
15565 the average number of code lines in subprogram bodies, task bodies, entry
15566 bodies and statement sequences in package bodies (this metric is only computed
15567 across the whole set of the analyzed units)
15568
15569 @end itemize
15570
15571 @noindent
15572 @command{gnatmetric} sums the values of the line metrics for all the
15573 files being processed and then generates the cumulative results. The tool
15574 also computes for all the files being processed the average number of code
15575 lines in bodies.
15576
15577 You can use the following switches to select the specific line metrics
15578 to be computed and reported.
15579
15580 @table @option
15581 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
15582
15583 @ifclear vms
15584 @cindex @option{--no-lines@var{x}}
15585 @end ifclear
15586
15587 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
15588 Report all the line metrics
15589
15590 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
15591 Do not report any of line metrics
15592
15593 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
15594 Report the number of all lines
15595
15596 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
15597 Do not report the number of all lines
15598
15599 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
15600 Report the number of code lines
15601
15602 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
15603 Do not report the number of code lines
15604
15605 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
15606 Report the number of comment lines
15607
15608 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
15609 Do not report the number of comment lines
15610
15611 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
15612 Report the number of code lines containing
15613 end-of-line comments
15614
15615 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
15616 Do not report the number of code lines containing
15617 end-of-line comments
15618
15619 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
15620 Report the comment percentage in the program text
15621
15622 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
15623 Do not report the comment percentage in the program text
15624
15625 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
15626 Report the number of blank lines
15627
15628 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
15629 Do not report the number of blank lines
15630
15631 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
15632 Report the average number of code lines in subprogram bodies, task bodies,
15633 entry bodies and statement sequences in package bodies. The metric is computed
15634 and reported for the whole set of processed Ada sources only.
15635
15636 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
15637 Do not report the average number of code lines in subprogram bodies,
15638 task bodies, entry bodies and statement sequences in package bodies.
15639
15640 @end table
15641
15642 @node Syntax Metrics Control
15643 @subsubsection Syntax Metrics Control
15644 @cindex Syntax metrics control in @command{gnatmetric}
15645
15646 @noindent
15647 @command{gnatmetric} computes various syntactic metrics for the
15648 outermost unit and for each eligible local unit:
15649
15650 @table @emph
15651 @item LSLOC (``Logical Source Lines Of Code'')
15652 The total number of declarations and the total number of statements. Note
15653 that the definition of declarations is the one given in the reference
15654 manual:
15655
15656 @noindent
15657 ``Each of the following is defined to be a declaration: any basic_declaration;
15658 an enumeration_literal_specification; a discriminant_specification;
15659 a component_declaration; a loop_parameter_specification; a
15660 parameter_specification; a subprogram_body; an entry_declaration;
15661 an entry_index_specification; a choice_parameter_specification;
15662 a generic_formal_parameter_declaration.''
15663
15664 This means for example that each enumeration literal adds one to the count,
15665 as well as each subprogram parameter.
15666
15667 Thus the results from this metric will be significantly greater than might
15668 be expected from a naive view of counting semicolons.
15669
15670 @item Maximal static nesting level of inner program units
15671 According to
15672 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
15673 package, a task unit, a protected unit, a
15674 protected entry, a generic unit, or an explicitly declared subprogram other
15675 than an enumeration literal.''
15676
15677 @item Maximal nesting level of composite syntactic constructs
15678 This corresponds to the notion of the
15679 maximum nesting level in the GNAT built-in style checks
15680 (@pxref{Style Checking})
15681 @end table
15682
15683 @noindent
15684 For the outermost unit in the file, @command{gnatmetric} additionally computes
15685 the following metrics:
15686
15687 @table @emph
15688 @item Public subprograms
15689 This metric is computed for package specs. It is the
15690 number of subprograms and generic subprograms declared in the visible
15691 part (including the visible part of nested packages, protected objects, and
15692 protected types).
15693
15694 @item All subprograms
15695 This metric is computed for bodies and subunits. The
15696 metric is equal to a total number of subprogram bodies in the compilation
15697 unit.
15698 Neither generic instantiations nor renamings-as-a-body nor body stubs
15699 are counted. Any subprogram body is counted, independently of its nesting
15700 level and enclosing constructs. Generic bodies and bodies of protected
15701 subprograms are counted in the same way as ``usual'' subprogram bodies.
15702
15703 @item Public types
15704 This metric is computed for package specs and
15705 generic package declarations. It is the total number of types
15706 that can be referenced from outside this compilation unit, plus the
15707 number of types from all the visible parts of all the visible generic
15708 packages. Generic formal types are not counted. Only types, not subtypes,
15709 are included.
15710
15711 @noindent
15712 Along with the total number of public types, the following
15713 types are counted and reported separately:
15714
15715 @itemize @bullet
15716 @item
15717 Abstract types
15718
15719 @item
15720 Root tagged types (abstract, non-abstract, private, non-private). Type
15721 extensions are @emph{not} counted
15722
15723 @item
15724 Private types (including private extensions)
15725
15726 @item
15727 Task types
15728
15729 @item
15730 Protected types
15731
15732 @end itemize
15733
15734 @item All types
15735 This metric is computed for any compilation unit. It is equal to the total
15736 number of the declarations of different types given in the compilation unit.
15737 The private and the corresponding full type declaration are counted as one
15738 type declaration. Incomplete type declarations and generic formal types
15739 are not counted.
15740 No distinction is made among different kinds of types (abstract,
15741 private etc.); the total number of types is computed and reported.
15742
15743 @end table
15744
15745 @noindent
15746 By default, all the syntax metrics are computed and reported. You can use the
15747 following switches to select specific syntax metrics.
15748
15749 @table @option
15750
15751 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
15752
15753 @ifclear vms
15754 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
15755 @end ifclear
15756
15757 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
15758 Report all the syntax metrics
15759
15760 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
15761 Do not report any of syntax metrics
15762
15763 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
15764 Report the total number of declarations
15765
15766 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
15767 Do not report the total number of declarations
15768
15769 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
15770 Report the total number of statements
15771
15772 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
15773 Do not report the total number of statements
15774
15775 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
15776 Report the number of public subprograms in a compilation unit
15777
15778 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
15779 Do not report the number of public subprograms in a compilation unit
15780
15781 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
15782 Report the number of all the subprograms in a compilation unit
15783
15784 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
15785 Do not report the number of all the subprograms in a compilation unit
15786
15787 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
15788 Report the number of public types in a compilation unit
15789
15790 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
15791 Do not report the number of public types in a compilation unit
15792
15793 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
15794 Report the number of all the types in a compilation unit
15795
15796 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
15797 Do not report the number of all the types in a compilation unit
15798
15799 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
15800 Report the maximal program unit nesting level
15801
15802 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
15803 Do not report the maximal program unit nesting level
15804
15805 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
15806 Report the maximal construct nesting level
15807
15808 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
15809 Do not report the maximal construct nesting level
15810
15811 @end table
15812
15813 @node Complexity Metrics Control
15814 @subsubsection Complexity Metrics Control
15815 @cindex Complexity metrics control in @command{gnatmetric}
15816
15817 @noindent
15818 For a program unit that is an executable body (a subprogram body (including
15819 generic bodies), task body, entry body or a package body containing
15820 its own statement sequence) @command{gnatmetric} computes the following
15821 complexity metrics:
15822
15823 @itemize @bullet
15824 @item
15825 McCabe cyclomatic complexity;
15826
15827 @item
15828 McCabe essential complexity;
15829
15830 @item
15831 maximal loop nesting level;
15832
15833 @item
15834 extra exit points (for subprograms);
15835 @end itemize
15836
15837 @noindent
15838 The McCabe cyclomatic complexity metric is defined
15839 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
15840
15841 According to McCabe, both control statements and short-circuit control forms
15842 should be taken into account when computing cyclomatic complexity.
15843 For Ada 2012 we have also take into account conditional expressions
15844 and quantified expressions. For each body, we compute three metric values:
15845
15846 @itemize @bullet
15847 @item
15848 the complexity introduced by control
15849 statements only, without taking into account short-circuit forms,
15850
15851 @item
15852 the complexity introduced by short-circuit control forms only, and
15853
15854 @item
15855 the total
15856 cyclomatic complexity, which is the sum of these two values.
15857 @end itemize
15858
15859 @noindent
15860
15861 The cyclomatic complexity is also computed for Ada 2012 expression functions.
15862 An expression function cannot have statements as its components, so only one
15863 metric value is computed as a cyclomatic complexity of an expression function.
15864
15865 The origin of cyclomatic complexity metric is the need to estimate the number
15866 of independent paths in the control flow graph that in turn gives the number
15867 of tests needed to satisfy paths coverage testing completeness criterion.
15868 Considered from the testing point of view, a static Ada @code{loop} (that is,
15869 the @code{loop} statement having static subtype in loop parameter
15870 specification) does not add to cyclomatic complexity. By providing
15871 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
15872 may specify that such loops should not be counted when computing the
15873 cyclomatic complexity metric
15874
15875 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
15876 counted for the code that is reduced by excluding all the pure structural Ada
15877 control statements. An compound statement is considered as a non-structural
15878 if it contains a @code{raise} or @code{return} statement as it subcomponent,
15879 or if it contains a @code{goto} statement that transfers the control outside
15880 the operator. A selective accept statement with @code{terminate} alternative
15881 is considered as non-structural statement. When computing this metric,
15882 @code{exit} statements are treated in the same way as @code{goto}
15883 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
15884
15885 The Ada essential complexity metric defined here is intended to quantify
15886 the extent to which the software is unstructured. It is adapted from
15887 the McCabe essential complexity metric defined in
15888 @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more
15889 suitable for typical Ada usage. For example, short circuit forms
15890 are not penalized as unstructured in the Ada essential complexity metric.
15891
15892 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
15893 the code in the exception handlers and in all the nested program units. The
15894 code of assertions and predicates (that is, subprogram preconditions and
15895 postconditions, subtype predicates and type invariants) is also skipped.
15896
15897 By default, all the complexity metrics are computed and reported.
15898 For more fine-grained control you can use
15899 the following switches:
15900
15901 @table @option
15902 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
15903
15904 @ifclear vms
15905 @cindex @option{--no-complexity@var{x}}
15906 @end ifclear
15907
15908 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
15909 Report all the complexity metrics
15910
15911 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
15912 Do not report any of complexity metrics
15913
15914 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
15915 Report the McCabe Cyclomatic Complexity
15916
15917 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
15918 Do not report the McCabe Cyclomatic Complexity
15919
15920 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
15921 Report the Essential Complexity
15922
15923 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
15924 Do not report the Essential Complexity
15925
15926 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
15927 Report maximal loop nesting level
15928
15929 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
15930 Do not report maximal loop nesting level
15931
15932 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
15933 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
15934 task bodies, entry bodies and statement sequences in package bodies.
15935 The metric is computed and reported for whole set of processed Ada sources
15936 only.
15937
15938 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
15939 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
15940 bodies, task bodies, entry bodies and statement sequences in package bodies
15941
15942 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
15943 @item ^-ne^/NO_EXITS_AS_GOTOS^
15944 Do not consider @code{exit} statements as @code{goto}s when
15945 computing Essential Complexity
15946
15947 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
15948 @item ^--no-static-loop^/NO_STATIC_LOOP^
15949 Do not consider static loops when computing cyclomatic complexity
15950
15951 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
15952 Report the extra exit points for subprogram bodies. As an exit point, this
15953 metric counts @code{return} statements and raise statements in case when the
15954 raised exception is not handled in the same body. In case of a function this
15955 metric subtracts 1 from the number of exit points, because a function body
15956 must contain at least one @code{return} statement.
15957
15958 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
15959 Do not report the extra exit points for subprogram bodies
15960 @end table
15961
15962
15963 @node Coupling Metrics Control
15964 @subsubsection Coupling Metrics Control
15965 @cindex Coupling metrics control in @command{gnatmetric}
15966
15967 @noindent
15968 @cindex Coupling metrics (in in @command{gnatmetric})
15969 Coupling metrics measure the dependencies between a given entity and other
15970 entities the program consists of. The goal of these metrics is to estimate the
15971 stability of the whole program considered as the collection of entities
15972 (modules, classes etc.).
15973
15974 Gnatmetric computes the following coupling metrics:
15975
15976 @itemize @bullet
15977
15978 @item
15979 @emph{object-oriented coupling} - for classes in traditional object-oriented
15980 sense;
15981
15982 @item
15983 @emph{unit coupling} - for all the program units making up a program;
15984
15985 @item
15986 @emph{control coupling} - this metric counts dependencies between a unit and
15987 only those units that define subprograms;
15988 @end itemize
15989
15990 @noindent
15991 Two kinds of coupling metrics are computed:
15992
15993 @table @asis
15994 @item fan-out coupling (efferent coupling)
15995 @cindex fan-out coupling
15996 @cindex efferent coupling
15997 the number of entities the given entity depends upon. It
15998 estimates in what extent the given entity depends on the changes in
15999 ``external world''
16000
16001 @item fan-in coupling (afferent coupling)
16002 @cindex fan-in coupling
16003 @cindex afferent coupling
16004 the number of entities that depend on a given entity.
16005 It estimates in what extent the ``external world'' depends on the changes in a
16006 given entity
16007 @end table
16008
16009 @noindent
16010
16011 Object-oriented coupling metrics are metrics that measure the dependencies
16012 between a given class (or a group of classes) and the other classes in the
16013 program. In this subsection the term ``class'' is used in its traditional
16014 object-oriented programming sense (an instantiable module that contains data
16015 and/or method members). A @emph{category} (of classes) is a group of closely
16016 related classes that are reused and/or modified together.
16017
16018 A class @code{K}'s fan-out coupling is the number of classes
16019 that @code{K} depends upon.
16020 A category's fan-out coupling is the number of classes outside the
16021 category that the classes inside the category depend upon.
16022
16023 A class @code{K}'s fan-in coupling is the number of classes
16024 that depend upon @code{K}.
16025 A category's fan-in coupling is the number of classes outside the
16026 category that depend on classes belonging to the category.
16027
16028 Ada's implementation of the object-oriented paradigm does not use the
16029 traditional class notion, so the definition of the coupling
16030 metrics for Ada maps the class and class category notions
16031 onto Ada constructs.
16032
16033 For the coupling metrics, several kinds of modules -- a library package,
16034 a library generic package, and a library generic package instantiation --
16035 that define a tagged type or an interface type are
16036 considered to be a class. A category consists of a library package (or
16037 a library generic package) that defines a tagged or an interface type,
16038 together with all its descendant (generic) packages that define tagged
16039 or interface types. That is a
16040 category is an Ada hierarchy of library-level program units. So class coupling
16041 in case of Ada is called as tagged coupling, and category coupling - as
16042 hierarchy coupling.
16043
16044 For any package counted as a class, its body and subunits (if any) are
16045 considered together with its spec when counting the dependencies, and coupling
16046 metrics are reported for spec units only. For dependencies between classes,
16047 the Ada semantic dependencies are considered. For object-oriented coupling
16048 metrics, only dependencies on units that are considered as classes, are
16049 considered.
16050
16051 For unit and control coupling also not compilation units but program units are
16052 counted. That is, for a package, its spec, its body and its subunits (if any)
16053 are considered as making up one unit, and the dependencies that are counted
16054 are the dependencies of all these compilation units collected together as
16055 the dependencies as a (whole) unit. And metrics are reported for spec
16056 compilation units only (or for a subprogram body unit in case if there is no
16057 separate spec for the given subprogram).
16058
16059 For unit coupling, dependencies between all kinds of program units are
16060 considered. For control coupling, for each unit the dependencies of this unit
16061 upon units that define subprograms are counted, so control fan-out coupling
16062 is reported for all units, but control fan-in coupling - only for the units
16063 that define subprograms.
16064
16065 The following simple example illustrates the difference between unit coupling
16066 and control coupling metrics:
16067
16068 @smallexample @c ada
16069 package Lib_1 is
16070 function F_1 (I : Integer) return Integer;
16071 end Lib_1;
16072
16073 package Lib_2 is
16074 type T_2 is new Integer;
16075 end Lib_2;
16076
16077 package body Lib_1 is
16078 function F_1 (I : Integer) return Integer is
16079 begin
16080 return I + 1;
16081 end F_1;
16082 end Lib_1;
16083
16084 with Lib_2; use Lib_2;
16085 package Pack is
16086 Var : T_2;
16087 function Fun (I : Integer) return Integer;
16088 end Pack;
16089
16090 with Lib_1; use Lib_1;
16091 package body Pack is
16092 function Fun (I : Integer) return Integer is
16093 begin
16094 return F_1 (I);
16095 end Fun;
16096 end Pack;
16097 @end smallexample
16098
16099 @noindent
16100 if we apply @command{gnatmetric} with @code{--coupling-all} option to these
16101 units, the result will be:
16102
16103 @smallexample
16104 Coupling metrics:
16105 =================
16106 Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads)
16107 control fan-out coupling : 0
16108 control fan-in coupling : 1
16109 unit fan-out coupling : 0
16110 unit fan-in coupling : 1
16111
16112 Unit Pack (C:\customers\662\L406-007\pack.ads)
16113 control fan-out coupling : 1
16114 control fan-in coupling : 0
16115 unit fan-out coupling : 2
16116 unit fan-in coupling : 0
16117
16118 Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads)
16119 control fan-out coupling : 0
16120 unit fan-out coupling : 0
16121 unit fan-in coupling : 1
16122 @end smallexample
16123
16124 @noindent
16125 The result does not contain values for object-oriented
16126 coupling because none of the argument unit contains a tagged type and
16127 therefore none of these units can be treated as a class.
16128
16129 @code{Pack} (considered as a program unit, that is spec+body) depends on two
16130 units - @code{Lib_1} @code{and Lib_2}, therefore it has unit fan-out coupling
16131 equals to 2. And nothing depend on it, so its unit fan-in coupling is 0 as
16132 well as control fan-in coupling. Only one of the units @code{Pack} depends
16133 upon defines a subprogram, so its control fan-out coupling is 1.
16134
16135 @code{Lib_2} depends on nothing, so fan-out metrics for it are 0. It does
16136 not define a subprogram, so control fan-in metric cannot be applied to it,
16137 and there is one unit that depends on it (@code{Pack}), so it has
16138 unit fan-in coupling equals to 1.
16139
16140 @code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram.
16141 So it has control fan-in coupling equals to 1 (because there is a unit
16142 depending on it).
16143
16144 When computing coupling metrics, @command{gnatmetric} counts only
16145 dependencies between units that are arguments of the @command{gnatmetric}
16146 call. Coupling metrics are program-wide (or project-wide) metrics, so to
16147 get a valid result, you should call @command{gnatmetric} for
16148 the whole set of sources that make up your program. It can be done
16149 by calling @command{gnatmetric} from the GNAT driver with @option{-U}
16150 option (see @ref{The GNAT Driver and Project Files} for details).
16151
16152 By default, all the coupling metrics are disabled. You can use the following
16153 switches to specify the coupling metrics to be computed and reported:
16154
16155 @table @option
16156
16157 @ifclear vms
16158 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
16159 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
16160 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
16161 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
16162 @end ifclear
16163
16164 @ifset vms
16165 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
16166 @end ifset
16167
16168 @item ^--coupling-all^/COUPLING_METRICS=ALL^
16169 Report all the coupling metrics
16170
16171 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
16172 Report tagged (class) fan-out coupling
16173
16174 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
16175 Report tagged (class) fan-in coupling
16176
16177 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
16178 Report hierarchy (category) fan-out coupling
16179
16180 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
16181 Report hierarchy (category) fan-in coupling
16182
16183 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
16184 Report unit fan-out coupling
16185
16186 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
16187 Report unit fan-in coupling
16188
16189 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
16190 Report control fan-out coupling
16191
16192 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
16193 Report control fan-in coupling
16194 @end table
16195
16196 @node Other gnatmetric Switches
16197 @subsection Other @code{gnatmetric} Switches
16198
16199 @noindent
16200 Additional @command{gnatmetric} switches are as follows:
16201
16202 @table @option
16203 @item --version
16204 @cindex @option{--version} @command{gnatmetric}
16205 Display Copyright and version, then exit disregarding all other options.
16206
16207 @item --help
16208 @cindex @option{--help} @command{gnatmetric}
16209 Display usage, then exit disregarding all other options.
16210
16211 @item ^-files @var{filename}^/FILES=@var{filename}^
16212 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
16213 Take the argument source files from the specified file. This file should be an
16214 ordinary text file containing file names separated by spaces or
16215 line breaks. You can use this switch more than once in the same call to
16216 @command{gnatmetric}. You also can combine this switch with
16217 an explicit list of files.
16218
16219 @item ^-v^/VERBOSE^
16220 @cindex @option{^-v^/VERBOSE^} (@code{gnatmetric})
16221 Verbose mode;
16222 @command{gnatmetric} generates version information and then
16223 a trace of sources being processed.
16224
16225 @item ^-q^/QUIET^
16226 @cindex @option{^-q^/QUIET^} (@code{gnatmetric})
16227 Quiet mode.
16228 @end table
16229
16230 @node Generate project-wide metrics
16231 @subsection Generate project-wide metrics
16232
16233 In order to compute metrics on all units of a given project, you can use
16234 the @command{gnat} driver along with the @option{-P} option:
16235 @smallexample
16236 gnat metric -Pproj
16237 @end smallexample
16238
16239 @noindent
16240 If the project @code{proj} depends upon other projects, you can compute
16241 the metrics on the project closure using the @option{-U} option:
16242 @smallexample
16243 gnat metric -Pproj -U
16244 @end smallexample
16245
16246 @noindent
16247 Finally, if not all the units are relevant to a particular main
16248 program in the project closure, you can generate metrics for the set
16249 of units needed to create a given main program (unit closure) using
16250 the @option{-U} option followed by the name of the main unit:
16251 @smallexample
16252 gnat metric -Pproj -U main
16253 @end smallexample
16254
16255
16256 @c ***********************************
16257 @node File Name Krunching with gnatkr
16258 @chapter File Name Krunching with @code{gnatkr}
16259 @findex gnatkr
16260
16261 @noindent
16262 This chapter discusses the method used by the compiler to shorten
16263 the default file names chosen for Ada units so that they do not
16264 exceed the maximum length permitted. It also describes the
16265 @code{gnatkr} utility that can be used to determine the result of
16266 applying this shortening.
16267 @menu
16268 * About gnatkr::
16269 * Using gnatkr::
16270 * Krunching Method::
16271 * Examples of gnatkr Usage::
16272 @end menu
16273
16274 @node About gnatkr
16275 @section About @code{gnatkr}
16276
16277 @noindent
16278 The default file naming rule in GNAT
16279 is that the file name must be derived from
16280 the unit name. The exact default rule is as follows:
16281 @itemize @bullet
16282 @item
16283 Take the unit name and replace all dots by hyphens.
16284 @item
16285 If such a replacement occurs in the
16286 second character position of a name, and the first character is
16287 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
16288 then replace the dot by the character
16289 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
16290 instead of a minus.
16291 @end itemize
16292 The reason for this exception is to avoid clashes
16293 with the standard names for children of System, Ada, Interfaces,
16294 and GNAT, which use the prefixes
16295 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
16296 respectively.
16297
16298 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
16299 switch of the compiler activates a ``krunching''
16300 circuit that limits file names to nn characters (where nn is a decimal
16301 integer). For example, using OpenVMS,
16302 where the maximum file name length is
16303 39, the value of nn is usually set to 39, but if you want to generate
16304 a set of files that would be usable if ported to a system with some
16305 different maximum file length, then a different value can be specified.
16306 The default value of 39 for OpenVMS need not be specified.
16307
16308 The @code{gnatkr} utility can be used to determine the krunched name for
16309 a given file, when krunched to a specified maximum length.
16310
16311 @node Using gnatkr
16312 @section Using @code{gnatkr}
16313
16314 @noindent
16315 The @code{gnatkr} command has the form
16316
16317 @ifclear vms
16318 @smallexample
16319 @c $ gnatkr @var{name} @ovar{length}
16320 @c Expanding @ovar macro inline (explanation in macro def comments)
16321 $ gnatkr @var{name} @r{[}@var{length}@r{]}
16322 @end smallexample
16323 @end ifclear
16324
16325 @ifset vms
16326 @smallexample
16327 $ gnatkr @var{name} /COUNT=nn
16328 @end smallexample
16329 @end ifset
16330
16331 @noindent
16332 @var{name} is the uncrunched file name, derived from the name of the unit
16333 in the standard manner described in the previous section (i.e., in particular
16334 all dots are replaced by hyphens). The file name may or may not have an
16335 extension (defined as a suffix of the form period followed by arbitrary
16336 characters other than period). If an extension is present then it will
16337 be preserved in the output. For example, when krunching @file{hellofile.ads}
16338 to eight characters, the result will be hellofil.ads.
16339
16340 Note: for compatibility with previous versions of @code{gnatkr} dots may
16341 appear in the name instead of hyphens, but the last dot will always be
16342 taken as the start of an extension. So if @code{gnatkr} is given an argument
16343 such as @file{Hello.World.adb} it will be treated exactly as if the first
16344 period had been a hyphen, and for example krunching to eight characters
16345 gives the result @file{hellworl.adb}.
16346
16347 Note that the result is always all lower case (except on OpenVMS where it is
16348 all upper case). Characters of the other case are folded as required.
16349
16350 @var{length} represents the length of the krunched name. The default
16351 when no argument is given is ^8^39^ characters. A length of zero stands for
16352 unlimited, in other words do not chop except for system files where the
16353 implied crunching length is always eight characters.
16354
16355 @noindent
16356 The output is the krunched name. The output has an extension only if the
16357 original argument was a file name with an extension.
16358
16359 @node Krunching Method
16360 @section Krunching Method
16361
16362 @noindent
16363 The initial file name is determined by the name of the unit that the file
16364 contains. The name is formed by taking the full expanded name of the
16365 unit and replacing the separating dots with hyphens and
16366 using ^lowercase^uppercase^
16367 for all letters, except that a hyphen in the second character position is
16368 replaced by a ^tilde^dollar sign^ if the first character is
16369 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
16370 The extension is @code{.ads} for a
16371 spec and @code{.adb} for a body.
16372 Krunching does not affect the extension, but the file name is shortened to
16373 the specified length by following these rules:
16374
16375 @itemize @bullet
16376 @item
16377 The name is divided into segments separated by hyphens, tildes or
16378 underscores and all hyphens, tildes, and underscores are
16379 eliminated. If this leaves the name short enough, we are done.
16380
16381 @item
16382 If the name is too long, the longest segment is located (left-most
16383 if there are two of equal length), and shortened by dropping
16384 its last character. This is repeated until the name is short enough.
16385
16386 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16387 to fit the name into 8 characters as required by some operating systems.
16388
16389 @smallexample
16390 our-strings-wide_fixed 22
16391 our strings wide fixed 19
16392 our string wide fixed 18
16393 our strin wide fixed 17
16394 our stri wide fixed 16
16395 our stri wide fixe 15
16396 our str wide fixe 14
16397 our str wid fixe 13
16398 our str wid fix 12
16399 ou str wid fix 11
16400 ou st wid fix 10
16401 ou st wi fix 9
16402 ou st wi fi 8
16403 Final file name: oustwifi.adb
16404 @end smallexample
16405
16406 @item
16407 The file names for all predefined units are always krunched to eight
16408 characters. The krunching of these predefined units uses the following
16409 special prefix replacements:
16410
16411 @table @file
16412 @item ada-
16413 replaced by @file{^a^A^-}
16414
16415 @item gnat-
16416 replaced by @file{^g^G^-}
16417
16418 @item interfaces-
16419 replaced by @file{^i^I^-}
16420
16421 @item system-
16422 replaced by @file{^s^S^-}
16423 @end table
16424
16425 These system files have a hyphen in the second character position. That
16426 is why normal user files replace such a character with a
16427 ^tilde^dollar sign^, to
16428 avoid confusion with system file names.
16429
16430 As an example of this special rule, consider
16431 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16432
16433 @smallexample
16434 ada-strings-wide_fixed 22
16435 a- strings wide fixed 18
16436 a- string wide fixed 17
16437 a- strin wide fixed 16
16438 a- stri wide fixed 15
16439 a- stri wide fixe 14
16440 a- str wide fixe 13
16441 a- str wid fixe 12
16442 a- str wid fix 11
16443 a- st wid fix 10
16444 a- st wi fix 9
16445 a- st wi fi 8
16446 Final file name: a-stwifi.adb
16447 @end smallexample
16448 @end itemize
16449
16450 Of course no file shortening algorithm can guarantee uniqueness over all
16451 possible unit names, and if file name krunching is used then it is your
16452 responsibility to ensure that no name clashes occur. The utility
16453 program @code{gnatkr} is supplied for conveniently determining the
16454 krunched name of a file.
16455
16456 @node Examples of gnatkr Usage
16457 @section Examples of @code{gnatkr} Usage
16458
16459 @smallexample
16460 @iftex
16461 @leftskip=0cm
16462 @end iftex
16463 @ifclear vms
16464 $ gnatkr very_long_unit_name.ads --> velounna.ads
16465 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16466 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16467 $ gnatkr grandparent-parent-child --> grparchi
16468 @end ifclear
16469 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16470 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16471 @end smallexample
16472
16473 @node Preprocessing with gnatprep
16474 @chapter Preprocessing with @code{gnatprep}
16475 @findex gnatprep
16476
16477 @noindent
16478 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
16479 preprocessing.
16480 Although designed for use with GNAT, @code{gnatprep} does not depend on any
16481 special GNAT features.
16482 For further discussion of conditional compilation in general, see
16483 @ref{Conditional Compilation}.
16484
16485 @menu
16486 * Preprocessing Symbols::
16487 * Using gnatprep::
16488 * Switches for gnatprep::
16489 * Form of Definitions File::
16490 * Form of Input Text for gnatprep::
16491 @end menu
16492
16493 @node Preprocessing Symbols
16494 @section Preprocessing Symbols
16495
16496 @noindent
16497 Preprocessing symbols are defined in definition files and referred to in
16498 sources to be preprocessed. A Preprocessing symbol is an identifier, following
16499 normal Ada (case-insensitive) rules for its syntax, with the restriction that
16500 all characters need to be in the ASCII set (no accented letters).
16501
16502 @node Using gnatprep
16503 @section Using @code{gnatprep}
16504
16505 @noindent
16506 To call @code{gnatprep} use
16507
16508 @smallexample
16509 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
16510 @c Expanding @ovar macro inline (explanation in macro def comments)
16511 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
16512 @end smallexample
16513
16514 @noindent
16515 where
16516 @table @var
16517 @item switches
16518 is an optional sequence of switches as described in the next section.
16519
16520 @item infile
16521 is the full name of the input file, which is an Ada source
16522 file containing preprocessor directives.
16523
16524 @item outfile
16525 is the full name of the output file, which is an Ada source
16526 in standard Ada form. When used with GNAT, this file name will
16527 normally have an ads or adb suffix.
16528
16529 @item deffile
16530 is the full name of a text file containing definitions of
16531 preprocessing symbols to be referenced by the preprocessor. This argument is
16532 optional, and can be replaced by the use of the @option{-D} switch.
16533
16534 @end table
16535
16536 @node Switches for gnatprep
16537 @section Switches for @code{gnatprep}
16538
16539 @table @option
16540 @c !sort!
16541
16542 @item ^-b^/BLANK_LINES^
16543 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16544 Causes both preprocessor lines and the lines deleted by
16545 preprocessing to be replaced by blank lines in the output source file,
16546 preserving line numbers in the output file.
16547
16548 @item ^-c^/COMMENTS^
16549 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16550 Causes both preprocessor lines and the lines deleted
16551 by preprocessing to be retained in the output source as comments marked
16552 with the special string @code{"--! "}. This option will result in line numbers
16553 being preserved in the output file.
16554
16555 @item ^-C^/REPLACE_IN_COMMENTS^
16556 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
16557 Causes comments to be scanned. Normally comments are ignored by gnatprep.
16558 If this option is specified, then comments are scanned and any $symbol
16559 substitutions performed as in program text. This is particularly useful
16560 when structured comments are used (e.g., when writing programs in the
16561 SPARK dialect of Ada). Note that this switch is not available when
16562 doing integrated preprocessing (it would be useless in this context
16563 since comments are ignored by the compiler in any case).
16564
16565 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16566 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16567 Defines a new preprocessing symbol, associated with value. If no value is given
16568 on the command line, then symbol is considered to be @code{True}. This switch
16569 can be used in place of a definition file.
16570
16571 @ifset vms
16572 @item /REMOVE
16573 @cindex @option{/REMOVE} (@command{gnatprep})
16574 This is the default setting which causes lines deleted by preprocessing
16575 to be entirely removed from the output file.
16576 @end ifset
16577
16578 @item ^-r^/REFERENCE^
16579 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16580 Causes a @code{Source_Reference} pragma to be generated that
16581 references the original input file, so that error messages will use
16582 the file name of this original file. The use of this switch implies
16583 that preprocessor lines are not to be removed from the file, so its
16584 use will force @option{^-b^/BLANK_LINES^} mode if
16585 @option{^-c^/COMMENTS^}
16586 has not been specified explicitly.
16587
16588 Note that if the file to be preprocessed contains multiple units, then
16589 it will be necessary to @code{gnatchop} the output file from
16590 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16591 in the preprocessed file, it will be respected by
16592 @code{gnatchop ^-r^/REFERENCE^}
16593 so that the final chopped files will correctly refer to the original
16594 input source file for @code{gnatprep}.
16595
16596 @item ^-s^/SYMBOLS^
16597 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16598 Causes a sorted list of symbol names and values to be
16599 listed on the standard output file.
16600
16601 @item ^-u^/UNDEFINED^
16602 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16603 Causes undefined symbols to be treated as having the value FALSE in the context
16604 of a preprocessor test. In the absence of this option, an undefined symbol in
16605 a @code{#if} or @code{#elsif} test will be treated as an error.
16606
16607 @end table
16608
16609 @ifclear vms
16610 @noindent
16611 Note: if neither @option{-b} nor @option{-c} is present,
16612 then preprocessor lines and
16613 deleted lines are completely removed from the output, unless -r is
16614 specified, in which case -b is assumed.
16615 @end ifclear
16616
16617 @node Form of Definitions File
16618 @section Form of Definitions File
16619
16620 @noindent
16621 The definitions file contains lines of the form
16622
16623 @smallexample
16624 symbol := value
16625 @end smallexample
16626
16627 @noindent
16628 where symbol is a preprocessing symbol, and value is one of the following:
16629
16630 @itemize @bullet
16631 @item
16632 Empty, corresponding to a null substitution
16633 @item
16634 A string literal using normal Ada syntax
16635 @item
16636 Any sequence of characters from the set
16637 (letters, digits, period, underline).
16638 @end itemize
16639
16640 @noindent
16641 Comment lines may also appear in the definitions file, starting with
16642 the usual @code{--},
16643 and comments may be added to the definitions lines.
16644
16645 @node Form of Input Text for gnatprep
16646 @section Form of Input Text for @code{gnatprep}
16647
16648 @noindent
16649 The input text may contain preprocessor conditional inclusion lines,
16650 as well as general symbol substitution sequences.
16651
16652 The preprocessor conditional inclusion commands have the form
16653
16654 @smallexample
16655 @group
16656 @cartouche
16657 #if @i{expression} @r{[}then@r{]}
16658 lines
16659 #elsif @i{expression} @r{[}then@r{]}
16660 lines
16661 #elsif @i{expression} @r{[}then@r{]}
16662 lines
16663 @dots{}
16664 #else
16665 lines
16666 #end if;
16667 @end cartouche
16668 @end group
16669 @end smallexample
16670
16671 @noindent
16672 In this example, @i{expression} is defined by the following grammar:
16673 @smallexample
16674 @i{expression} ::= <symbol>
16675 @i{expression} ::= <symbol> = "<value>"
16676 @i{expression} ::= <symbol> = <symbol>
16677 @i{expression} ::= <symbol> 'Defined
16678 @i{expression} ::= not @i{expression}
16679 @i{expression} ::= @i{expression} and @i{expression}
16680 @i{expression} ::= @i{expression} or @i{expression}
16681 @i{expression} ::= @i{expression} and then @i{expression}
16682 @i{expression} ::= @i{expression} or else @i{expression}
16683 @i{expression} ::= ( @i{expression} )
16684 @end smallexample
16685
16686 The following restriction exists: it is not allowed to have "and" or "or"
16687 following "not" in the same expression without parentheses. For example, this
16688 is not allowed:
16689
16690 @smallexample
16691 not X or Y
16692 @end smallexample
16693
16694 This should be one of the following:
16695
16696 @smallexample
16697 (not X) or Y
16698 not (X or Y)
16699 @end smallexample
16700
16701 @noindent
16702 For the first test (@i{expression} ::= <symbol>) the symbol must have
16703 either the value true or false, that is to say the right-hand of the
16704 symbol definition must be one of the (case-insensitive) literals
16705 @code{True} or @code{False}. If the value is true, then the
16706 corresponding lines are included, and if the value is false, they are
16707 excluded.
16708
16709 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
16710 the symbol has been defined in the definition file or by a @option{-D}
16711 switch on the command line. Otherwise, the test is false.
16712
16713 The equality tests are case insensitive, as are all the preprocessor lines.
16714
16715 If the symbol referenced is not defined in the symbol definitions file,
16716 then the effect depends on whether or not switch @option{-u}
16717 is specified. If so, then the symbol is treated as if it had the value
16718 false and the test fails. If this switch is not specified, then
16719 it is an error to reference an undefined symbol. It is also an error to
16720 reference a symbol that is defined with a value other than @code{True}
16721 or @code{False}.
16722
16723 The use of the @code{not} operator inverts the sense of this logical test.
16724 The @code{not} operator cannot be combined with the @code{or} or @code{and}
16725 operators, without parentheses. For example, "if not X or Y then" is not
16726 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
16727
16728 The @code{then} keyword is optional as shown
16729
16730 The @code{#} must be the first non-blank character on a line, but
16731 otherwise the format is free form. Spaces or tabs may appear between
16732 the @code{#} and the keyword. The keywords and the symbols are case
16733 insensitive as in normal Ada code. Comments may be used on a
16734 preprocessor line, but other than that, no other tokens may appear on a
16735 preprocessor line. Any number of @code{elsif} clauses can be present,
16736 including none at all. The @code{else} is optional, as in Ada.
16737
16738 The @code{#} marking the start of a preprocessor line must be the first
16739 non-blank character on the line, i.e., it must be preceded only by
16740 spaces or horizontal tabs.
16741
16742 Symbol substitution outside of preprocessor lines is obtained by using
16743 the sequence
16744
16745 @smallexample
16746 $symbol
16747 @end smallexample
16748
16749 @noindent
16750 anywhere within a source line, except in a comment or within a
16751 string literal. The identifier
16752 following the @code{$} must match one of the symbols defined in the symbol
16753 definition file, and the result is to substitute the value of the
16754 symbol in place of @code{$symbol} in the output file.
16755
16756 Note that although the substitution of strings within a string literal
16757 is not possible, it is possible to have a symbol whose defined value is
16758 a string literal. So instead of setting XYZ to @code{hello} and writing:
16759
16760 @smallexample
16761 Header : String := "$XYZ";
16762 @end smallexample
16763
16764 @noindent
16765 you should set XYZ to @code{"hello"} and write:
16766
16767 @smallexample
16768 Header : String := $XYZ;
16769 @end smallexample
16770
16771 @noindent
16772 and then the substitution will occur as desired.
16773
16774 @node The GNAT Library Browser gnatls
16775 @chapter The GNAT Library Browser @code{gnatls}
16776 @findex gnatls
16777 @cindex Library browser
16778
16779 @noindent
16780 @code{gnatls} is a tool that outputs information about compiled
16781 units. It gives the relationship between objects, unit names and source
16782 files. It can also be used to check the source dependencies of a unit
16783 as well as various characteristics.
16784
16785 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
16786 driver (see @ref{The GNAT Driver and Project Files}).
16787
16788 @menu
16789 * Running gnatls::
16790 * Switches for gnatls::
16791 * Examples of gnatls Usage::
16792 @end menu
16793
16794 @node Running gnatls
16795 @section Running @code{gnatls}
16796
16797 @noindent
16798 The @code{gnatls} command has the form
16799
16800 @smallexample
16801 $ gnatls switches @var{object_or_ali_file}
16802 @end smallexample
16803
16804 @noindent
16805 The main argument is the list of object or @file{ali} files
16806 (@pxref{The Ada Library Information Files})
16807 for which information is requested.
16808
16809 In normal mode, without additional option, @code{gnatls} produces a
16810 four-column listing. Each line represents information for a specific
16811 object. The first column gives the full path of the object, the second
16812 column gives the name of the principal unit in this object, the third
16813 column gives the status of the source and the fourth column gives the
16814 full path of the source representing this unit.
16815 Here is a simple example of use:
16816
16817 @smallexample
16818 $ gnatls *.o
16819 ^./^[]^demo1.o demo1 DIF demo1.adb
16820 ^./^[]^demo2.o demo2 OK demo2.adb
16821 ^./^[]^hello.o h1 OK hello.adb
16822 ^./^[]^instr-child.o instr.child MOK instr-child.adb
16823 ^./^[]^instr.o instr OK instr.adb
16824 ^./^[]^tef.o tef DIF tef.adb
16825 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
16826 ^./^[]^tgef.o tgef DIF tgef.adb
16827 @end smallexample
16828
16829 @noindent
16830 The first line can be interpreted as follows: the main unit which is
16831 contained in
16832 object file @file{demo1.o} is demo1, whose main source is in
16833 @file{demo1.adb}. Furthermore, the version of the source used for the
16834 compilation of demo1 has been modified (DIF). Each source file has a status
16835 qualifier which can be:
16836
16837 @table @code
16838 @item OK (unchanged)
16839 The version of the source file used for the compilation of the
16840 specified unit corresponds exactly to the actual source file.
16841
16842 @item MOK (slightly modified)
16843 The version of the source file used for the compilation of the
16844 specified unit differs from the actual source file but not enough to
16845 require recompilation. If you use gnatmake with the qualifier
16846 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
16847 MOK will not be recompiled.
16848
16849 @item DIF (modified)
16850 No version of the source found on the path corresponds to the source
16851 used to build this object.
16852
16853 @item ??? (file not found)
16854 No source file was found for this unit.
16855
16856 @item HID (hidden, unchanged version not first on PATH)
16857 The version of the source that corresponds exactly to the source used
16858 for compilation has been found on the path but it is hidden by another
16859 version of the same source that has been modified.
16860
16861 @end table
16862
16863 @node Switches for gnatls
16864 @section Switches for @code{gnatls}
16865
16866 @noindent
16867 @code{gnatls} recognizes the following switches:
16868
16869 @table @option
16870 @c !sort!
16871 @cindex @option{--version} @command{gnatls}
16872 Display Copyright and version, then exit disregarding all other options.
16873
16874 @item --help
16875 @cindex @option{--help} @command{gnatls}
16876 If @option{--version} was not used, display usage, then exit disregarding
16877 all other options.
16878
16879 @item ^-a^/ALL_UNITS^
16880 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
16881 Consider all units, including those of the predefined Ada library.
16882 Especially useful with @option{^-d^/DEPENDENCIES^}.
16883
16884 @item ^-d^/DEPENDENCIES^
16885 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
16886 List sources from which specified units depend on.
16887
16888 @item ^-h^/OUTPUT=OPTIONS^
16889 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
16890 Output the list of options.
16891
16892 @item ^-o^/OUTPUT=OBJECTS^
16893 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
16894 Only output information about object files.
16895
16896 @item ^-s^/OUTPUT=SOURCES^
16897 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
16898 Only output information about source files.
16899
16900 @item ^-u^/OUTPUT=UNITS^
16901 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
16902 Only output information about compilation units.
16903
16904 @item ^-files^/FILES^=@var{file}
16905 @cindex @option{^-files^/FILES^} (@code{gnatls})
16906 Take as arguments the files listed in text file @var{file}.
16907 Text file @var{file} may contain empty lines that are ignored.
16908 Each nonempty line should contain the name of an existing file.
16909 Several such switches may be specified simultaneously.
16910
16911 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
16912 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
16913 @itemx ^-I^/SEARCH=^@var{dir}
16914 @itemx ^-I-^/NOCURRENT_DIRECTORY^
16915 @itemx -nostdinc
16916 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
16917 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
16918 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
16919 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
16920 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
16921 flags (@pxref{Switches for gnatmake}).
16922
16923 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^@var{dir}
16924 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (@code{gnatls})
16925 Add @var{dir} at the beginning of the project search dir.
16926
16927 @item --RTS=@var{rts-path}
16928 @cindex @option{--RTS} (@code{gnatls})
16929 Specifies the default location of the runtime library. Same meaning as the
16930 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
16931
16932 @item ^-v^/OUTPUT=VERBOSE^
16933 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
16934 Verbose mode. Output the complete source, object and project paths. Do not use
16935 the default column layout but instead use long format giving as much as
16936 information possible on each requested units, including special
16937 characteristics such as:
16938
16939 @table @code
16940 @item Preelaborable
16941 The unit is preelaborable in the Ada sense.
16942
16943 @item No_Elab_Code
16944 No elaboration code has been produced by the compiler for this unit.
16945
16946 @item Pure
16947 The unit is pure in the Ada sense.
16948
16949 @item Elaborate_Body
16950 The unit contains a pragma Elaborate_Body.
16951
16952 @item Remote_Types
16953 The unit contains a pragma Remote_Types.
16954
16955 @item Shared_Passive
16956 The unit contains a pragma Shared_Passive.
16957
16958 @item Predefined
16959 This unit is part of the predefined environment and cannot be modified
16960 by the user.
16961
16962 @item Remote_Call_Interface
16963 The unit contains a pragma Remote_Call_Interface.
16964
16965 @end table
16966
16967 @end table
16968
16969 @node Examples of gnatls Usage
16970 @section Example of @code{gnatls} Usage
16971 @ifclear vms
16972
16973 @noindent
16974 Example of using the verbose switch. Note how the source and
16975 object paths are affected by the -I switch.
16976
16977 @smallexample
16978 $ gnatls -v -I.. demo1.o
16979
16980 GNATLS 5.03w (20041123-34)
16981 Copyright 1997-2004 Free Software Foundation, Inc.
16982
16983 Source Search Path:
16984 <Current_Directory>
16985 ../
16986 /home/comar/local/adainclude/
16987
16988 Object Search Path:
16989 <Current_Directory>
16990 ../
16991 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
16992
16993 Project Search Path:
16994 <Current_Directory>
16995 /home/comar/local/lib/gnat/
16996
16997 ./demo1.o
16998 Unit =>
16999 Name => demo1
17000 Kind => subprogram body
17001 Flags => No_Elab_Code
17002 Source => demo1.adb modified
17003 @end smallexample
17004
17005 @noindent
17006 The following is an example of use of the dependency list.
17007 Note the use of the -s switch
17008 which gives a straight list of source files. This can be useful for
17009 building specialized scripts.
17010
17011 @smallexample
17012 $ gnatls -d demo2.o
17013 ./demo2.o demo2 OK demo2.adb
17014 OK gen_list.ads
17015 OK gen_list.adb
17016 OK instr.ads
17017 OK instr-child.ads
17018
17019 $ gnatls -d -s -a demo1.o
17020 demo1.adb
17021 /home/comar/local/adainclude/ada.ads
17022 /home/comar/local/adainclude/a-finali.ads
17023 /home/comar/local/adainclude/a-filico.ads
17024 /home/comar/local/adainclude/a-stream.ads
17025 /home/comar/local/adainclude/a-tags.ads
17026 gen_list.ads
17027 gen_list.adb
17028 /home/comar/local/adainclude/gnat.ads
17029 /home/comar/local/adainclude/g-io.ads
17030 instr.ads
17031 /home/comar/local/adainclude/system.ads
17032 /home/comar/local/adainclude/s-exctab.ads
17033 /home/comar/local/adainclude/s-finimp.ads
17034 /home/comar/local/adainclude/s-finroo.ads
17035 /home/comar/local/adainclude/s-secsta.ads
17036 /home/comar/local/adainclude/s-stalib.ads
17037 /home/comar/local/adainclude/s-stoele.ads
17038 /home/comar/local/adainclude/s-stratt.ads
17039 /home/comar/local/adainclude/s-tasoli.ads
17040 /home/comar/local/adainclude/s-unstyp.ads
17041 /home/comar/local/adainclude/unchconv.ads
17042 @end smallexample
17043 @end ifclear
17044
17045 @ifset vms
17046 @smallexample
17047 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
17048
17049 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
17050 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
17051 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
17052 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
17053 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
17054 demo1.adb
17055 gen_list.ads
17056 gen_list.adb
17057 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
17058 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
17059 instr.ads
17060 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
17061 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
17062 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
17063 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
17064 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
17065 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
17066 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
17067 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
17068 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
17069 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
17070 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
17071 @end smallexample
17072 @end ifset
17073
17074 @node Cleaning Up with gnatclean
17075 @chapter Cleaning Up with @code{gnatclean}
17076 @findex gnatclean
17077 @cindex Cleaning tool
17078
17079 @noindent
17080 @code{gnatclean} is a tool that allows the deletion of files produced by the
17081 compiler, binder and linker, including ALI files, object files, tree files,
17082 expanded source files, library files, interface copy source files, binder
17083 generated files and executable files.
17084
17085 @menu
17086 * Running gnatclean::
17087 * Switches for gnatclean::
17088 @c * Examples of gnatclean Usage::
17089 @end menu
17090
17091 @node Running gnatclean
17092 @section Running @code{gnatclean}
17093
17094 @noindent
17095 The @code{gnatclean} command has the form:
17096
17097 @smallexample
17098 $ gnatclean switches @var{names}
17099 @end smallexample
17100
17101 @noindent
17102 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
17103 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
17104 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
17105
17106 @noindent
17107 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17108 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
17109 the linker. In informative-only mode, specified by switch
17110 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
17111 normal mode is listed, but no file is actually deleted.
17112
17113 @node Switches for gnatclean
17114 @section Switches for @code{gnatclean}
17115
17116 @noindent
17117 @code{gnatclean} recognizes the following switches:
17118
17119 @table @option
17120 @c !sort!
17121 @cindex @option{--version} @command{gnatclean}
17122 Display Copyright and version, then exit disregarding all other options.
17123
17124 @item --help
17125 @cindex @option{--help} @command{gnatclean}
17126 If @option{--version} was not used, display usage, then exit disregarding
17127 all other options.
17128
17129 @item ^--subdirs^/SUBDIRS^=subdir
17130 Actual object directory of each project file is the subdirectory subdir of the
17131 object directory specified or defaulted in the project file.
17132
17133 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
17134 By default, shared library projects are not allowed to import static library
17135 projects. When this switch is used on the command line, this restriction is
17136 relaxed.
17137
17138 @item ^-c^/COMPILER_FILES_ONLY^
17139 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
17140 Only attempt to delete the files produced by the compiler, not those produced
17141 by the binder or the linker. The files that are not to be deleted are library
17142 files, interface copy files, binder generated files and executable files.
17143
17144 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
17145 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17146 Indicate that ALI and object files should normally be found in directory
17147 @var{dir}.
17148
17149 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17150 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17151 When using project files, if some errors or warnings are detected during
17152 parsing and verbose mode is not in effect (no use of switch
17153 ^-v^/VERBOSE^), then error lines start with the full path name of the project
17154 file, rather than its simple file name.
17155
17156 @item ^-h^/HELP^
17157 @cindex @option{^-h^/HELP^} (@code{gnatclean})
17158 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17159
17160 @item ^-n^/NODELETE^
17161 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17162 Informative-only mode. Do not delete any files. Output the list of the files
17163 that would have been deleted if this switch was not specified.
17164
17165 @item ^-P^/PROJECT_FILE=^@var{project}
17166 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17167 Use project file @var{project}. Only one such switch can be used.
17168 When cleaning a project file, the files produced by the compilation of the
17169 immediate sources or inherited sources of the project files are to be
17170 deleted. This is not depending on the presence or not of executable names
17171 on the command line.
17172
17173 @item ^-q^/QUIET^
17174 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
17175 Quiet output. If there are no errors, do not output anything, except in
17176 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17177 (switch ^-n^/NODELETE^).
17178
17179 @item ^-r^/RECURSIVE^
17180 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17181 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17182 clean all imported and extended project files, recursively. If this switch
17183 is not specified, only the files related to the main project file are to be
17184 deleted. This switch has no effect if no project file is specified.
17185
17186 @item ^-v^/VERBOSE^
17187 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17188 Verbose mode.
17189
17190 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17191 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17192 Indicates the verbosity of the parsing of GNAT project files.
17193 @xref{Switches Related to Project Files}.
17194
17195 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17196 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17197 Indicates that external variable @var{name} has the value @var{value}.
17198 The Project Manager will use this value for occurrences of
17199 @code{external(name)} when parsing the project file.
17200 @xref{Switches Related to Project Files}.
17201
17202 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17203 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17204 When searching for ALI and object files, look in directory
17205 @var{dir}.
17206
17207 @item ^-I^/SEARCH=^@var{dir}
17208 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17209 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17210
17211 @item ^-I-^/NOCURRENT_DIRECTORY^
17212 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
17213 @cindex Source files, suppressing search
17214 Do not look for ALI or object files in the directory
17215 where @code{gnatclean} was invoked.
17216
17217 @end table
17218
17219 @c @node Examples of gnatclean Usage
17220 @c @section Examples of @code{gnatclean} Usage
17221
17222 @ifclear vms
17223 @node GNAT and Libraries
17224 @chapter GNAT and Libraries
17225 @cindex Library, building, installing, using
17226
17227 @noindent
17228 This chapter describes how to build and use libraries with GNAT, and also shows
17229 how to recompile the GNAT run-time library. You should be familiar with the
17230 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
17231 chapter.
17232
17233 @menu
17234 * Introduction to Libraries in GNAT::
17235 * General Ada Libraries::
17236 * Stand-alone Ada Libraries::
17237 * Rebuilding the GNAT Run-Time Library::
17238 @end menu
17239
17240 @node Introduction to Libraries in GNAT
17241 @section Introduction to Libraries in GNAT
17242
17243 @noindent
17244 A library is, conceptually, a collection of objects which does not have its
17245 own main thread of execution, but rather provides certain services to the
17246 applications that use it. A library can be either statically linked with the
17247 application, in which case its code is directly included in the application,
17248 or, on platforms that support it, be dynamically linked, in which case
17249 its code is shared by all applications making use of this library.
17250
17251 GNAT supports both types of libraries.
17252 In the static case, the compiled code can be provided in different ways. The
17253 simplest approach is to provide directly the set of objects resulting from
17254 compilation of the library source files. Alternatively, you can group the
17255 objects into an archive using whatever commands are provided by the operating
17256 system. For the latter case, the objects are grouped into a shared library.
17257
17258 In the GNAT environment, a library has three types of components:
17259 @itemize @bullet
17260 @item
17261 Source files.
17262 @item
17263 @file{ALI} files.
17264 @xref{The Ada Library Information Files}.
17265 @item
17266 Object files, an archive or a shared library.
17267 @end itemize
17268
17269 @noindent
17270 A GNAT library may expose all its source files, which is useful for
17271 documentation purposes. Alternatively, it may expose only the units needed by
17272 an external user to make use of the library. That is to say, the specs
17273 reflecting the library services along with all the units needed to compile
17274 those specs, which can include generic bodies or any body implementing an
17275 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17276 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17277
17278 All compilation units comprising an application, including those in a library,
17279 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17280 computes the elaboration order from the @file{ALI} files and this is why they
17281 constitute a mandatory part of GNAT libraries.
17282 @emph{Stand-alone libraries} are the exception to this rule because a specific
17283 library elaboration routine is produced independently of the application(s)
17284 using the library.
17285
17286 @node General Ada Libraries
17287 @section General Ada Libraries
17288
17289 @menu
17290 * Building a library::
17291 * Installing a library::
17292 * Using a library::
17293 @end menu
17294
17295 @node Building a library
17296 @subsection Building a library
17297
17298 @noindent
17299 The easiest way to build a library is to use the Project Manager,
17300 which supports a special type of project called a @emph{Library Project}
17301 (@pxref{Library Projects}).
17302
17303 A project is considered a library project, when two project-level attributes
17304 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17305 control different aspects of library configuration, additional optional
17306 project-level attributes can be specified:
17307 @table @code
17308 @item Library_Kind
17309 This attribute controls whether the library is to be static or dynamic
17310
17311 @item Library_Version
17312 This attribute specifies the library version; this value is used
17313 during dynamic linking of shared libraries to determine if the currently
17314 installed versions of the binaries are compatible.
17315
17316 @item Library_Options
17317 @item Library_GCC
17318 These attributes specify additional low-level options to be used during
17319 library generation, and redefine the actual application used to generate
17320 library.
17321 @end table
17322
17323 @noindent
17324 The GNAT Project Manager takes full care of the library maintenance task,
17325 including recompilation of the source files for which objects do not exist
17326 or are not up to date, assembly of the library archive, and installation of
17327 the library (i.e., copying associated source, object and @file{ALI} files
17328 to the specified location).
17329
17330 Here is a simple library project file:
17331 @smallexample @c ada
17332 project My_Lib is
17333 for Source_Dirs use ("src1", "src2");
17334 for Object_Dir use "obj";
17335 for Library_Name use "mylib";
17336 for Library_Dir use "lib";
17337 for Library_Kind use "dynamic";
17338 end My_lib;
17339 @end smallexample
17340
17341 @noindent
17342 and the compilation command to build and install the library:
17343
17344 @smallexample @c ada
17345 $ gnatmake -Pmy_lib
17346 @end smallexample
17347
17348 @noindent
17349 It is not entirely trivial to perform manually all the steps required to
17350 produce a library. We recommend that you use the GNAT Project Manager
17351 for this task. In special cases where this is not desired, the necessary
17352 steps are discussed below.
17353
17354 There are various possibilities for compiling the units that make up the
17355 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17356 with a conventional script. For simple libraries, it is also possible to create
17357 a dummy main program which depends upon all the packages that comprise the
17358 interface of the library. This dummy main program can then be given to
17359 @command{gnatmake}, which will ensure that all necessary objects are built.
17360
17361 After this task is accomplished, you should follow the standard procedure
17362 of the underlying operating system to produce the static or shared library.
17363
17364 Here is an example of such a dummy program:
17365 @smallexample @c ada
17366 @group
17367 with My_Lib.Service1;
17368 with My_Lib.Service2;
17369 with My_Lib.Service3;
17370 procedure My_Lib_Dummy is
17371 begin
17372 null;
17373 end;
17374 @end group
17375 @end smallexample
17376
17377 @noindent
17378 Here are the generic commands that will build an archive or a shared library.
17379
17380 @smallexample
17381 # compiling the library
17382 $ gnatmake -c my_lib_dummy.adb
17383
17384 # we don't need the dummy object itself
17385 $ rm my_lib_dummy.o my_lib_dummy.ali
17386
17387 # create an archive with the remaining objects
17388 $ ar rc libmy_lib.a *.o
17389 # some systems may require "ranlib" to be run as well
17390
17391 # or create a shared library
17392 $ gcc -shared -o libmy_lib.so *.o
17393 # some systems may require the code to have been compiled with -fPIC
17394
17395 # remove the object files that are now in the library
17396 $ rm *.o
17397
17398 # Make the ALI files read-only so that gnatmake will not try to
17399 # regenerate the objects that are in the library
17400 $ chmod -w *.ali
17401 @end smallexample
17402
17403 @noindent
17404 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
17405 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
17406 be accessed by the directive @option{-l@var{xxx}} at link time.
17407
17408 @node Installing a library
17409 @subsection Installing a library
17410 @cindex @code{ADA_PROJECT_PATH}
17411 @cindex @code{GPR_PROJECT_PATH}
17412
17413 @noindent
17414 If you use project files, library installation is part of the library build
17415 process (@pxref{Installing a library with project files}).
17416
17417 When project files are not an option, it is also possible, but not recommended,
17418 to install the library so that the sources needed to use the library are on the
17419 Ada source path and the ALI files & libraries be on the Ada Object path (see
17420 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17421 administrator can place general-purpose libraries in the default compiler
17422 paths, by specifying the libraries' location in the configuration files
17423 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17424 must be located in the GNAT installation tree at the same place as the gcc spec
17425 file. The location of the gcc spec file can be determined as follows:
17426 @smallexample
17427 $ gcc -v
17428 @end smallexample
17429
17430 @noindent
17431 The configuration files mentioned above have a simple format: each line
17432 must contain one unique directory name.
17433 Those names are added to the corresponding path
17434 in their order of appearance in the file. The names can be either absolute
17435 or relative; in the latter case, they are relative to where theses files
17436 are located.
17437
17438 The files @file{ada_source_path} and @file{ada_object_path} might not be
17439 present in a
17440 GNAT installation, in which case, GNAT will look for its run-time library in
17441 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17442 objects and @file{ALI} files). When the files exist, the compiler does not
17443 look in @file{adainclude} and @file{adalib}, and thus the
17444 @file{ada_source_path} file
17445 must contain the location for the GNAT run-time sources (which can simply
17446 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17447 contain the location for the GNAT run-time objects (which can simply
17448 be @file{adalib}).
17449
17450 You can also specify a new default path to the run-time library at compilation
17451 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17452 the run-time library you want your program to be compiled with. This switch is
17453 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17454 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17455
17456 It is possible to install a library before or after the standard GNAT
17457 library, by reordering the lines in the configuration files. In general, a
17458 library must be installed before the GNAT library if it redefines
17459 any part of it.
17460
17461 @node Using a library
17462 @subsection Using a library
17463
17464 @noindent Once again, the project facility greatly simplifies the use of
17465 libraries. In this context, using a library is just a matter of adding a
17466 @code{with} clause in the user project. For instance, to make use of the
17467 library @code{My_Lib} shown in examples in earlier sections, you can
17468 write:
17469
17470 @smallexample @c projectfile
17471 with "my_lib";
17472 project My_Proj is
17473 @dots{}
17474 end My_Proj;
17475 @end smallexample
17476
17477 Even if you have a third-party, non-Ada library, you can still use GNAT's
17478 Project Manager facility to provide a wrapper for it. For example, the
17479 following project, when @code{with}ed by your main project, will link with the
17480 third-party library @file{liba.a}:
17481
17482 @smallexample @c projectfile
17483 @group
17484 project Liba is
17485 for Externally_Built use "true";
17486 for Source_Files use ();
17487 for Library_Dir use "lib";
17488 for Library_Name use "a";
17489 for Library_Kind use "static";
17490 end Liba;
17491 @end group
17492 @end smallexample
17493 This is an alternative to the use of @code{pragma Linker_Options}. It is
17494 especially interesting in the context of systems with several interdependent
17495 static libraries where finding a proper linker order is not easy and best be
17496 left to the tools having visibility over project dependence information.
17497
17498 @noindent
17499 In order to use an Ada library manually, you need to make sure that this
17500 library is on both your source and object path
17501 (see @ref{Search Paths and the Run-Time Library (RTL)}
17502 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17503 in an archive or a shared library, you need to specify the desired
17504 library at link time.
17505
17506 For example, you can use the library @file{mylib} installed in
17507 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17508
17509 @smallexample
17510 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17511 -largs -lmy_lib
17512 @end smallexample
17513
17514 @noindent
17515 This can be expressed more simply:
17516 @smallexample
17517 $ gnatmake my_appl
17518 @end smallexample
17519 @noindent
17520 when the following conditions are met:
17521 @itemize @bullet
17522 @item
17523 @file{/dir/my_lib_src} has been added by the user to the environment
17524 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
17525 @file{ada_source_path}
17526 @item
17527 @file{/dir/my_lib_obj} has been added by the user to the environment
17528 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
17529 @file{ada_object_path}
17530 @item
17531 a pragma @code{Linker_Options} has been added to one of the sources.
17532 For example:
17533
17534 @smallexample @c ada
17535 pragma Linker_Options ("-lmy_lib");
17536 @end smallexample
17537 @end itemize
17538
17539 @node Stand-alone Ada Libraries
17540 @section Stand-alone Ada Libraries
17541 @cindex Stand-alone library, building, using
17542
17543 @menu
17544 * Introduction to Stand-alone Libraries::
17545 * Building a Stand-alone Library::
17546 * Creating a Stand-alone Library to be used in a non-Ada context::
17547 * Restrictions in Stand-alone Libraries::
17548 @end menu
17549
17550 @node Introduction to Stand-alone Libraries
17551 @subsection Introduction to Stand-alone Libraries
17552
17553 @noindent
17554 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17555 necessary code to
17556 elaborate the Ada units that are included in the library. In contrast with
17557 an ordinary library, which consists of all sources, objects and @file{ALI}
17558 files of the
17559 library, a SAL may specify a restricted subset of compilation units
17560 to serve as a library interface. In this case, the fully
17561 self-sufficient set of files will normally consist of an objects
17562 archive, the sources of interface units' specs, and the @file{ALI}
17563 files of interface units.
17564 If an interface spec contains a generic unit or an inlined subprogram,
17565 the body's
17566 source must also be provided; if the units that must be provided in the source
17567 form depend on other units, the source and @file{ALI} files of those must
17568 also be provided.
17569
17570 The main purpose of a SAL is to minimize the recompilation overhead of client
17571 applications when a new version of the library is installed. Specifically,
17572 if the interface sources have not changed, client applications do not need to
17573 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17574 version, controlled by @code{Library_Version} attribute, is not changed,
17575 then the clients do not need to be relinked.
17576
17577 SALs also allow the library providers to minimize the amount of library source
17578 text exposed to the clients. Such ``information hiding'' might be useful or
17579 necessary for various reasons.
17580
17581 Stand-alone libraries are also well suited to be used in an executable whose
17582 main routine is not written in Ada.
17583
17584 @node Building a Stand-alone Library
17585 @subsection Building a Stand-alone Library
17586
17587 @noindent
17588 GNAT's Project facility provides a simple way of building and installing
17589 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17590 To be a Stand-alone Library Project, in addition to the two attributes
17591 that make a project a Library Project (@code{Library_Name} and
17592 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17593 @code{Library_Interface} must be defined. For example:
17594
17595 @smallexample @c projectfile
17596 @group
17597 for Library_Dir use "lib_dir";
17598 for Library_Name use "dummy";
17599 for Library_Interface use ("int1", "int1.child");
17600 @end group
17601 @end smallexample
17602
17603 @noindent
17604 Attribute @code{Library_Interface} has a non-empty string list value,
17605 each string in the list designating a unit contained in an immediate source
17606 of the project file.
17607
17608 When a Stand-alone Library is built, first the binder is invoked to build
17609 a package whose name depends on the library name
17610 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
17611 This binder-generated package includes initialization and
17612 finalization procedures whose
17613 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17614 in the example
17615 above). The object corresponding to this package is included in the library.
17616
17617 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17618 calling of these procedures if a static SAL is built, or if a shared SAL
17619 is built
17620 with the project-level attribute @code{Library_Auto_Init} set to
17621 @code{"false"}.
17622
17623 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17624 (those that are listed in attribute @code{Library_Interface}) are copied to
17625 the Library Directory. As a consequence, only the Interface Units may be
17626 imported from Ada units outside of the library. If other units are imported,
17627 the binding phase will fail.
17628
17629 @noindent
17630 It is also possible to build an encapsulated library where not only
17631 the code to elaborate and finalize the library is embedded but also
17632 ensuring that the library is linked only against static
17633 libraries. So an encapsulated library only depends on system
17634 libraries, all other code, including the GNAT runtime, is embedded. To
17635 build an encapsulated library the attribute
17636 @code{Library_Standalone} must be set to @code{encapsulated}:
17637
17638 @smallexample @c projectfile
17639 @group
17640 for Library_Dir use "lib_dir";
17641 for Library_Name use "dummy";
17642 for Library_Kind use "dynamic";
17643 for Library_Interface use ("int1", "int1.child");
17644 for Library_Standalone use "encapsulated";
17645 @end group
17646 @end smallexample
17647
17648 @noindent
17649 The default value for this attribute is @code{standard} in which case
17650 a stand-alone library is built.
17651
17652 The attribute @code{Library_Src_Dir} may be specified for a
17653 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
17654 single string value. Its value must be the path (absolute or relative to the
17655 project directory) of an existing directory. This directory cannot be the
17656 object directory or one of the source directories, but it can be the same as
17657 the library directory. The sources of the Interface
17658 Units of the library that are needed by an Ada client of the library will be
17659 copied to the designated directory, called the Interface Copy directory.
17660 These sources include the specs of the Interface Units, but they may also
17661 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
17662 are used, or when there is a generic unit in the spec. Before the sources
17663 are copied to the Interface Copy directory, an attempt is made to delete all
17664 files in the Interface Copy directory.
17665
17666 Building stand-alone libraries by hand is somewhat tedious, but for those
17667 occasions when it is necessary here are the steps that you need to perform:
17668 @itemize @bullet
17669 @item
17670 Compile all library sources.
17671
17672 @item
17673 Invoke the binder with the switch @option{-n} (No Ada main program),
17674 with all the @file{ALI} files of the interfaces, and
17675 with the switch @option{-L} to give specific names to the @code{init}
17676 and @code{final} procedures. For example:
17677 @smallexample
17678 gnatbind -n int1.ali int2.ali -Lsal1
17679 @end smallexample
17680
17681 @item
17682 Compile the binder generated file:
17683 @smallexample
17684 gcc -c b~int2.adb
17685 @end smallexample
17686
17687 @item
17688 Link the dynamic library with all the necessary object files,
17689 indicating to the linker the names of the @code{init} (and possibly
17690 @code{final}) procedures for automatic initialization (and finalization).
17691 The built library should be placed in a directory different from
17692 the object directory.
17693
17694 @item
17695 Copy the @code{ALI} files of the interface to the library directory,
17696 add in this copy an indication that it is an interface to a SAL
17697 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
17698 with letter ``P'') and make the modified copy of the @file{ALI} file
17699 read-only.
17700 @end itemize
17701
17702 @noindent
17703 Using SALs is not different from using other libraries
17704 (see @ref{Using a library}).
17705
17706 @node Creating a Stand-alone Library to be used in a non-Ada context
17707 @subsection Creating a Stand-alone Library to be used in a non-Ada context
17708
17709 @noindent
17710 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
17711 a non-Ada context.
17712
17713 The only extra step required is to ensure that library interface subprograms
17714 are compatible with the main program, by means of @code{pragma Export}
17715 or @code{pragma Convention}.
17716
17717 Here is an example of simple library interface for use with C main program:
17718
17719 @smallexample @c ada
17720 package My_Package is
17721
17722 procedure Do_Something;
17723 pragma Export (C, Do_Something, "do_something");
17724
17725 procedure Do_Something_Else;
17726 pragma Export (C, Do_Something_Else, "do_something_else");
17727
17728 end My_Package;
17729 @end smallexample
17730
17731 @noindent
17732 On the foreign language side, you must provide a ``foreign'' view of the
17733 library interface; remember that it should contain elaboration routines in
17734 addition to interface subprograms.
17735
17736 The example below shows the content of @code{mylib_interface.h} (note
17737 that there is no rule for the naming of this file, any name can be used)
17738 @smallexample
17739 /* the library elaboration procedure */
17740 extern void mylibinit (void);
17741
17742 /* the library finalization procedure */
17743 extern void mylibfinal (void);
17744
17745 /* the interface exported by the library */
17746 extern void do_something (void);
17747 extern void do_something_else (void);
17748 @end smallexample
17749
17750 @noindent
17751 Libraries built as explained above can be used from any program, provided
17752 that the elaboration procedures (named @code{mylibinit} in the previous
17753 example) are called before the library services are used. Any number of
17754 libraries can be used simultaneously, as long as the elaboration
17755 procedure of each library is called.
17756
17757 Below is an example of a C program that uses the @code{mylib} library.
17758
17759 @smallexample
17760 #include "mylib_interface.h"
17761
17762 int
17763 main (void)
17764 @{
17765 /* First, elaborate the library before using it */
17766 mylibinit ();
17767
17768 /* Main program, using the library exported entities */
17769 do_something ();
17770 do_something_else ();
17771
17772 /* Library finalization at the end of the program */
17773 mylibfinal ();
17774 return 0;
17775 @}
17776 @end smallexample
17777
17778 @noindent
17779 Note that invoking any library finalization procedure generated by
17780 @code{gnatbind} shuts down the Ada run-time environment.
17781 Consequently, the
17782 finalization of all Ada libraries must be performed at the end of the program.
17783 No call to these libraries or to the Ada run-time library should be made
17784 after the finalization phase.
17785
17786 @node Restrictions in Stand-alone Libraries
17787 @subsection Restrictions in Stand-alone Libraries
17788
17789 @noindent
17790 The pragmas listed below should be used with caution inside libraries,
17791 as they can create incompatibilities with other Ada libraries:
17792 @itemize @bullet
17793 @item pragma @code{Locking_Policy}
17794 @item pragma @code{Partition_Elaboration_Policy}
17795 @item pragma @code{Queuing_Policy}
17796 @item pragma @code{Task_Dispatching_Policy}
17797 @item pragma @code{Unreserve_All_Interrupts}
17798 @end itemize
17799
17800 @noindent
17801 When using a library that contains such pragmas, the user must make sure
17802 that all libraries use the same pragmas with the same values. Otherwise,
17803 @code{Program_Error} will
17804 be raised during the elaboration of the conflicting
17805 libraries. The usage of these pragmas and its consequences for the user
17806 should therefore be well documented.
17807
17808 Similarly, the traceback in the exception occurrence mechanism should be
17809 enabled or disabled in a consistent manner across all libraries.
17810 Otherwise, Program_Error will be raised during the elaboration of the
17811 conflicting libraries.
17812
17813 If the @code{Version} or @code{Body_Version}
17814 attributes are used inside a library, then you need to
17815 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
17816 libraries, so that version identifiers can be properly computed.
17817 In practice these attributes are rarely used, so this is unlikely
17818 to be a consideration.
17819
17820 @node Rebuilding the GNAT Run-Time Library
17821 @section Rebuilding the GNAT Run-Time Library
17822 @cindex GNAT Run-Time Library, rebuilding
17823 @cindex Building the GNAT Run-Time Library
17824 @cindex Rebuilding the GNAT Run-Time Library
17825 @cindex Run-Time Library, rebuilding
17826
17827 @noindent
17828 It may be useful to recompile the GNAT library in various contexts, the
17829 most important one being the use of partition-wide configuration pragmas
17830 such as @code{Normalize_Scalars}. A special Makefile called
17831 @code{Makefile.adalib} is provided to that effect and can be found in
17832 the directory containing the GNAT library. The location of this
17833 directory depends on the way the GNAT environment has been installed and can
17834 be determined by means of the command:
17835
17836 @smallexample
17837 $ gnatls -v
17838 @end smallexample
17839
17840 @noindent
17841 The last entry in the object search path usually contains the
17842 gnat library. This Makefile contains its own documentation and in
17843 particular the set of instructions needed to rebuild a new library and
17844 to use it.
17845
17846 @node Using the GNU make Utility
17847 @chapter Using the GNU @code{make} Utility
17848 @findex make
17849
17850 @noindent
17851 This chapter offers some examples of makefiles that solve specific
17852 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
17853 make, make, GNU @code{make}}), nor does it try to replace the
17854 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
17855
17856 All the examples in this section are specific to the GNU version of
17857 make. Although @command{make} is a standard utility, and the basic language
17858 is the same, these examples use some advanced features found only in
17859 @code{GNU make}.
17860
17861 @menu
17862 * Using gnatmake in a Makefile::
17863 * Automatically Creating a List of Directories::
17864 * Generating the Command Line Switches::
17865 * Overcoming Command Line Length Limits::
17866 @end menu
17867
17868 @node Using gnatmake in a Makefile
17869 @section Using gnatmake in a Makefile
17870 @findex makefile
17871 @cindex GNU make
17872
17873 @noindent
17874 Complex project organizations can be handled in a very powerful way by
17875 using GNU make combined with gnatmake. For instance, here is a Makefile
17876 which allows you to build each subsystem of a big project into a separate
17877 shared library. Such a makefile allows you to significantly reduce the link
17878 time of very big applications while maintaining full coherence at
17879 each step of the build process.
17880
17881 The list of dependencies are handled automatically by
17882 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
17883 the appropriate directories.
17884
17885 Note that you should also read the example on how to automatically
17886 create the list of directories
17887 (@pxref{Automatically Creating a List of Directories})
17888 which might help you in case your project has a lot of subdirectories.
17889
17890 @smallexample
17891 @iftex
17892 @leftskip=0cm
17893 @font@heightrm=cmr8
17894 @heightrm
17895 @end iftex
17896 ## This Makefile is intended to be used with the following directory
17897 ## configuration:
17898 ## - The sources are split into a series of csc (computer software components)
17899 ## Each of these csc is put in its own directory.
17900 ## Their name are referenced by the directory names.
17901 ## They will be compiled into shared library (although this would also work
17902 ## with static libraries
17903 ## - The main program (and possibly other packages that do not belong to any
17904 ## csc is put in the top level directory (where the Makefile is).
17905 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
17906 ## \_ second_csc (sources) __ lib (will contain the library)
17907 ## \_ @dots{}
17908 ## Although this Makefile is build for shared library, it is easy to modify
17909 ## to build partial link objects instead (modify the lines with -shared and
17910 ## gnatlink below)
17911 ##
17912 ## With this makefile, you can change any file in the system or add any new
17913 ## file, and everything will be recompiled correctly (only the relevant shared
17914 ## objects will be recompiled, and the main program will be re-linked).
17915
17916 # The list of computer software component for your project. This might be
17917 # generated automatically.
17918 CSC_LIST=aa bb cc
17919
17920 # Name of the main program (no extension)
17921 MAIN=main
17922
17923 # If we need to build objects with -fPIC, uncomment the following line
17924 #NEED_FPIC=-fPIC
17925
17926 # The following variable should give the directory containing libgnat.so
17927 # You can get this directory through 'gnatls -v'. This is usually the last
17928 # directory in the Object_Path.
17929 GLIB=@dots{}
17930
17931 # The directories for the libraries
17932 # (This macro expands the list of CSC to the list of shared libraries, you
17933 # could simply use the expanded form:
17934 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
17935 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
17936
17937 $@{MAIN@}: objects $@{LIB_DIR@}
17938 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
17939 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
17940
17941 objects::
17942 # recompile the sources
17943 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
17944
17945 # Note: In a future version of GNAT, the following commands will be simplified
17946 # by a new tool, gnatmlib
17947 $@{LIB_DIR@}:
17948 mkdir -p $@{dir $@@ @}
17949 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
17950 cd $@{dir $@@ @} && cp -f ../*.ali .
17951
17952 # The dependencies for the modules
17953 # Note that we have to force the expansion of *.o, since in some cases
17954 # make won't be able to do it itself.
17955 aa/lib/libaa.so: $@{wildcard aa/*.o@}
17956 bb/lib/libbb.so: $@{wildcard bb/*.o@}
17957 cc/lib/libcc.so: $@{wildcard cc/*.o@}
17958
17959 # Make sure all of the shared libraries are in the path before starting the
17960 # program
17961 run::
17962 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
17963
17964 clean::
17965 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
17966 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
17967 $@{RM@} $@{CSC_LIST:%=%/*.o@}
17968 $@{RM@} *.o *.ali $@{MAIN@}
17969 @end smallexample
17970
17971 @node Automatically Creating a List of Directories
17972 @section Automatically Creating a List of Directories
17973
17974 @noindent
17975 In most makefiles, you will have to specify a list of directories, and
17976 store it in a variable. For small projects, it is often easier to
17977 specify each of them by hand, since you then have full control over what
17978 is the proper order for these directories, which ones should be
17979 included.
17980
17981 However, in larger projects, which might involve hundreds of
17982 subdirectories, it might be more convenient to generate this list
17983 automatically.
17984
17985 The example below presents two methods. The first one, although less
17986 general, gives you more control over the list. It involves wildcard
17987 characters, that are automatically expanded by @command{make}. Its
17988 shortcoming is that you need to explicitly specify some of the
17989 organization of your project, such as for instance the directory tree
17990 depth, whether some directories are found in a separate tree, @enddots{}
17991
17992 The second method is the most general one. It requires an external
17993 program, called @command{find}, which is standard on all Unix systems. All
17994 the directories found under a given root directory will be added to the
17995 list.
17996
17997 @smallexample
17998 @iftex
17999 @leftskip=0cm
18000 @font@heightrm=cmr8
18001 @heightrm
18002 @end iftex
18003 # The examples below are based on the following directory hierarchy:
18004 # All the directories can contain any number of files
18005 # ROOT_DIRECTORY -> a -> aa -> aaa
18006 # -> ab
18007 # -> ac
18008 # -> b -> ba -> baa
18009 # -> bb
18010 # -> bc
18011 # This Makefile creates a variable called DIRS, that can be reused any time
18012 # you need this list (see the other examples in this section)
18013
18014 # The root of your project's directory hierarchy
18015 ROOT_DIRECTORY=.
18016
18017 ####
18018 # First method: specify explicitly the list of directories
18019 # This allows you to specify any subset of all the directories you need.
18020 ####
18021
18022 DIRS := a/aa/ a/ab/ b/ba/
18023
18024 ####
18025 # Second method: use wildcards
18026 # Note that the argument(s) to wildcard below should end with a '/'.
18027 # Since wildcards also return file names, we have to filter them out
18028 # to avoid duplicate directory names.
18029 # We thus use make's @code{dir} and @code{sort} functions.
18030 # It sets DIRs to the following value (note that the directories aaa and baa
18031 # are not given, unless you change the arguments to wildcard).
18032 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
18033 ####
18034
18035 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
18036 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
18037
18038 ####
18039 # Third method: use an external program
18040 # This command is much faster if run on local disks, avoiding NFS slowdowns.
18041 # This is the most complete command: it sets DIRs to the following value:
18042 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
18043 ####
18044
18045 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
18046
18047 @end smallexample
18048
18049 @node Generating the Command Line Switches
18050 @section Generating the Command Line Switches
18051
18052 @noindent
18053 Once you have created the list of directories as explained in the
18054 previous section (@pxref{Automatically Creating a List of Directories}),
18055 you can easily generate the command line arguments to pass to gnatmake.
18056
18057 For the sake of completeness, this example assumes that the source path
18058 is not the same as the object path, and that you have two separate lists
18059 of directories.
18060
18061 @smallexample
18062 # see "Automatically creating a list of directories" to create
18063 # these variables
18064 SOURCE_DIRS=
18065 OBJECT_DIRS=
18066
18067 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
18068 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
18069
18070 all:
18071 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
18072 @end smallexample
18073
18074 @node Overcoming Command Line Length Limits
18075 @section Overcoming Command Line Length Limits
18076
18077 @noindent
18078 One problem that might be encountered on big projects is that many
18079 operating systems limit the length of the command line. It is thus hard to give
18080 gnatmake the list of source and object directories.
18081
18082 This example shows how you can set up environment variables, which will
18083 make @command{gnatmake} behave exactly as if the directories had been
18084 specified on the command line, but have a much higher length limit (or
18085 even none on most systems).
18086
18087 It assumes that you have created a list of directories in your Makefile,
18088 using one of the methods presented in
18089 @ref{Automatically Creating a List of Directories}.
18090 For the sake of completeness, we assume that the object
18091 path (where the ALI files are found) is different from the sources patch.
18092
18093 Note a small trick in the Makefile below: for efficiency reasons, we
18094 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
18095 expanded immediately by @code{make}. This way we overcome the standard
18096 make behavior which is to expand the variables only when they are
18097 actually used.
18098
18099 On Windows, if you are using the standard Windows command shell, you must
18100 replace colons with semicolons in the assignments to these variables.
18101
18102 @smallexample
18103 @iftex
18104 @leftskip=0cm
18105 @font@heightrm=cmr8
18106 @heightrm
18107 @end iftex
18108 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
18109 # This is the same thing as putting the -I arguments on the command line.
18110 # (the equivalent of using -aI on the command line would be to define
18111 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
18112 # You can of course have different values for these variables.
18113 #
18114 # Note also that we need to keep the previous values of these variables, since
18115 # they might have been set before running 'make' to specify where the GNAT
18116 # library is installed.
18117
18118 # see "Automatically creating a list of directories" to create these
18119 # variables
18120 SOURCE_DIRS=
18121 OBJECT_DIRS=
18122
18123 empty:=
18124 space:=$@{empty@} $@{empty@}
18125 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
18126 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
18127 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
18128 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
18129 export ADA_INCLUDE_PATH
18130 export ADA_OBJECTS_PATH
18131
18132 all:
18133 gnatmake main_unit
18134 @end smallexample
18135 @end ifclear
18136
18137 @node Memory Management Issues
18138 @chapter Memory Management Issues
18139
18140 @noindent
18141 This chapter describes some useful memory pools provided in the GNAT library
18142 and in particular the GNAT Debug Pool facility, which can be used to detect
18143 incorrect uses of access values (including ``dangling references'').
18144 @ifclear vms
18145 It also describes the @command{gnatmem} tool, which can be used to track down
18146 ``memory leaks''.
18147 @end ifclear
18148
18149 @menu
18150 * Some Useful Memory Pools::
18151 * The GNAT Debug Pool Facility::
18152 @ifclear vms
18153 * The gnatmem Tool::
18154 @end ifclear
18155 @end menu
18156
18157 @node Some Useful Memory Pools
18158 @section Some Useful Memory Pools
18159 @findex Memory Pool
18160 @cindex storage, pool
18161
18162 @noindent
18163 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18164 storage pool. Allocations use the standard system call @code{malloc} while
18165 deallocations use the standard system call @code{free}. No reclamation is
18166 performed when the pool goes out of scope. For performance reasons, the
18167 standard default Ada allocators/deallocators do not use any explicit storage
18168 pools but if they did, they could use this storage pool without any change in
18169 behavior. That is why this storage pool is used when the user
18170 manages to make the default implicit allocator explicit as in this example:
18171 @smallexample @c ada
18172 type T1 is access Something;
18173 -- no Storage pool is defined for T2
18174 type T2 is access Something_Else;
18175 for T2'Storage_Pool use T1'Storage_Pool;
18176 -- the above is equivalent to
18177 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18178 @end smallexample
18179
18180 @noindent
18181 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18182 pool. The allocation strategy is similar to @code{Pool_Local}'s
18183 except that the all
18184 storage allocated with this pool is reclaimed when the pool object goes out of
18185 scope. This pool provides a explicit mechanism similar to the implicit one
18186 provided by several Ada 83 compilers for allocations performed through a local
18187 access type and whose purpose was to reclaim memory when exiting the
18188 scope of a given local access. As an example, the following program does not
18189 leak memory even though it does not perform explicit deallocation:
18190
18191 @smallexample @c ada
18192 with System.Pool_Local;
18193 procedure Pooloc1 is
18194 procedure Internal is
18195 type A is access Integer;
18196 X : System.Pool_Local.Unbounded_Reclaim_Pool;
18197 for A'Storage_Pool use X;
18198 v : A;
18199 begin
18200 for I in 1 .. 50 loop
18201 v := new Integer;
18202 end loop;
18203 end Internal;
18204 begin
18205 for I in 1 .. 100 loop
18206 Internal;
18207 end loop;
18208 end Pooloc1;
18209 @end smallexample
18210
18211 @noindent
18212 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
18213 @code{Storage_Size} is specified for an access type.
18214 The whole storage for the pool is
18215 allocated at once, usually on the stack at the point where the access type is
18216 elaborated. It is automatically reclaimed when exiting the scope where the
18217 access type is defined. This package is not intended to be used directly by the
18218 user and it is implicitly used for each such declaration:
18219
18220 @smallexample @c ada
18221 type T1 is access Something;
18222 for T1'Storage_Size use 10_000;
18223 @end smallexample
18224
18225 @node The GNAT Debug Pool Facility
18226 @section The GNAT Debug Pool Facility
18227 @findex Debug Pool
18228 @cindex storage, pool, memory corruption
18229
18230 @noindent
18231 The use of unchecked deallocation and unchecked conversion can easily
18232 lead to incorrect memory references. The problems generated by such
18233 references are usually difficult to tackle because the symptoms can be
18234 very remote from the origin of the problem. In such cases, it is
18235 very helpful to detect the problem as early as possible. This is the
18236 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
18237
18238 In order to use the GNAT specific debugging pool, the user must
18239 associate a debug pool object with each of the access types that may be
18240 related to suspected memory problems. See Ada Reference Manual 13.11.
18241 @smallexample @c ada
18242 type Ptr is access Some_Type;
18243 Pool : GNAT.Debug_Pools.Debug_Pool;
18244 for Ptr'Storage_Pool use Pool;
18245 @end smallexample
18246
18247 @noindent
18248 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18249 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18250 allow the user to redefine allocation and deallocation strategies. They
18251 also provide a checkpoint for each dereference, through the use of
18252 the primitive operation @code{Dereference} which is implicitly called at
18253 each dereference of an access value.
18254
18255 Once an access type has been associated with a debug pool, operations on
18256 values of the type may raise four distinct exceptions,
18257 which correspond to four potential kinds of memory corruption:
18258 @itemize @bullet
18259 @item
18260 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18261 @item
18262 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18263 @item
18264 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18265 @item
18266 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18267 @end itemize
18268
18269 @noindent
18270 For types associated with a Debug_Pool, dynamic allocation is performed using
18271 the standard GNAT allocation routine. References to all allocated chunks of
18272 memory are kept in an internal dictionary. Several deallocation strategies are
18273 provided, whereupon the user can choose to release the memory to the system,
18274 keep it allocated for further invalid access checks, or fill it with an easily
18275 recognizable pattern for debug sessions. The memory pattern is the old IBM
18276 hexadecimal convention: @code{16#DEADBEEF#}.
18277
18278 See the documentation in the file g-debpoo.ads for more information on the
18279 various strategies.
18280
18281 Upon each dereference, a check is made that the access value denotes a
18282 properly allocated memory location. Here is a complete example of use of
18283 @code{Debug_Pools}, that includes typical instances of memory corruption:
18284 @smallexample @c ada
18285 @iftex
18286 @leftskip=0cm
18287 @end iftex
18288 with Gnat.Io; use Gnat.Io;
18289 with Unchecked_Deallocation;
18290 with Unchecked_Conversion;
18291 with GNAT.Debug_Pools;
18292 with System.Storage_Elements;
18293 with Ada.Exceptions; use Ada.Exceptions;
18294 procedure Debug_Pool_Test is
18295
18296 type T is access Integer;
18297 type U is access all T;
18298
18299 P : GNAT.Debug_Pools.Debug_Pool;
18300 for T'Storage_Pool use P;
18301
18302 procedure Free is new Unchecked_Deallocation (Integer, T);
18303 function UC is new Unchecked_Conversion (U, T);
18304 A, B : aliased T;
18305
18306 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
18307
18308 begin
18309 Info (P);
18310 A := new Integer;
18311 B := new Integer;
18312 B := A;
18313 Info (P);
18314 Free (A);
18315 begin
18316 Put_Line (Integer'Image(B.all));
18317 exception
18318 when E : others => Put_Line ("raised: " & Exception_Name (E));
18319 end;
18320 begin
18321 Free (B);
18322 exception
18323 when E : others => Put_Line ("raised: " & Exception_Name (E));
18324 end;
18325 B := UC(A'Access);
18326 begin
18327 Put_Line (Integer'Image(B.all));
18328 exception
18329 when E : others => Put_Line ("raised: " & Exception_Name (E));
18330 end;
18331 begin
18332 Free (B);
18333 exception
18334 when E : others => Put_Line ("raised: " & Exception_Name (E));
18335 end;
18336 Info (P);
18337 end Debug_Pool_Test;
18338 @end smallexample
18339
18340 @noindent
18341 The debug pool mechanism provides the following precise diagnostics on the
18342 execution of this erroneous program:
18343 @smallexample
18344 Debug Pool info:
18345 Total allocated bytes : 0
18346 Total deallocated bytes : 0
18347 Current Water Mark: 0
18348 High Water Mark: 0
18349
18350 Debug Pool info:
18351 Total allocated bytes : 8
18352 Total deallocated bytes : 0
18353 Current Water Mark: 8
18354 High Water Mark: 8
18355
18356 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18357 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18358 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18359 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18360 Debug Pool info:
18361 Total allocated bytes : 8
18362 Total deallocated bytes : 4
18363 Current Water Mark: 4
18364 High Water Mark: 8
18365 @end smallexample
18366
18367 @ifclear vms
18368 @node The gnatmem Tool
18369 @section The @command{gnatmem} Tool
18370 @findex gnatmem
18371
18372 @noindent
18373 The @code{gnatmem} utility monitors dynamic allocation and
18374 deallocation activity in a program, and displays information about
18375 incorrect deallocations and possible sources of memory leaks.
18376 It is designed to work in association with a static runtime library
18377 only and in this context provides three types of information:
18378 @itemize @bullet
18379 @item
18380 General information concerning memory management, such as the total
18381 number of allocations and deallocations, the amount of allocated
18382 memory and the high water mark, i.e.@: the largest amount of allocated
18383 memory in the course of program execution.
18384
18385 @item
18386 Backtraces for all incorrect deallocations, that is to say deallocations
18387 which do not correspond to a valid allocation.
18388
18389 @item
18390 Information on each allocation that is potentially the origin of a memory
18391 leak.
18392 @end itemize
18393
18394 @menu
18395 * Running gnatmem::
18396 * Switches for gnatmem::
18397 * Example of gnatmem Usage::
18398 @end menu
18399
18400 @node Running gnatmem
18401 @subsection Running @code{gnatmem}
18402
18403 @noindent
18404 @code{gnatmem} makes use of the output created by the special version of
18405 allocation and deallocation routines that record call information. This
18406 allows to obtain accurate dynamic memory usage history at a minimal cost to
18407 the execution speed. Note however, that @code{gnatmem} is not supported on
18408 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
18409 Solaris and Windows NT/2000/XP (x86).
18410
18411 @noindent
18412 The @code{gnatmem} command has the form
18413
18414 @smallexample
18415 @c $ gnatmem @ovar{switches} user_program
18416 @c Expanding @ovar macro inline (explanation in macro def comments)
18417 $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
18418 @end smallexample
18419
18420 @noindent
18421 The program must have been linked with the instrumented version of the
18422 allocation and deallocation routines. This is done by linking with the
18423 @file{libgmem.a} library. For correct symbolic backtrace information,
18424 the user program should be compiled with debugging options
18425 (see @ref{Switches for gcc}). For example to build @file{my_program}:
18426
18427 @smallexample
18428 $ gnatmake -g my_program -largs -lgmem
18429 @end smallexample
18430
18431 @noindent
18432 As library @file{libgmem.a} contains an alternate body for package
18433 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
18434 when an executable is linked with library @file{libgmem.a}. It is then not
18435 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
18436
18437 @noindent
18438 When @file{my_program} is executed, the file @file{gmem.out} is produced.
18439 This file contains information about all allocations and deallocations
18440 performed by the program. It is produced by the instrumented allocations and
18441 deallocations routines and will be used by @code{gnatmem}.
18442
18443 In order to produce symbolic backtrace information for allocations and
18444 deallocations performed by the GNAT run-time library, you need to use a
18445 version of that library that has been compiled with the @option{-g} switch
18446 (see @ref{Rebuilding the GNAT Run-Time Library}).
18447
18448 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18449 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18450 @option{-i} switch, gnatmem will assume that this file can be found in the
18451 current directory. For example, after you have executed @file{my_program},
18452 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18453
18454 @smallexample
18455 $ gnatmem my_program
18456 @end smallexample
18457
18458 @noindent
18459 This will produce the output with the following format:
18460
18461 *************** debut cc
18462 @smallexample
18463 $ gnatmem my_program
18464
18465 Global information
18466 ------------------
18467 Total number of allocations : 45
18468 Total number of deallocations : 6
18469 Final Water Mark (non freed mem) : 11.29 Kilobytes
18470 High Water Mark : 11.40 Kilobytes
18471
18472 .
18473 .
18474 .
18475 Allocation Root # 2
18476 -------------------
18477 Number of non freed allocations : 11
18478 Final Water Mark (non freed mem) : 1.16 Kilobytes
18479 High Water Mark : 1.27 Kilobytes
18480 Backtrace :
18481 my_program.adb:23 my_program.alloc
18482 .
18483 .
18484 .
18485 @end smallexample
18486
18487 The first block of output gives general information. In this case, the
18488 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18489 Unchecked_Deallocation routine occurred.
18490
18491 @noindent
18492 Subsequent paragraphs display information on all allocation roots.
18493 An allocation root is a specific point in the execution of the program
18494 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18495 construct. This root is represented by an execution backtrace (or subprogram
18496 call stack). By default the backtrace depth for allocations roots is 1, so
18497 that a root corresponds exactly to a source location. The backtrace can
18498 be made deeper, to make the root more specific.
18499
18500 @node Switches for gnatmem
18501 @subsection Switches for @code{gnatmem}
18502
18503 @noindent
18504 @code{gnatmem} recognizes the following switches:
18505
18506 @table @option
18507
18508 @item -q
18509 @cindex @option{-q} (@code{gnatmem})
18510 Quiet. Gives the minimum output needed to identify the origin of the
18511 memory leaks. Omits statistical information.
18512
18513 @item @var{N}
18514 @cindex @var{N} (@code{gnatmem})
18515 N is an integer literal (usually between 1 and 10) which controls the
18516 depth of the backtraces defining allocation root. The default value for
18517 N is 1. The deeper the backtrace, the more precise the localization of
18518 the root. Note that the total number of roots can depend on this
18519 parameter. This parameter must be specified @emph{before} the name of the
18520 executable to be analyzed, to avoid ambiguity.
18521
18522 @item -b n
18523 @cindex @option{-b} (@code{gnatmem})
18524 This switch has the same effect as just depth parameter.
18525
18526 @item -i @var{file}
18527 @cindex @option{-i} (@code{gnatmem})
18528 Do the @code{gnatmem} processing starting from @file{file}, rather than
18529 @file{gmem.out} in the current directory.
18530
18531 @item -m n
18532 @cindex @option{-m} (@code{gnatmem})
18533 This switch causes @code{gnatmem} to mask the allocation roots that have less
18534 than n leaks. The default value is 1. Specifying the value of 0 will allow to
18535 examine even the roots that didn't result in leaks.
18536
18537 @item -s order
18538 @cindex @option{-s} (@code{gnatmem})
18539 This switch causes @code{gnatmem} to sort the allocation roots according to the
18540 specified order of sort criteria, each identified by a single letter. The
18541 currently supported criteria are @code{n, h, w} standing respectively for
18542 number of unfreed allocations, high watermark, and final watermark
18543 corresponding to a specific root. The default order is @code{nwh}.
18544
18545 @end table
18546
18547 @node Example of gnatmem Usage
18548 @subsection Example of @code{gnatmem} Usage
18549
18550 @noindent
18551 The following example shows the use of @code{gnatmem}
18552 on a simple memory-leaking program.
18553 Suppose that we have the following Ada program:
18554
18555 @smallexample @c ada
18556 @group
18557 @cartouche
18558 with Unchecked_Deallocation;
18559 procedure Test_Gm is
18560
18561 type T is array (1..1000) of Integer;
18562 type Ptr is access T;
18563 procedure Free is new Unchecked_Deallocation (T, Ptr);
18564 A : Ptr;
18565
18566 procedure My_Alloc is
18567 begin
18568 A := new T;
18569 end My_Alloc;
18570
18571 procedure My_DeAlloc is
18572 B : Ptr := A;
18573 begin
18574 Free (B);
18575 end My_DeAlloc;
18576
18577 begin
18578 My_Alloc;
18579 for I in 1 .. 5 loop
18580 for J in I .. 5 loop
18581 My_Alloc;
18582 end loop;
18583 My_Dealloc;
18584 end loop;
18585 end;
18586 @end cartouche
18587 @end group
18588 @end smallexample
18589
18590 @noindent
18591 The program needs to be compiled with debugging option and linked with
18592 @code{gmem} library:
18593
18594 @smallexample
18595 $ gnatmake -g test_gm -largs -lgmem
18596 @end smallexample
18597
18598 @noindent
18599 Then we execute the program as usual:
18600
18601 @smallexample
18602 $ test_gm
18603 @end smallexample
18604
18605 @noindent
18606 Then @code{gnatmem} is invoked simply with
18607 @smallexample
18608 $ gnatmem test_gm
18609 @end smallexample
18610
18611 @noindent
18612 which produces the following output (result may vary on different platforms):
18613
18614 @smallexample
18615 Global information
18616 ------------------
18617 Total number of allocations : 18
18618 Total number of deallocations : 5
18619 Final Water Mark (non freed mem) : 53.00 Kilobytes
18620 High Water Mark : 56.90 Kilobytes
18621
18622 Allocation Root # 1
18623 -------------------
18624 Number of non freed allocations : 11
18625 Final Water Mark (non freed mem) : 42.97 Kilobytes
18626 High Water Mark : 46.88 Kilobytes
18627 Backtrace :
18628 test_gm.adb:11 test_gm.my_alloc
18629
18630 Allocation Root # 2
18631 -------------------
18632 Number of non freed allocations : 1
18633 Final Water Mark (non freed mem) : 10.02 Kilobytes
18634 High Water Mark : 10.02 Kilobytes
18635 Backtrace :
18636 s-secsta.adb:81 system.secondary_stack.ss_init
18637
18638 Allocation Root # 3
18639 -------------------
18640 Number of non freed allocations : 1
18641 Final Water Mark (non freed mem) : 12 Bytes
18642 High Water Mark : 12 Bytes
18643 Backtrace :
18644 s-secsta.adb:181 system.secondary_stack.ss_init
18645 @end smallexample
18646
18647 @noindent
18648 Note that the GNAT run time contains itself a certain number of
18649 allocations that have no corresponding deallocation,
18650 as shown here for root #2 and root
18651 #3. This is a normal behavior when the number of non-freed allocations
18652 is one, it allocates dynamic data structures that the run time needs for
18653 the complete lifetime of the program. Note also that there is only one
18654 allocation root in the user program with a single line back trace:
18655 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
18656 program shows that 'My_Alloc' is called at 2 different points in the
18657 source (line 21 and line 24). If those two allocation roots need to be
18658 distinguished, the backtrace depth parameter can be used:
18659
18660 @smallexample
18661 $ gnatmem 3 test_gm
18662 @end smallexample
18663
18664 @noindent
18665 which will give the following output:
18666
18667 @smallexample
18668 Global information
18669 ------------------
18670 Total number of allocations : 18
18671 Total number of deallocations : 5
18672 Final Water Mark (non freed mem) : 53.00 Kilobytes
18673 High Water Mark : 56.90 Kilobytes
18674
18675 Allocation Root # 1
18676 -------------------
18677 Number of non freed allocations : 10
18678 Final Water Mark (non freed mem) : 39.06 Kilobytes
18679 High Water Mark : 42.97 Kilobytes
18680 Backtrace :
18681 test_gm.adb:11 test_gm.my_alloc
18682 test_gm.adb:24 test_gm
18683 b_test_gm.c:52 main
18684
18685 Allocation Root # 2
18686 -------------------
18687 Number of non freed allocations : 1
18688 Final Water Mark (non freed mem) : 10.02 Kilobytes
18689 High Water Mark : 10.02 Kilobytes
18690 Backtrace :
18691 s-secsta.adb:81 system.secondary_stack.ss_init
18692 s-secsta.adb:283 <system__secondary_stack___elabb>
18693 b_test_gm.c:33 adainit
18694
18695 Allocation Root # 3
18696 -------------------
18697 Number of non freed allocations : 1
18698 Final Water Mark (non freed mem) : 3.91 Kilobytes
18699 High Water Mark : 3.91 Kilobytes
18700 Backtrace :
18701 test_gm.adb:11 test_gm.my_alloc
18702 test_gm.adb:21 test_gm
18703 b_test_gm.c:52 main
18704
18705 Allocation Root # 4
18706 -------------------
18707 Number of non freed allocations : 1
18708 Final Water Mark (non freed mem) : 12 Bytes
18709 High Water Mark : 12 Bytes
18710 Backtrace :
18711 s-secsta.adb:181 system.secondary_stack.ss_init
18712 s-secsta.adb:283 <system__secondary_stack___elabb>
18713 b_test_gm.c:33 adainit
18714 @end smallexample
18715
18716 @noindent
18717 The allocation root #1 of the first example has been split in 2 roots #1
18718 and #3 thanks to the more precise associated backtrace.
18719
18720 @end ifclear
18721
18722 @node Stack Related Facilities
18723 @chapter Stack Related Facilities
18724
18725 @noindent
18726 This chapter describes some useful tools associated with stack
18727 checking and analysis. In
18728 particular, it deals with dynamic and static stack usage measurements.
18729
18730 @menu
18731 * Stack Overflow Checking::
18732 * Static Stack Usage Analysis::
18733 * Dynamic Stack Usage Analysis::
18734 @end menu
18735
18736 @node Stack Overflow Checking
18737 @section Stack Overflow Checking
18738 @cindex Stack Overflow Checking
18739 @cindex -fstack-check
18740
18741 @noindent
18742 For most operating systems, @command{gcc} does not perform stack overflow
18743 checking by default. This means that if the main environment task or
18744 some other task exceeds the available stack space, then unpredictable
18745 behavior will occur. Most native systems offer some level of protection by
18746 adding a guard page at the end of each task stack. This mechanism is usually
18747 not enough for dealing properly with stack overflow situations because
18748 a large local variable could ``jump'' above the guard page.
18749 Furthermore, when the
18750 guard page is hit, there may not be any space left on the stack for executing
18751 the exception propagation code. Enabling stack checking avoids
18752 such situations.
18753
18754 To activate stack checking, compile all units with the gcc option
18755 @option{-fstack-check}. For example:
18756
18757 @smallexample
18758 gcc -c -fstack-check package1.adb
18759 @end smallexample
18760
18761 @noindent
18762 Units compiled with this option will generate extra instructions to check
18763 that any use of the stack (for procedure calls or for declaring local
18764 variables in declare blocks) does not exceed the available stack space.
18765 If the space is exceeded, then a @code{Storage_Error} exception is raised.
18766
18767 For declared tasks, the stack size is controlled by the size
18768 given in an applicable @code{Storage_Size} pragma or by the value specified
18769 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
18770 the default size as defined in the GNAT runtime otherwise.
18771
18772 For the environment task, the stack size depends on
18773 system defaults and is unknown to the compiler. Stack checking
18774 may still work correctly if a fixed
18775 size stack is allocated, but this cannot be guaranteed.
18776 @ifclear vms
18777 To ensure that a clean exception is signalled for stack
18778 overflow, set the environment variable
18779 @env{GNAT_STACK_LIMIT} to indicate the maximum
18780 stack area that can be used, as in:
18781 @cindex GNAT_STACK_LIMIT
18782
18783 @smallexample
18784 SET GNAT_STACK_LIMIT 1600
18785 @end smallexample
18786
18787 @noindent
18788 The limit is given in kilobytes, so the above declaration would
18789 set the stack limit of the environment task to 1.6 megabytes.
18790 Note that the only purpose of this usage is to limit the amount
18791 of stack used by the environment task. If it is necessary to
18792 increase the amount of stack for the environment task, then this
18793 is an operating systems issue, and must be addressed with the
18794 appropriate operating systems commands.
18795 @end ifclear
18796 @ifset vms
18797 To have a fixed size stack in the environment task, the stack must be put
18798 in the P0 address space and its size specified. Use these switches to
18799 create a p0 image:
18800
18801 @smallexample
18802 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
18803 @end smallexample
18804
18805 @noindent
18806 The quotes are required to keep case. The number after @samp{STACK=} is the
18807 size of the environmental task stack in pagelets (512 bytes). In this example
18808 the stack size is about 2 megabytes.
18809
18810 @noindent
18811 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
18812 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
18813 more details about the @option{/p0image} qualifier and the @option{stack}
18814 option.
18815
18816 @noindent
18817 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
18818 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
18819 stack in kilobytes. For example:
18820
18821 @smallexample
18822 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
18823 @end smallexample
18824 @end ifset
18825
18826 @node Static Stack Usage Analysis
18827 @section Static Stack Usage Analysis
18828 @cindex Static Stack Usage Analysis
18829 @cindex -fstack-usage
18830
18831 @noindent
18832 A unit compiled with @option{-fstack-usage} will generate an extra file
18833 that specifies
18834 the maximum amount of stack used, on a per-function basis.
18835 The file has the same
18836 basename as the target object file with a @file{.su} extension.
18837 Each line of this file is made up of three fields:
18838
18839 @itemize
18840 @item
18841 The name of the function.
18842 @item
18843 A number of bytes.
18844 @item
18845 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
18846 @end itemize
18847
18848 The second field corresponds to the size of the known part of the function
18849 frame.
18850
18851 The qualifier @code{static} means that the function frame size
18852 is purely static.
18853 It usually means that all local variables have a static size.
18854 In this case, the second field is a reliable measure of the function stack
18855 utilization.
18856
18857 The qualifier @code{dynamic} means that the function frame size is not static.
18858 It happens mainly when some local variables have a dynamic size. When this
18859 qualifier appears alone, the second field is not a reliable measure
18860 of the function stack analysis. When it is qualified with @code{bounded}, it
18861 means that the second field is a reliable maximum of the function stack
18862 utilization.
18863
18864 A unit compiled with @option{-Wstack-usage} will issue a warning for each
18865 subprogram whose stack usage might be larger than the specified amount of
18866 bytes. The wording is in keeping with the qualifier documented above.
18867
18868 @node Dynamic Stack Usage Analysis
18869 @section Dynamic Stack Usage Analysis
18870
18871 @noindent
18872 It is possible to measure the maximum amount of stack used by a task, by
18873 adding a switch to @command{gnatbind}, as:
18874
18875 @smallexample
18876 $ gnatbind -u0 file
18877 @end smallexample
18878
18879 @noindent
18880 With this option, at each task termination, its stack usage is output on
18881 @file{stderr}.
18882 It is not always convenient to output the stack usage when the program
18883 is still running. Hence, it is possible to delay this output until program
18884 termination. for a given number of tasks specified as the argument of the
18885 @option{-u} option. For instance:
18886
18887 @smallexample
18888 $ gnatbind -u100 file
18889 @end smallexample
18890
18891 @noindent
18892 will buffer the stack usage information of the first 100 tasks to terminate and
18893 output this info at program termination. Results are displayed in four
18894 columns:
18895
18896 @noindent
18897 Index | Task Name | Stack Size | Stack Usage
18898
18899 @noindent
18900 where:
18901
18902 @table @emph
18903 @item Index
18904 is a number associated with each task.
18905
18906 @item Task Name
18907 is the name of the task analyzed.
18908
18909 @item Stack Size
18910 is the maximum size for the stack.
18911
18912 @item Stack Usage
18913 is the measure done by the stack analyzer. In order to prevent overflow, the stack
18914 is not entirely analyzed, and it's not possible to know exactly how
18915 much has actually been used.
18916
18917 @end table
18918
18919 @noindent
18920 The environment task stack, e.g., the stack that contains the main unit, is
18921 only processed when the environment variable GNAT_STACK_LIMIT is set.
18922
18923 @noindent
18924 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
18925 stack usage reports at run-time. See its body for the details.
18926
18927 @c *********************************
18928 @c * GNATCHECK *
18929 @c *********************************
18930 @node Verifying Properties with gnatcheck
18931 @chapter Verifying Properties with @command{gnatcheck}
18932 @findex gnatcheck
18933 @cindex @command{gnatcheck}
18934
18935 @noindent
18936 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
18937 of Ada source files according to a given set of semantic rules.
18938 @cindex ASIS
18939
18940 In order to check compliance with a given rule, @command{gnatcheck} has to
18941 semantically analyze the Ada sources.
18942 Therefore, checks can only be performed on
18943 legal Ada units. Moreover, when a unit depends semantically upon units located
18944 outside the current directory, the source search path has to be provided when
18945 calling @command{gnatcheck}, either through a specified project file or
18946 through @command{gnatcheck} switches.
18947
18948 For full details, refer to @cite{GNATcheck Reference Manual} document.
18949
18950
18951 @c *********************************
18952 @node Creating Sample Bodies with gnatstub
18953 @chapter Creating Sample Bodies with @command{gnatstub}
18954 @findex gnatstub
18955
18956 @noindent
18957 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
18958 for library unit declarations.
18959
18960 Note: to invoke @code{gnatstub} with a project file, use the @code{gnat}
18961 driver (see @ref{The GNAT Driver and Project Files}).
18962
18963 To create a body stub, @command{gnatstub} has to compile the library
18964 unit declaration. Therefore, bodies can be created only for legal
18965 library units. Moreover, if a library unit depends semantically upon
18966 units located outside the current directory, you have to provide
18967 the source search path when calling @command{gnatstub}, see the description
18968 of @command{gnatstub} switches below.
18969
18970 By default, all the program unit body stubs generated by @code{gnatstub}
18971 raise the predefined @code{Program_Error} exception, which will catch
18972 accidental calls of generated stubs. This behavior can be changed with
18973 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
18974
18975 @menu
18976 * Running gnatstub::
18977 * Switches for gnatstub::
18978 @end menu
18979
18980 @node Running gnatstub
18981 @section Running @command{gnatstub}
18982
18983 @noindent
18984 @command{gnatstub} has a command-line interface of the form:
18985
18986 @smallexample
18987 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
18988 @c Expanding @ovar macro inline (explanation in macro def comments)
18989 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
18990 @end smallexample
18991
18992 @noindent
18993 where
18994 @table @var
18995 @item filename
18996 is the name of the source file that contains a library unit declaration
18997 for which a body must be created. The file name may contain the path
18998 information.
18999 The file name does not have to follow the GNAT file name conventions. If the
19000 name
19001 does not follow GNAT file naming conventions, the name of the body file must
19002 be provided
19003 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
19004 If the file name follows the GNAT file naming
19005 conventions and the name of the body file is not provided,
19006 @command{gnatstub}
19007 creates the name
19008 of the body file from the argument file name by replacing the @file{.ads}
19009 suffix
19010 with the @file{.adb} suffix.
19011
19012 @item directory
19013 indicates the directory in which the body stub is to be placed (the default
19014 is the
19015 current directory)
19016
19017 @item @samp{@var{gcc_switches}} is a list of switches for
19018 @command{gcc}. They will be passed on to all compiler invocations made by
19019 @command{gnatstub} to generate the ASIS trees. Here you can provide
19020 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19021 use the @option{-gnatec} switch to set the configuration file,
19022 use the @option{-gnat05} switch if sources should be compiled in
19023 Ada 2005 mode etc.
19024
19025 @item switches
19026 is an optional sequence of switches as described in the next section
19027 @end table
19028
19029 @node Switches for gnatstub
19030 @section Switches for @command{gnatstub}
19031
19032 @table @option
19033 @c !sort!
19034
19035 @item --version
19036 @cindex @option{--version} @command{gnatstub}
19037 Display Copyright and version, then exit disregarding all other options.
19038
19039 @item --help
19040 @cindex @option{--help} @command{gnatstub}
19041 Display usage, then exit disregarding all other options.
19042
19043 @item ^-f^/FULL^
19044 @cindex @option{^-f^/FULL^} (@command{gnatstub})
19045 If the destination directory already contains a file with the name of the
19046 body file
19047 for the argument spec file, replace it with the generated body stub.
19048
19049 @item ^-hs^/HEADER=SPEC^
19050 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
19051 Put the comment header (i.e., all the comments preceding the
19052 compilation unit) from the source of the library unit declaration
19053 into the body stub.
19054
19055 @item ^-hg^/HEADER=GENERAL^
19056 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
19057 Put a sample comment header into the body stub.
19058
19059 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
19060 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
19061 Use the content of the file as the comment header for a generated body stub.
19062
19063 @ifclear vms
19064 @item -IDIR
19065 @cindex @option{-IDIR} (@command{gnatstub})
19066 @itemx -I-
19067 @cindex @option{-I-} (@command{gnatstub})
19068 @end ifclear
19069 @ifset vms
19070 @item /NOCURRENT_DIRECTORY
19071 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
19072 @end ifset
19073 ^These switches have ^This switch has^ the same meaning as in calls to
19074 @command{gcc}.
19075 ^They define ^It defines ^ the source search path in the call to
19076 @command{gcc} issued
19077 by @command{gnatstub} to compile an argument source file.
19078
19079 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
19080 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
19081 This switch has the same meaning as in calls to @command{gcc}.
19082 It defines the additional configuration file to be passed to the call to
19083 @command{gcc} issued
19084 by @command{gnatstub} to compile an argument source file.
19085
19086 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
19087 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
19088 (@var{n} is a non-negative integer). Set the maximum line length that is
19089 allowed in a source file. The default is 79. The maximum value that can be
19090 specified is 32767. Note that in the special case of configuration
19091 pragma files, the maximum is always 32767 regardless of whether or
19092 not this switch appears.
19093
19094 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
19095 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
19096 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
19097 the generated body sample to @var{n}.
19098 The default indentation is 3.
19099
19100 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
19101 @cindex @option{^-gnatyo^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
19102 Order local bodies alphabetically. (By default local bodies are ordered
19103 in the same way as the corresponding local specs in the argument spec file.)
19104
19105 @item ^-i^/INDENTATION=^@var{n}
19106 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
19107 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
19108
19109 @item ^-k^/TREE_FILE=SAVE^
19110 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
19111 Do not remove the tree file (i.e., the snapshot of the compiler internal
19112 structures used by @command{gnatstub}) after creating the body stub.
19113
19114 @item ^-l^/LINE_LENGTH=^@var{n}
19115 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
19116 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
19117
19118 @item ^--no-exception^/NO_EXCEPTION^
19119 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
19120 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
19121 This is not always possible for function stubs.
19122
19123 @item ^--no-local-header^/NO_LOCAL_HEADER^
19124 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
19125 Do not place local comment header with unit name before body stub for a
19126 unit.
19127
19128 @item ^-o ^/BODY=^@var{body-name}
19129 @cindex @option{^-o^/BODY^} (@command{gnatstub})
19130 Body file name. This should be set if the argument file name does not
19131 follow
19132 the GNAT file naming
19133 conventions. If this switch is omitted the default name for the body will be
19134 obtained
19135 from the argument file name according to the GNAT file naming conventions.
19136
19137 @item ^-q^/QUIET^
19138 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
19139 Quiet mode: do not generate a confirmation when a body is
19140 successfully created, and do not generate a message when a body is not
19141 required for an
19142 argument unit.
19143
19144 @item ^-r^/TREE_FILE=REUSE^
19145 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
19146 Reuse the tree file (if it exists) instead of creating it. Instead of
19147 creating the tree file for the library unit declaration, @command{gnatstub}
19148 tries to find it in the current directory and use it for creating
19149 a body. If the tree file is not found, no body is created. This option
19150 also implies @option{^-k^/SAVE^}, whether or not
19151 the latter is set explicitly.
19152
19153 @item ^-t^/TREE_FILE=OVERWRITE^
19154 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
19155 Overwrite the existing tree file. If the current directory already
19156 contains the file which, according to the GNAT file naming rules should
19157 be considered as a tree file for the argument source file,
19158 @command{gnatstub}
19159 will refuse to create the tree file needed to create a sample body
19160 unless this option is set.
19161
19162 @item ^-v^/VERBOSE^
19163 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
19164 Verbose mode: generate version information.
19165
19166 @end table
19167
19168 @c *********************************
19169 @node Creating Unit Tests with gnattest
19170 @chapter Creating Unit Tests with @command{gnattest}
19171 @findex gnattest
19172
19173 @noindent
19174 @command{gnattest} is an ASIS-based utility that creates unit-test skeletons
19175 as well as a test driver infrastructure (harness). @command{gnattest} creates
19176 a skeleton for each visible subprogram in the packages under consideration when
19177 they do not exist already.
19178
19179 In order to process source files from a project, @command{gnattest} has to
19180 semantically analyze the sources. Therefore, test skeletons can only be
19181 generated for legal Ada units. If a unit is dependent on other units,
19182 those units should be among the source files of the project or of other projects
19183 imported by this one.
19184
19185 Generated skeletons and harnesses are based on the AUnit testing framework.
19186 AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit
19187 for Java or CppUnit for C++. While it is advised that gnattest users read
19188 the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest.
19189 For correct operation of @command{gnattest}, AUnit should be installed and
19190 aunit.gpr must be on the project path. This happens automatically when Aunit
19191 is installed at its default location.
19192 @menu
19193 * Running gnattest::
19194 * Switches for gnattest::
19195 * Project Attributes for gnattest::
19196 * Simple Example::
19197 * Setting Up and Tearing Down the Testing Environment::
19198 * Regenerating Tests::
19199 * Default Test Behavior::
19200 * Testing Primitive Operations of Tagged Types::
19201 * Testing Inheritance::
19202 * Tagged Types Substitutability Testing::
19203 * Testing with Contracts::
19204 * Additional Tests::
19205 @ifclear vms
19206 * Support for other platforms/run-times::
19207 @end ifclear
19208 * Current Limitations::
19209 @end menu
19210
19211 @node Running gnattest
19212 @section Running @command{gnattest}
19213
19214 @noindent
19215 @command{gnattest} has a command-line interface of the form
19216
19217 @smallexample
19218 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
19219 @c Expanding @ovar macro inline (explanation in macro def comments)
19220 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19221 @end smallexample
19222
19223 @noindent
19224 where
19225 @table @var
19226
19227 @item -Pprojname
19228 specifies the project defining the location of source files. When no
19229 file names are provided on the command line, all sources in the project
19230 are used as input. This switch is required.
19231
19232 @item filename
19233 is the name of the source file containing the library unit package declaration
19234 for which a test package will be created. The file name may be given with a
19235 path.
19236
19237 @item @samp{@var{gcc_switches}}
19238 is a list of switches for
19239 @command{gcc}. These switches will be passed on to all compiler invocations
19240 made by @command{gnattest} to generate a set of ASIS trees. Here you can provide
19241 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19242 use the @option{-gnatec} switch to set the configuration file,
19243 use the @option{-gnat05} switch if sources should be compiled in
19244 Ada 2005 mode, etc.
19245
19246 @item switches
19247 is an optional sequence of switches as described in the next section.
19248
19249 @end table
19250
19251 @command{gnattest} results can be found in two different places.
19252
19253 @itemize @bullet
19254 @item automatic harness:
19255 the harness code, which is located by default in "gnattest/harness" directory
19256 that is created in the object directory of corresponding project file. All of
19257 this code is generated completely automatically and can be destroyed and
19258 regenerated at will. It is not recommended to modify this code manually, since
19259 it could easily be overridden by mistake. The entry point in the harness code is
19260 the project file named @command{test_driver.gpr}. Tests can be compiled and run
19261 using a command such as:
19262
19263 @smallexample
19264 gnatmake -P<harness-dir>/test_driver
19265 test_runner
19266 @end smallexample
19267
19268 Note that you might need to specify the necessary values of scenario variables
19269 when you are not using the AUnit defaults.
19270
19271 @item actual unit test skeletons:
19272 a test skeleton for each visible subprogram is created in a separate file, if it
19273 doesn't exist already. By default, those separate test files are located in a
19274 "gnattest/tests" directory that is created in the object directory of
19275 corresponding project file. For example, if a source file my_unit.ads in
19276 directory src contains a visible subprogram Proc, then the corresponding unit
19277 test will be found in file src/tests/my_unit-test_data-tests-proc_<code>.adb.
19278 <code> is a signature encoding used to differentiate test names in case of
19279 overloading.
19280
19281 Note that if the project already has both my_unit.ads and my_unit-test_data.ads,
19282 this will cause a name conflict with the generated test package.
19283 @end itemize
19284
19285 @node Switches for gnattest
19286 @section Switches for @command{gnattest}
19287
19288 @table @option
19289 @c !sort!
19290
19291 @item --harness-only
19292 @cindex @option{--harness-only} (@command{gnattest})
19293 When this option is given, @command{gnattest} creates a harness for all
19294 sources, treating them as test packages.
19295
19296 @item --additional-tests=@var{projname}
19297 @cindex @option{--additional-tests} (@command{gnattest})
19298 Sources described in @var{projname} are considered potential additional
19299 manual tests to be added to the test suite.
19300
19301 @item -r
19302 @cindex @option{-r} (@command{gnattest})
19303 Recursively consider all sources from all projects.
19304
19305 @item -X@var{name=value}
19306 @cindex @option{-X} (@command{gnattest})
19307 Indicate that external variable @var{name} has the value @var{value}.
19308
19309 @item -q
19310 @cindex @option{-q} (@command{gnattest})
19311 Suppresses noncritical output messages.
19312
19313 @item -v
19314 @cindex @option{-v} (@command{gnattest})
19315 Verbose mode: generates version information.
19316
19317 @item --validate-type-extensions
19318 @cindex @option{--validate-type-extensions} (@command{gnattest})
19319 Enables substitution check: run all tests from all parents in order
19320 to check substitutability.
19321
19322 @item --skeleton-default=@var{val}
19323 @cindex @option{--skeleton-default} (@command{gnattest})
19324 Specifies the default behavior of generated skeletons. @var{val} can be either
19325 "fail" or "pass", "fail" being the default.
19326
19327 @item --tests-root=@var{dirname}
19328 @cindex @option{--tests-root} (@command{gnattest})
19329 The directory hierarchy of tested sources is recreated in the @var{dirname}
19330 directory, and test packages are placed in corresponding directories.
19331 If the @var{dirname} is a relative path, it is considered relative to the object
19332 directory of the project file. When all sources from all projects are taken
19333 recursively from all projects, directory hierarchies of tested sources are
19334 recreated for each project in their object directories and test packages are
19335 placed accordingly.
19336
19337 @item --subdir=@var{dirname}
19338 @cindex @option{--subdir} (@command{gnattest})
19339 Test packages are placed in subdirectories.
19340
19341 @item --tests-dir=@var{dirname}
19342 @cindex @option{--tests-dir} (@command{gnattest})
19343 All test packages are placed in the @var{dirname} directory.
19344 If the @var{dirname} is a relative path, it is considered relative to the object
19345 directory of the project file. When all sources from all projects are taken
19346 recursively from all projects, @var{dirname} directories are created for each
19347 project in their object directories and test packages are placed accordingly.
19348
19349 @item --harness-dir=@var{dirname}
19350 @cindex @option{--harness-dir} (@command{gnattest})
19351 specifies the directory that will hold the harness packages and project file
19352 for the test driver. If the @var{dirname} is a relative path, it is considered
19353 relative to the object directory of the project file.
19354
19355 @item --separates
19356 @cindex @option{--separates} (@command{gnattest})
19357 Bodies of all test routines are generated as separates. Note that this mode is
19358 kept for compatibility reasons only and it is not advised to use it due to
19359 possible problems with hash in names of test skeletons when using an
19360 inconsistent casing. Separate test skeletons can be incorporated to monolith
19361 test package with improved hash being used by using @option{--transition}
19362 switch.
19363
19364
19365 @item --transition
19366 @cindex @option{--transition} (@command{gnattest})
19367 This allows transition from separate test routines to monolith test packages.
19368 All matching test routines are overwritten with contents of corresponding
19369 separates. Note that if separate test routines had any manually added with
19370 clauses they will be moved to the test package body as is and have to be moved
19371 by hand.
19372
19373 @end table
19374
19375 @option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are
19376 mutually exclusive.
19377
19378 @node Project Attributes for gnattest
19379 @section Project Attributes for @command{gnattest}
19380
19381 @noindent
19382
19383 Most of the command-line options can also be passed to the tool by adding
19384 special attributes to the project file. Those attributes should be put in
19385 package gnattest. Here is the list of attributes:
19386
19387 @itemize @bullet
19388
19389 @item Tests_Root
19390 is used to select the same output mode as with the --tests-root option.
19391 This attribute cannot be used together with Subdir or Tests_Dir.
19392
19393 @item Subdir
19394 is used to select the same output mode as with the --subdir option.
19395 This attribute cannot be used together with Tests_Root or Tests_Dir.
19396
19397 @item Tests_Dir
19398 is used to select the same output mode as with the --tests-dir option.
19399 This attribute cannot be used together with Subdir or Tests_Root.
19400
19401 @item Harness_Dir
19402 is used to specify the directory in which to place harness packages and project
19403 file for the test driver, otherwise specified by --harness-dir.
19404
19405 @item Additional_Tests
19406 is used to specify the project file, otherwise given by
19407 --additional-tests switch.
19408
19409 @item Skeletons_Default
19410 is used to specify the default behaviour of test skeletons, otherwise
19411 specified by --skeleton-default option. The value of this attribute
19412 should be either "pass" or "fail".
19413
19414 @end itemize
19415
19416 Each of those attributes can be overridden from the command line if needed.
19417 Other @command{gnattest} switches can also be passed via the project
19418 file as an attribute list called GNATtest_Switches.
19419
19420 @node Simple Example
19421 @section Simple Example
19422
19423 @noindent
19424
19425 Let's take a very simple example using the first @command{gnattest} example
19426 located in:
19427
19428 @smallexample
19429 <install_prefix>/share/examples/gnattest/simple
19430 @end smallexample
19431
19432 This project contains a simple package containing one subprogram. By running gnattest:
19433
19434 @smallexample
19435 $ gnattest --harness-dir=driver -Psimple.gpr
19436 @end smallexample
19437
19438 a test driver is created in directory "driver". It can be compiled and run:
19439
19440 @smallexample
19441 $ cd obj/driver
19442 $ gnatmake -Ptest_driver
19443 $ test_runner
19444 @end smallexample
19445
19446 One failed test with diagnosis "test not implemented" is reported.
19447 Since no special output option was specified, the test package Simple.Tests
19448 is located in:
19449
19450 @smallexample
19451 <install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
19452 @end smallexample
19453
19454 For each package containing visible subprograms, a child test package is
19455 generated. It contains one test routine per tested subprogram. Each
19456 declaration of a test subprogram has a comment specifying which tested
19457 subprogram it corresponds to. Bodies of test routines are placed in test package
19458 bodies and are surrounded by special comment sections. Those comment sections
19459 should not be removed or modified in order for gnattest to be able to regenerate
19460 test packages and keep already written tests in place.
19461 The test routine Test_Inc_5eaee3 located at simple-test_data-tests.adb contains
19462 a single statement: a call to procedure Assert. It has two arguments:
19463 the Boolean expression we want to check and the diagnosis message to display if
19464 the condition is false.
19465
19466 That is where actual testing code should be written after a proper setup.
19467 An actual check can be performed by replacing the Assert call with:
19468
19469 @smallexample @c ada
19470 Assert (Inc (1) = 2, "wrong incrementation");
19471 @end smallexample
19472
19473 After recompiling and running the test driver, one successfully passed test
19474 is reported.
19475
19476 @node Setting Up and Tearing Down the Testing Environment
19477 @section Setting Up and Tearing Down the Testing Environment
19478
19479 @noindent
19480
19481 Besides test routines themselves, each test package has a parent package
19482 Test_Data that has two procedures: Set_Up and Tear_Down. This package is never
19483 overwritten by the tool. Set_Up is called before each test routine of the
19484 package and Tear_Down is called after each test routine. Those two procedures
19485 can be used to perform necessary initialization and finalization,
19486 memory allocation, etc. Test type declared in Test_Data package is parent type
19487 for the test type of test package and can have user-defined components whose
19488 values can be set by Set_Up routine and used in test routines afterwards.
19489
19490 @node Regenerating Tests
19491 @section Regenerating Tests
19492
19493 @noindent
19494
19495 Bodies of test routines and test_data packages are never overridden after they
19496 have been created once. As long as the name of the subprogram, full expanded Ada
19497 names, and the order of its parameters is the same, and comment sections are
19498 intact the old test routine will fit in its place and no test skeleton will be
19499 generated for the subprogram.
19500
19501 This can be demonstrated with the previous example. By uncommenting declaration
19502 and body of function Dec in simple.ads and simple.adb, running
19503 @command{gnattest} on the project, and then running the test driver:
19504
19505 @smallexample
19506 gnattest --harness-dir=driver -Psimple.gpr
19507 cd obj/driver
19508 gnatmake -Ptest_driver
19509 test_runner
19510 @end smallexample
19511
19512 the old test is not replaced with a stub, nor is it lost, but a new test
19513 skeleton is created for function Dec.
19514
19515 The only way of regenerating tests skeletons is to remove the previously created
19516 tests together with corresponding comment sections.
19517
19518 @node Default Test Behavior
19519 @section Default Test Behavior
19520
19521 @noindent
19522
19523 The generated test driver can treat unimplemented tests in two ways:
19524 either count them all as failed (this is useful to see which tests are still
19525 left to implement) or as passed (to sort out unimplemented ones from those
19526 actually failing).
19527
19528 The test driver accepts a switch to specify this behavior:
19529 --skeleton-default=val, where val is either "pass" or "fail" (exactly as for
19530 @command{gnattest}).
19531
19532 The default behavior of the test driver is set with the same switch
19533 as passed to gnattest when generating the test driver.
19534
19535 Passing it to the driver generated on the first example:
19536
19537 @smallexample
19538 test_runner --skeleton-default=pass
19539 @end smallexample
19540
19541 makes both tests pass, even the unimplemented one.
19542
19543 @node Testing Primitive Operations of Tagged Types
19544 @section Testing Primitive Operations of Tagged Types
19545
19546 @noindent
19547
19548 Creation of test skeletons for primitive operations of tagged types entails
19549 a number of features. Test routines for all primitives of a given tagged type
19550 are placed in a separate child package named according to the tagged type. For
19551 example, if you have tagged type T in package P, all tests for primitives
19552 of T will be in P.T_Test_Data.T_Tests.
19553
19554 Consider running gnattest on the second example (note: actual tests for this
19555 example already exist, so there's no need to worry if the tool reports that
19556 no new stubs were generated):
19557
19558 @smallexample
19559 cd <install_prefix>/share/examples/gnattest/tagged_rec
19560 gnattest --harness-dir=driver -Ptagged_rec.gpr
19561 @end smallexample
19562
19563 Taking a closer look at the test type declared in the test package
19564 Speed1.Controller_Test_Data is necessary. It is declared in:
19565
19566 @smallexample
19567 <install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
19568 @end smallexample
19569
19570 Test types are direct or indirect descendants of
19571 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
19572 subprograms, the user doesn't need to be concerned with them. However,
19573 when generating test packages for primitive operations, there are some things
19574 the user needs to know.
19575
19576 Type Test_Controller has components that allow assignment of various
19577 derivations of type Controller. And if you look at the specification of
19578 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
19579 actually derives from Test_Controller rather than AUnit type Test_Fixture.
19580 Thus, test types mirror the hierarchy of tested types.
19581
19582 The Set_Up procedure of Test_Data package corresponding to a test package
19583 of primitive operations of type T assigns to Fixture a reference to an
19584 object of that exact type T. Notice, however, that if the tagged type has
19585 discriminants, the Set_Up only has a commented template for setting
19586 up the fixture, since filling the discriminant with actual value is up
19587 to the user.
19588
19589 The knowledge of the structure of test types allows additional testing
19590 without additional effort. Those possibilities are described below.
19591
19592 @node Testing Inheritance
19593 @section Testing Inheritance
19594
19595 @noindent
19596
19597 Since the test type hierarchy mimics the hierarchy of tested types, the
19598 inheritance of tests takes place. An example of such inheritance can be
19599 seen by running the test driver generated for the second example. As previously
19600 mentioned, actual tests are already written for this example.
19601
19602 @smallexample
19603 cd obj/driver
19604 gnatmake -Ptest_driver
19605 test_runner
19606 @end smallexample
19607
19608 There are 6 passed tests while there are only 5 testable subprograms. The test
19609 routine for function Speed has been inherited and run against objects of the
19610 derived type.
19611
19612 @node Tagged Types Substitutability Testing
19613 @section Tagged Types Substitutability Testing
19614
19615 @noindent
19616
19617 Tagged Types Substitutability Testing is a way of verifying the global type
19618 consistency by testing. Global type consistency is a principle stating that if
19619 S is a subtype of T (in Ada, S is a derived type of tagged type T),
19620 then objects of type T may be replaced with objects of type S (that is,
19621 objects of type S may be substituted for objects of type T), without
19622 altering any of the desirable properties of the program. When the properties
19623 of the program are expressed in the form of subprogram preconditions and
19624 postconditions (let's call them pre and post), the principle is formulated as
19625 relations between the pre and post of primitive operations and the pre and post
19626 of their derived operations. The pre of a derived operation should not be
19627 stronger than the original pre, and the post of the derived operation should
19628 not be weaker than the original post. Those relations ensure that verifying if
19629 a dispatching call is safe can be done just by using the pre and post of the
19630 root operation.
19631
19632 Verifying global type consistency by testing consists of running all the unit
19633 tests associated with the primitives of a given tagged type with objects of its
19634 derived types.
19635
19636 In the example used in the previous section, there was clearly a violation of
19637 type consistency. The overriding primitive Adjust_Speed in package Speed2
19638 removes the functionality of the overridden primitive and thus doesn't respect
19639 the consistency principle.
19640 Gnattest has a special option to run overridden parent tests against objects
19641 of the type which have overriding primitives:
19642
19643 @smallexample
19644 gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr
19645 cd obj/driver
19646 gnatmake -Ptest_driver
19647 test_runner
19648 @end smallexample
19649
19650 While all the tests pass by themselves, the parent test for Adjust_Speed fails
19651 against objects of the derived type.
19652
19653 Non-overridden tests are already inherited for derived test types, so the
19654 --validate-type-extensions enables the application of overriden tests to objects
19655 of derived types.
19656
19657 @node Testing with Contracts
19658 @section Testing with Contracts
19659
19660 @noindent
19661
19662 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case,
19663 as well as corresponding aspects.
19664 Test routines are generated, one per each Test_Case associated with a tested
19665 subprogram. Those test routines have special wrappers for tested functions
19666 that have composition of pre- and postcondition of the subprogram with
19667 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
19668 either count for Nominal mode or do not count for Robustness mode).
19669
19670 The third example demonstrates how this works:
19671
19672 @smallexample
19673 cd <install_prefix>/share/examples/gnattest/contracts
19674 gnattest --harness-dir=driver -Pcontracts.gpr
19675 @end smallexample
19676
19677 Putting actual checks within the range of the contract does not cause any
19678 error reports. For example, for the test routine which corresponds to
19679 test case 1:
19680
19681 @smallexample @c ada
19682 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
19683 @end smallexample
19684
19685 and for the test routine corresponding to test case 2:
19686
19687 @smallexample @c ada
19688 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
19689 @end smallexample
19690
19691 are acceptable:
19692
19693 @smallexample
19694 cd obj/driver
19695 gnatmake -Ptest_driver
19696 test_runner
19697 @end smallexample
19698
19699 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
19700 a precondition violation for test case one. Also, by using any otherwise
19701 correct but positive pair of numbers in the second test routine, you can also
19702 get a precondition violation. Postconditions are checked and reported
19703 the same way.
19704
19705 @node Additional Tests
19706 @section Additional Tests
19707
19708 @noindent
19709 @command{gnattest} can add user-written tests to the main suite of the test
19710 driver. @command{gnattest} traverses the given packages and searches for test
19711 routines. All procedures with a single in out parameter of a type which is
19712 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
19713 specifications are added to the suites and are then executed by the test driver.
19714 (Set_Up and Tear_Down are filtered out.)
19715
19716 An example illustrates two ways of creating test harnesses for user-written
19717 tests. Directory additional_tests contains an AUnit-based test driver written
19718 by hand.
19719
19720 @smallexample
19721 <install_prefix>/share/examples/gnattest/additional_tests/
19722 @end smallexample
19723
19724 To create a test driver for already-written tests, use the --harness-only
19725 option:
19726
19727 @smallexample
19728 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
19729 --harness-only
19730 gnatmake -Pharness_only/test_driver.gpr
19731 harness_only/test_runner
19732 @end smallexample
19733
19734 Additional tests can also be executed together with generated tests:
19735
19736 @smallexample
19737 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
19738 --harness-dir=mixing
19739 gnatmake -Pmixing/test_driver.gpr
19740 mixing/test_runner
19741 @end smallexample
19742
19743 @ifclear vms
19744 @node Support for other platforms/run-times
19745 @section Support for other platforms/run-times
19746
19747 @noindent
19748 @command{gnattest} can be used to generate the test harness for platforms
19749 and run-time libraries others than the default native target with the
19750 default full run-time. For example, when using a limited run-time library
19751 such as Zero FootPrint (ZFP), a simplified harness is generated.
19752
19753 Two variables are used to tell the underlying AUnit framework how to generate
19754 the test harness: @code{PLATFORM}, which identifies the target, and
19755 @code{RUNTIME}, used to determine the run-time library for which the harness
19756 is generated. Corresponding prefix should also be used when calling
19757 @command{gnattest} for non-native targets. For example, the following options
19758 are used to generate the AUnit test harness for a PowerPC ELF target using
19759 the ZFP run-time library:
19760
19761 @smallexample
19762 powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
19763 @end smallexample
19764 @end ifclear
19765
19766 @node Current Limitations
19767 @section Current Limitations
19768
19769 @noindent
19770
19771 The tool currently does not support following features:
19772
19773 @itemize @bullet
19774 @item generic tests for generic packages and package instantiations
19775 @item tests for protected subprograms and entries
19776
19777 @end itemize
19778
19779 @c *********************************
19780 @node Performing Dimensionality Analysis in GNAT
19781 @chapter Performing Dimensionality Analysis in GNAT
19782 @noindent
19783 The GNAT compiler now supports dimensionality checking. The user can
19784 specify physical units for objects, and the compiler will verify that uses
19785 of these objects are compatible with their dimensions, in a fashion that is
19786 familiar to engineering practice. The dimensions of algebraic expressions
19787 (including powers with static exponents) are computed from their consistuents.
19788
19789 This feature depends on Ada 2012 aspect specifications, and is available from
19790 version 7.0.1 of GNAT onwards. The GNAT-specific aspect Dimension_System allows
19791 you to define a system of units; the aspect Dimension then allows the user
19792 to declare dimensioned quantities within a given system.
19793
19794 The major advantage of this model is that it does not require the declaration of
19795 multiple operators for all possible combinations of types: it is only necessary
19796 to use the proper subtypes in object declarations.
19797
19798 The simplest way to impose dimensionality checking on a computation is to make
19799 use of the package System.Dim.Mks, which is part of the GNAT library. This
19800 package defines a floating-point type MKS_Type, for which a sequence of
19801 dimension names are specified, together with their conventional abbreviations.
19802 The following should be read together with the full specification of the
19803 package, in file s-dimmks.ads.
19804
19805 @smallexample @c ada
19806 type Mks_Type is new Long_Long_Float
19807 with
19808 Dimension_System => (
19809 (Unit_Name => Meter, Unit_Symbol => 'm', Dim_Symbol => 'L'),
19810 (Unit_Name => Kilogram, Unit_Symbol => "kg", Dim_Symbol => 'M'),
19811 (Unit_Name => Second, Unit_Symbol => 's', Dim_Symbol => 'T'),
19812 (Unit_Name => Ampere, Unit_Symbol => 'A', Dim_Symbol => 'I'),
19813 (Unit_Name => Kelvin, Unit_Symbol => 'K', Dim_Symbol => "Theta"),
19814 (Unit_Name => Mole, Unit_Symbol => "mol", Dim_Symbol => 'N'),
19815 (Unit_Name => Candela, Unit_Symbol => "cd", Dim_Symbol => 'J'));
19816 @end smallexample
19817
19818 @noindent
19819 The package then defines a series of subtypes that correspond to these
19820 conventional units. For example:
19821 @smallexample @c ada
19822 subtype Length is Mks_Type
19823 with
19824 Dimension => (Symbol => 'm', Meter => 1, others => 0);
19825 @end smallexample
19826 @noindent
19827 and similarly for Mass, Time, Electric_Current, Thermodynamic_Temperature,
19828 Amount_Of_Substance, and Luminous_Intensity (the standard set of units of
19829 the SI system).
19830
19831 The package also defines conventional names for values of each unit, for
19832 example:
19833
19834 @smallexample @c ada
19835 m : constant Length := 1.0;
19836 kg : constant Mass := 1.0;
19837 s : constant Time := 1.0;
19838 A : constant Electric_Current := 1.0;
19839 @end smallexample
19840
19841 @noindent
19842 as well as useful multiples of these units:
19843
19844 @smallexample @c ada
19845 cm : constant Length := 1.0E-02;
19846 g : constant Mass := 1.0E-03;
19847 min : constant Time := 60.0;
19848 day : constant TIme := 60.0 * 24.0 * min;
19849 ...
19850 @end smallexample
19851
19852 @noindent
19853 Using this package, you can then define a derived unit by
19854 providing the aspect that
19855 specifies its dimensions within the MKS system, as well as the string to
19856 be used for output of a value of that unit:
19857
19858 @smallexample @c ada
19859 subtype Acceleration is Mks_Type
19860 with Dimension => ("m/sec^^^2",
19861 Meter => 1,
19862 Second => -2,
19863 others => 0);
19864 @end smallexample
19865
19866 @noindent
19867 Here is a complete example of use:
19868
19869 @smallexample @c ada
19870 with System.Dim.MKS; use System.Dim.Mks;
19871 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
19872 with Text_IO; use Text_IO;
19873 procedure Free_Fall is
19874 subtype Acceleration is Mks_Type
19875 with Dimension => ("m/sec^^^2", 1, 0, -2, others => 0);
19876 G : constant acceleration := 9.81 * m / (s ** 2);
19877 T : Time := 10.0*s;
19878 Distance : Length;
19879 begin
19880 Put ("Gravitational constant: ");
19881 Put (G, Aft => 2, Exp => 0); Put_Line ("");
19882 Distance := 0.5 * G * T ** 2;
19883 Put ("distance travelled in 10 seconds of free fall ");
19884 Put (Distance, Aft => 2, Exp => 0);
19885 Put_Line ("");
19886 end Free_Fall;
19887 @end smallexample
19888
19889 @noindent
19890 Execution of this program yields:
19891 @smallexample
19892 Gravitational constant: 9.81 m/sec^^^2
19893 distance travelled in 10 seconds of free fall 490.50 m
19894 @end smallexample
19895
19896 @noindent
19897 However, incorrect assignments such as:
19898
19899 @smallexample @c ada
19900 Distance := 5.0;
19901 Distance := 5.0 * kg:
19902 @end smallexample
19903
19904 @noindent
19905 are rejected with the following diagnoses:
19906
19907 @smallexample
19908 Distance := 5.0;
19909 >>> dimensions mismatch in assignment
19910 >>> left-hand side has dimension [L]
19911 >>> right-hand side is dimensionless
19912
19913 Distance := 5.0 * kg:
19914 >>> dimensions mismatch in assignment
19915 >>> left-hand side has dimension [L]
19916 >>> right-hand side has dimension [M]
19917 @end smallexample
19918
19919 @noindent
19920 The dimensions of an expression are properly displayed, even if there is
19921 no explicit subtype for it. If we add to the program:
19922
19923 @smallexample @c ada
19924 Put ("Final velocity: ");
19925 Put (G * T, Aft =>2, Exp =>0);
19926 Put_Line ("");
19927 @end smallexample
19928
19929 @noindent
19930 then the output includes:
19931 @smallexample
19932 Final velocity: 98.10 m.s**(-1)
19933 @end smallexample
19934
19935 @c *********************************
19936 @node Generating Ada Bindings for C and C++ headers
19937 @chapter Generating Ada Bindings for C and C++ headers
19938 @findex binding
19939
19940 @noindent
19941 GNAT now comes with a binding generator for C and C++ headers which is
19942 intended to do 95% of the tedious work of generating Ada specs from C
19943 or C++ header files.
19944
19945 Note that this capability is not intended to generate 100% correct Ada specs,
19946 and will is some cases require manual adjustments, although it can often
19947 be used out of the box in practice.
19948
19949 Some of the known limitations include:
19950
19951 @itemize @bullet
19952 @item only very simple character constant macros are translated into Ada
19953 constants. Function macros (macros with arguments) are partially translated
19954 as comments, to be completed manually if needed.
19955 @item some extensions (e.g. vector types) are not supported
19956 @item pointers to pointers or complex structures are mapped to System.Address
19957 @item identifiers with identical name (except casing) will generate compilation
19958 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
19959 @end itemize
19960
19961 The code generated is using the Ada 2005 syntax, which makes it
19962 easier to interface with other languages than previous versions of Ada.
19963
19964 @menu
19965 * Running the binding generator::
19966 * Generating bindings for C++ headers::
19967 * Switches::
19968 @end menu
19969
19970 @node Running the binding generator
19971 @section Running the binding generator
19972
19973 @noindent
19974 The binding generator is part of the @command{gcc} compiler and can be
19975 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
19976 spec files for the header files specified on the command line, and all
19977 header files needed by these files transitively. For example:
19978
19979 @smallexample
19980 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
19981 $ gcc -c -gnat05 *.ads
19982 @end smallexample
19983
19984 will generate, under GNU/Linux, the following files: @file{time_h.ads},
19985 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
19986 correspond to the files @file{/usr/include/time.h},
19987 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
19988 mode these Ada specs.
19989
19990 The @code{-C} switch tells @command{gcc} to extract comments from headers,
19991 and will attempt to generate corresponding Ada comments.
19992
19993 If you want to generate a single Ada file and not the transitive closure, you
19994 can use instead the @option{-fdump-ada-spec-slim} switch.
19995
19996 You can optionally specify a parent unit, of which all generated units will
19997 be children, using @code{-fada-spec-parent=}@var{unit}.
19998
19999 Note that we recommend when possible to use the @command{g++} driver to
20000 generate bindings, even for most C headers, since this will in general
20001 generate better Ada specs. For generating bindings for C++ headers, it is
20002 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
20003 is equivalent in this case. If @command{g++} cannot work on your C headers
20004 because of incompatibilities between C and C++, then you can fallback to
20005 @command{gcc} instead.
20006
20007 For an example of better bindings generated from the C++ front-end,
20008 the name of the parameters (when available) are actually ignored by the C
20009 front-end. Consider the following C header:
20010
20011 @smallexample
20012 extern void foo (int variable);
20013 @end smallexample
20014
20015 with the C front-end, @code{variable} is ignored, and the above is handled as:
20016
20017 @smallexample
20018 extern void foo (int);
20019 @end smallexample
20020
20021 generating a generic:
20022
20023 @smallexample
20024 procedure foo (param1 : int);
20025 @end smallexample
20026
20027 with the C++ front-end, the name is available, and we generate:
20028
20029 @smallexample
20030 procedure foo (variable : int);
20031 @end smallexample
20032
20033 In some cases, the generated bindings will be more complete or more meaningful
20034 when defining some macros, which you can do via the @option{-D} switch. This
20035 is for example the case with @file{Xlib.h} under GNU/Linux:
20036
20037 @smallexample
20038 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
20039 @end smallexample
20040
20041 The above will generate more complete bindings than a straight call without
20042 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
20043
20044 In other cases, it is not possible to parse a header file in a stand-alone
20045 manner, because other include files need to be included first. In this
20046 case, the solution is to create a small header file including the needed
20047 @code{#include} and possible @code{#define} directives. For example, to
20048 generate Ada bindings for @file{readline/readline.h}, you need to first
20049 include @file{stdio.h}, so you can create a file with the following two
20050 lines in e.g. @file{readline1.h}:
20051
20052 @smallexample
20053 #include <stdio.h>
20054 #include <readline/readline.h>
20055 @end smallexample
20056
20057 and then generate Ada bindings from this file:
20058
20059 @smallexample
20060 $ g++ -c -fdump-ada-spec readline1.h
20061 @end smallexample
20062
20063 @node Generating bindings for C++ headers
20064 @section Generating bindings for C++ headers
20065
20066 @noindent
20067 Generating bindings for C++ headers is done using the same options, always
20068 with the @command{g++} compiler.
20069
20070 In this mode, C++ classes will be mapped to Ada tagged types, constructors
20071 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
20072 multiple inheritance of abstract classes will be mapped to Ada interfaces
20073 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
20074 information on interfacing to C++).
20075
20076 For example, given the following C++ header file:
20077
20078 @smallexample
20079 @group
20080 @cartouche
20081 class Carnivore @{
20082 public:
20083 virtual int Number_Of_Teeth () = 0;
20084 @};
20085
20086 class Domestic @{
20087 public:
20088 virtual void Set_Owner (char* Name) = 0;
20089 @};
20090
20091 class Animal @{
20092 public:
20093 int Age_Count;
20094 virtual void Set_Age (int New_Age);
20095 @};
20096
20097 class Dog : Animal, Carnivore, Domestic @{
20098 public:
20099 int Tooth_Count;
20100 char *Owner;
20101
20102 virtual int Number_Of_Teeth ();
20103 virtual void Set_Owner (char* Name);
20104
20105 Dog();
20106 @};
20107 @end cartouche
20108 @end group
20109 @end smallexample
20110
20111 The corresponding Ada code is generated:
20112
20113 @smallexample @c ada
20114 @group
20115 @cartouche
20116 package Class_Carnivore is
20117 type Carnivore is limited interface;
20118 pragma Import (CPP, Carnivore);
20119
20120 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
20121 end;
20122 use Class_Carnivore;
20123
20124 package Class_Domestic is
20125 type Domestic is limited interface;
20126 pragma Import (CPP, Domestic);
20127
20128 procedure Set_Owner
20129 (this : access Domestic;
20130 Name : Interfaces.C.Strings.chars_ptr) is abstract;
20131 end;
20132 use Class_Domestic;
20133
20134 package Class_Animal is
20135 type Animal is tagged limited record
20136 Age_Count : aliased int;
20137 end record;
20138 pragma Import (CPP, Animal);
20139
20140 procedure Set_Age (this : access Animal; New_Age : int);
20141 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
20142 end;
20143 use Class_Animal;
20144
20145 package Class_Dog is
20146 type Dog is new Animal and Carnivore and Domestic with record
20147 Tooth_Count : aliased int;
20148 Owner : Interfaces.C.Strings.chars_ptr;
20149 end record;
20150 pragma Import (CPP, Dog);
20151
20152 function Number_Of_Teeth (this : access Dog) return int;
20153 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
20154
20155 procedure Set_Owner
20156 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
20157 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
20158
20159 function New_Dog return Dog;
20160 pragma CPP_Constructor (New_Dog);
20161 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
20162 end;
20163 use Class_Dog;
20164 @end cartouche
20165 @end group
20166 @end smallexample
20167
20168 @node Switches
20169 @section Switches
20170
20171 @table @option
20172 @item -fdump-ada-spec
20173 @cindex @option{-fdump-ada-spec} (@command{gcc})
20174 Generate Ada spec files for the given header files transitively (including
20175 all header files that these headers depend upon).
20176
20177 @item -fdump-ada-spec-slim
20178 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
20179 Generate Ada spec files for the header files specified on the command line
20180 only.
20181
20182 @item -fada-spec-parent=@var{unit}
20183 @cindex -fada-spec-parent (@command{gcc})
20184 Specifies that all files generated by @option{-fdump-ada-spec*} are
20185 to be child units of the specified parent unit.
20186
20187 @item -C
20188 @cindex @option{-C} (@command{gcc})
20189 Extract comments from headers and generate Ada comments in the Ada spec files.
20190 @end table
20191
20192 @node Other Utility Programs
20193 @chapter Other Utility Programs
20194
20195 @noindent
20196 This chapter discusses some other utility programs available in the Ada
20197 environment.
20198
20199 @menu
20200 * Using Other Utility Programs with GNAT::
20201 * The External Symbol Naming Scheme of GNAT::
20202 * Converting Ada Files to html with gnathtml::
20203 * Installing gnathtml::
20204 @ifset vms
20205 * LSE::
20206 * Profiling::
20207 @end ifset
20208 @end menu
20209
20210 @node Using Other Utility Programs with GNAT
20211 @section Using Other Utility Programs with GNAT
20212
20213 @noindent
20214 The object files generated by GNAT are in standard system format and in
20215 particular the debugging information uses this format. This means
20216 programs generated by GNAT can be used with existing utilities that
20217 depend on these formats.
20218
20219 @ifclear vms
20220 In general, any utility program that works with C will also often work with
20221 Ada programs generated by GNAT. This includes software utilities such as
20222 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
20223 as Purify.
20224 @end ifclear
20225
20226 @node The External Symbol Naming Scheme of GNAT
20227 @section The External Symbol Naming Scheme of GNAT
20228
20229 @noindent
20230 In order to interpret the output from GNAT, when using tools that are
20231 originally intended for use with other languages, it is useful to
20232 understand the conventions used to generate link names from the Ada
20233 entity names.
20234
20235 All link names are in all lowercase letters. With the exception of library
20236 procedure names, the mechanism used is simply to use the full expanded
20237 Ada name with dots replaced by double underscores. For example, suppose
20238 we have the following package spec:
20239
20240 @smallexample @c ada
20241 @group
20242 @cartouche
20243 package QRS is
20244 MN : Integer;
20245 end QRS;
20246 @end cartouche
20247 @end group
20248 @end smallexample
20249
20250 @noindent
20251 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
20252 the corresponding link name is @code{qrs__mn}.
20253 @findex Export
20254 Of course if a @code{pragma Export} is used this may be overridden:
20255
20256 @smallexample @c ada
20257 @group
20258 @cartouche
20259 package Exports is
20260 Var1 : Integer;
20261 pragma Export (Var1, C, External_Name => "var1_name");
20262 Var2 : Integer;
20263 pragma Export (Var2, C, Link_Name => "var2_link_name");
20264 end Exports;
20265 @end cartouche
20266 @end group
20267 @end smallexample
20268
20269 @noindent
20270 In this case, the link name for @var{Var1} is whatever link name the
20271 C compiler would assign for the C function @var{var1_name}. This typically
20272 would be either @var{var1_name} or @var{_var1_name}, depending on operating
20273 system conventions, but other possibilities exist. The link name for
20274 @var{Var2} is @var{var2_link_name}, and this is not operating system
20275 dependent.
20276
20277 @findex _main
20278 One exception occurs for library level procedures. A potential ambiguity
20279 arises between the required name @code{_main} for the C main program,
20280 and the name we would otherwise assign to an Ada library level procedure
20281 called @code{Main} (which might well not be the main program).
20282
20283 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
20284 names. So if we have a library level procedure such as
20285
20286 @smallexample @c ada
20287 @group
20288 @cartouche
20289 procedure Hello (S : String);
20290 @end cartouche
20291 @end group
20292 @end smallexample
20293
20294 @noindent
20295 the external name of this procedure will be @var{_ada_hello}.
20296
20297
20298 @node Converting Ada Files to html with gnathtml
20299 @section Converting Ada Files to HTML with @code{gnathtml}
20300
20301 @noindent
20302 This @code{Perl} script allows Ada source files to be browsed using
20303 standard Web browsers. For installation procedure, see the section
20304 @xref{Installing gnathtml}.
20305
20306 Ada reserved keywords are highlighted in a bold font and Ada comments in
20307 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
20308 switch to suppress the generation of cross-referencing information, user
20309 defined variables and types will appear in a different color; you will
20310 be able to click on any identifier and go to its declaration.
20311
20312 The command line is as follow:
20313 @smallexample
20314 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
20315 @c Expanding @ovar macro inline (explanation in macro def comments)
20316 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
20317 @end smallexample
20318
20319 @noindent
20320 You can pass it as many Ada files as you want. @code{gnathtml} will generate
20321 an html file for every ada file, and a global file called @file{index.htm}.
20322 This file is an index of every identifier defined in the files.
20323
20324 The available ^switches^options^ are the following ones:
20325
20326 @table @option
20327 @item -83
20328 @cindex @option{-83} (@code{gnathtml})
20329 Only the Ada 83 subset of keywords will be highlighted.
20330
20331 @item -cc @var{color}
20332 @cindex @option{-cc} (@code{gnathtml})
20333 This option allows you to change the color used for comments. The default
20334 value is green. The color argument can be any name accepted by html.
20335
20336 @item -d
20337 @cindex @option{-d} (@code{gnathtml})
20338 If the Ada files depend on some other files (for instance through
20339 @code{with} clauses, the latter files will also be converted to html.
20340 Only the files in the user project will be converted to html, not the files
20341 in the run-time library itself.
20342
20343 @item -D
20344 @cindex @option{-D} (@code{gnathtml})
20345 This command is the same as @option{-d} above, but @command{gnathtml} will
20346 also look for files in the run-time library, and generate html files for them.
20347
20348 @item -ext @var{extension}
20349 @cindex @option{-ext} (@code{gnathtml})
20350 This option allows you to change the extension of the generated HTML files.
20351 If you do not specify an extension, it will default to @file{htm}.
20352
20353 @item -f
20354 @cindex @option{-f} (@code{gnathtml})
20355 By default, gnathtml will generate html links only for global entities
20356 ('with'ed units, global variables and types,@dots{}). If you specify
20357 @option{-f} on the command line, then links will be generated for local
20358 entities too.
20359
20360 @item -l @var{number}
20361 @cindex @option{-l} (@code{gnathtml})
20362 If this ^switch^option^ is provided and @var{number} is not 0, then
20363 @code{gnathtml} will number the html files every @var{number} line.
20364
20365 @item -I @var{dir}
20366 @cindex @option{-I} (@code{gnathtml})
20367 Specify a directory to search for library files (@file{.ALI} files) and
20368 source files. You can provide several -I switches on the command line,
20369 and the directories will be parsed in the order of the command line.
20370
20371 @item -o @var{dir}
20372 @cindex @option{-o} (@code{gnathtml})
20373 Specify the output directory for html files. By default, gnathtml will
20374 saved the generated html files in a subdirectory named @file{html/}.
20375
20376 @item -p @var{file}
20377 @cindex @option{-p} (@code{gnathtml})
20378 If you are using Emacs and the most recent Emacs Ada mode, which provides
20379 a full Integrated Development Environment for compiling, checking,
20380 running and debugging applications, you may use @file{.gpr} files
20381 to give the directories where Emacs can find sources and object files.
20382
20383 Using this ^switch^option^, you can tell gnathtml to use these files.
20384 This allows you to get an html version of your application, even if it
20385 is spread over multiple directories.
20386
20387 @item -sc @var{color}
20388 @cindex @option{-sc} (@code{gnathtml})
20389 This ^switch^option^ allows you to change the color used for symbol
20390 definitions.
20391 The default value is red. The color argument can be any name accepted by html.
20392
20393 @item -t @var{file}
20394 @cindex @option{-t} (@code{gnathtml})
20395 This ^switch^option^ provides the name of a file. This file contains a list of
20396 file names to be converted, and the effect is exactly as though they had
20397 appeared explicitly on the command line. This
20398 is the recommended way to work around the command line length limit on some
20399 systems.
20400
20401 @end table
20402
20403 @node Installing gnathtml
20404 @section Installing @code{gnathtml}
20405
20406 @noindent
20407 @code{Perl} needs to be installed on your machine to run this script.
20408 @code{Perl} is freely available for almost every architecture and
20409 Operating System via the Internet.
20410
20411 On Unix systems, you may want to modify the first line of the script
20412 @code{gnathtml}, to explicitly tell the Operating system where Perl
20413 is. The syntax of this line is:
20414 @smallexample
20415 #!full_path_name_to_perl
20416 @end smallexample
20417
20418 @noindent
20419 Alternatively, you may run the script using the following command line:
20420
20421 @smallexample
20422 @c $ perl gnathtml.pl @ovar{switches} @var{files}
20423 @c Expanding @ovar macro inline (explanation in macro def comments)
20424 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
20425 @end smallexample
20426
20427 @ifset vms
20428 @node LSE
20429 @section LSE
20430 @findex LSE
20431
20432 @noindent
20433 The GNAT distribution provides an Ada 95 template for the HP Language
20434 Sensitive Editor (LSE), a component of DECset. In order to
20435 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
20436
20437 @node Profiling
20438 @section Profiling
20439 @findex PCA
20440
20441 @noindent
20442 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
20443 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
20444 the collection phase with the /DEBUG qualifier.
20445
20446 @smallexample
20447 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
20448 $ DEFINE LIB$DEBUG PCA$COLLECTOR
20449 $ RUN/DEBUG <PROGRAM_NAME>
20450 @end smallexample
20451 @noindent
20452 @end ifset
20453
20454 @ifclear vms
20455 @c ******************************
20456 @node Code Coverage and Profiling
20457 @chapter Code Coverage and Profiling
20458 @cindex Code Coverage
20459 @cindex Profiling
20460
20461 @noindent
20462 This chapter describes how to use @code{gcov} - coverage testing tool - and
20463 @code{gprof} - profiler tool - on your Ada programs.
20464
20465 @menu
20466 * Code Coverage of Ada Programs with gcov::
20467 * Profiling an Ada Program with gprof::
20468 @end menu
20469
20470 @node Code Coverage of Ada Programs with gcov
20471 @section Code Coverage of Ada Programs with gcov
20472 @cindex gcov
20473 @cindex -fprofile-arcs
20474 @cindex -ftest-coverage
20475 @cindex -coverage
20476 @cindex Code Coverage
20477
20478 @noindent
20479 @code{gcov} is a test coverage program: it analyzes the execution of a given
20480 program on selected tests, to help you determine the portions of the program
20481 that are still untested.
20482
20483 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
20484 User's Guide. You can refer to this documentation for a more complete
20485 description.
20486
20487 This chapter provides a quick startup guide, and
20488 details some Gnat-specific features.
20489
20490 @menu
20491 * Quick startup guide::
20492 * Gnat specifics::
20493 @end menu
20494
20495 @node Quick startup guide
20496 @subsection Quick startup guide
20497
20498 In order to perform coverage analysis of a program using @code{gcov}, 3
20499 steps are needed:
20500
20501 @itemize @bullet
20502 @item
20503 Code instrumentation during the compilation process
20504 @item
20505 Execution of the instrumented program
20506 @item
20507 Execution of the @code{gcov} tool to generate the result.
20508 @end itemize
20509
20510 The code instrumentation needed by gcov is created at the object level:
20511 The source code is not modified in any way, because the instrumentation code is
20512 inserted by gcc during the compilation process. To compile your code with code
20513 coverage activated, you need to recompile your whole project using the
20514 switches
20515 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
20516 @code{-fprofile-arcs}.
20517
20518 @smallexample
20519 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
20520 -largs -fprofile-arcs
20521 @end smallexample
20522
20523 This compilation process will create @file{.gcno} files together with
20524 the usual object files.
20525
20526 Once the program is compiled with coverage instrumentation, you can
20527 run it as many times as needed - on portions of a test suite for
20528 example. The first execution will produce @file{.gcda} files at the
20529 same location as the @file{.gcno} files. The following executions
20530 will update those files, so that a cumulative result of the covered
20531 portions of the program is generated.
20532
20533 Finally, you need to call the @code{gcov} tool. The different options of
20534 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
20535
20536 This will create annotated source files with a @file{.gcov} extension:
20537 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
20538
20539 @node Gnat specifics
20540 @subsection Gnat specifics
20541
20542 Because Ada semantics, portions of the source code may be shared among
20543 several object files. This is the case for example when generics are
20544 involved, when inlining is active or when declarations generate initialisation
20545 calls. In order to take
20546 into account this shared code, you need to call @code{gcov} on all
20547 source files of the tested program at once.
20548
20549 The list of source files might exceed the system's maximum command line
20550 length. In order to bypass this limitation, a new mechanism has been
20551 implemented in @code{gcov}: you can now list all your project's files into a
20552 text file, and provide this file to gcov as a parameter, preceded by a @@
20553 (e.g. @samp{gcov @@mysrclist.txt}).
20554
20555 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
20556 not supported as there can be unresolved symbols during the final link.
20557
20558 @node Profiling an Ada Program with gprof
20559 @section Profiling an Ada Program with gprof
20560 @cindex gprof
20561 @cindex -pg
20562 @cindex Profiling
20563
20564 @noindent
20565 This section is not meant to be an exhaustive documentation of @code{gprof}.
20566 Full documentation for it can be found in the GNU Profiler User's Guide
20567 documentation that is part of this GNAT distribution.
20568
20569 Profiling a program helps determine the parts of a program that are executed
20570 most often, and are therefore the most time-consuming.
20571
20572 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
20573 better handle Ada programs and multitasking.
20574 It is currently supported on the following platforms
20575 @itemize @bullet
20576 @item
20577 linux x86/x86_64
20578 @item
20579 solaris sparc/sparc64/x86
20580 @item
20581 windows x86
20582 @end itemize
20583
20584 @noindent
20585 In order to profile a program using @code{gprof}, 3 steps are needed:
20586
20587 @itemize @bullet
20588 @item
20589 Code instrumentation, requiring a full recompilation of the project with the
20590 proper switches.
20591 @item
20592 Execution of the program under the analysis conditions, i.e. with the desired
20593 input.
20594 @item
20595 Analysis of the results using the @code{gprof} tool.
20596 @end itemize
20597
20598 @noindent
20599 The following sections detail the different steps, and indicate how
20600 to interpret the results:
20601 @menu
20602 * Compilation for profiling::
20603 * Program execution::
20604 * Running gprof::
20605 * Interpretation of profiling results::
20606 @end menu
20607
20608 @node Compilation for profiling
20609 @subsection Compilation for profiling
20610 @cindex -pg
20611 @cindex Profiling
20612
20613 In order to profile a program the first step is to tell the compiler
20614 to generate the necessary profiling information. The compiler switch to be used
20615 is @code{-pg}, which must be added to other compilation switches. This
20616 switch needs to be specified both during compilation and link stages, and can
20617 be specified once when using gnatmake:
20618
20619 @smallexample
20620 gnatmake -f -pg -P my_project
20621 @end smallexample
20622
20623 @noindent
20624 Note that only the objects that were compiled with the @samp{-pg} switch will
20625 be profiled; if you need to profile your whole project, use the @samp{-f}
20626 gnatmake switch to force full recompilation.
20627
20628 @node Program execution
20629 @subsection Program execution
20630
20631 @noindent
20632 Once the program has been compiled for profiling, you can run it as usual.
20633
20634 The only constraint imposed by profiling is that the program must terminate
20635 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
20636 properly analyzed.
20637
20638 Once the program completes execution, a data file called @file{gmon.out} is
20639 generated in the directory where the program was launched from. If this file
20640 already exists, it will be overwritten.
20641
20642 @node Running gprof
20643 @subsection Running gprof
20644
20645 @noindent
20646 The @code{gprof} tool is called as follow:
20647
20648 @smallexample
20649 gprof my_prog gmon.out
20650 @end smallexample
20651
20652 @noindent
20653 or simpler:
20654
20655 @smallexample
20656 gprof my_prog
20657 @end smallexample
20658
20659 @noindent
20660 The complete form of the gprof command line is the following:
20661
20662 @smallexample
20663 gprof [^switches^options^] [executable [data-file]]
20664 @end smallexample
20665
20666 @noindent
20667 @code{gprof} supports numerous ^switch^options^. The order of these
20668 ^switch^options^ does not matter. The full list of options can be found in
20669 the GNU Profiler User's Guide documentation that comes with this documentation.
20670
20671 The following is the subset of those switches that is most relevant:
20672
20673 @table @option
20674
20675 @item --demangle[=@var{style}]
20676 @itemx --no-demangle
20677 @cindex @option{--demangle} (@code{gprof})
20678 These options control whether symbol names should be demangled when
20679 printing output. The default is to demangle C++ symbols. The
20680 @code{--no-demangle} option may be used to turn off demangling. Different
20681 compilers have different mangling styles. The optional demangling style
20682 argument can be used to choose an appropriate demangling style for your
20683 compiler, in particular Ada symbols generated by GNAT can be demangled using
20684 @code{--demangle=gnat}.
20685
20686 @item -e @var{function_name}
20687 @cindex @option{-e} (@code{gprof})
20688 The @samp{-e @var{function}} option tells @code{gprof} not to print
20689 information about the function @var{function_name} (and its
20690 children@dots{}) in the call graph. The function will still be listed
20691 as a child of any functions that call it, but its index number will be
20692 shown as @samp{[not printed]}. More than one @samp{-e} option may be
20693 given; only one @var{function_name} may be indicated with each @samp{-e}
20694 option.
20695
20696 @item -E @var{function_name}
20697 @cindex @option{-E} (@code{gprof})
20698 The @code{-E @var{function}} option works like the @code{-e} option, but
20699 execution time spent in the function (and children who were not called from
20700 anywhere else), will not be used to compute the percentages-of-time for
20701 the call graph. More than one @samp{-E} option may be given; only one
20702 @var{function_name} may be indicated with each @samp{-E} option.
20703
20704 @item -f @var{function_name}
20705 @cindex @option{-f} (@code{gprof})
20706 The @samp{-f @var{function}} option causes @code{gprof} to limit the
20707 call graph to the function @var{function_name} and its children (and
20708 their children@dots{}). More than one @samp{-f} option may be given;
20709 only one @var{function_name} may be indicated with each @samp{-f}
20710 option.
20711
20712 @item -F @var{function_name}
20713 @cindex @option{-F} (@code{gprof})
20714 The @samp{-F @var{function}} option works like the @code{-f} option, but
20715 only time spent in the function and its children (and their
20716 children@dots{}) will be used to determine total-time and
20717 percentages-of-time for the call graph. More than one @samp{-F} option
20718 may be given; only one @var{function_name} may be indicated with each
20719 @samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.
20720
20721 @end table
20722
20723 @node Interpretation of profiling results
20724 @subsection Interpretation of profiling results
20725
20726 @noindent
20727
20728 The results of the profiling analysis are represented by two arrays: the
20729 'flat profile' and the 'call graph'. Full documentation of those outputs
20730 can be found in the GNU Profiler User's Guide.
20731
20732 The flat profile shows the time spent in each function of the program, and how
20733 many time it has been called. This allows you to locate easily the most
20734 time-consuming functions.
20735
20736 The call graph shows, for each subprogram, the subprograms that call it,
20737 and the subprograms that it calls. It also provides an estimate of the time
20738 spent in each of those callers/called subprograms.
20739 @end ifclear
20740
20741 @c ******************************
20742 @node Running and Debugging Ada Programs
20743 @chapter Running and Debugging Ada Programs
20744 @cindex Debugging
20745
20746 @noindent
20747 This chapter discusses how to debug Ada programs.
20748 @ifset vms
20749 It applies to GNAT on the Alpha OpenVMS platform;
20750 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
20751 since HP has implemented Ada support in the OpenVMS debugger on I64.
20752 @end ifset
20753
20754 An incorrect Ada program may be handled in three ways by the GNAT compiler:
20755
20756 @enumerate
20757 @item
20758 The illegality may be a violation of the static semantics of Ada. In
20759 that case GNAT diagnoses the constructs in the program that are illegal.
20760 It is then a straightforward matter for the user to modify those parts of
20761 the program.
20762
20763 @item
20764 The illegality may be a violation of the dynamic semantics of Ada. In
20765 that case the program compiles and executes, but may generate incorrect
20766 results, or may terminate abnormally with some exception.
20767
20768 @item
20769 When presented with a program that contains convoluted errors, GNAT
20770 itself may terminate abnormally without providing full diagnostics on
20771 the incorrect user program.
20772 @end enumerate
20773
20774 @menu
20775 * The GNAT Debugger GDB::
20776 * Running GDB::
20777 * Introduction to GDB Commands::
20778 * Using Ada Expressions::
20779 * Calling User-Defined Subprograms::
20780 * Using the Next Command in a Function::
20781 * Ada Exceptions::
20782 * Ada Tasks::
20783 * Debugging Generic Units::
20784 * Remote Debugging with gdbserver::
20785 * GNAT Abnormal Termination or Failure to Terminate::
20786 * Naming Conventions for GNAT Source Files::
20787 * Getting Internal Debugging Information::
20788 * Stack Traceback::
20789 @end menu
20790
20791 @cindex Debugger
20792 @findex gdb
20793
20794 @node The GNAT Debugger GDB
20795 @section The GNAT Debugger GDB
20796
20797 @noindent
20798 @code{GDB} is a general purpose, platform-independent debugger that
20799 can be used to debug mixed-language programs compiled with @command{gcc},
20800 and in particular is capable of debugging Ada programs compiled with
20801 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
20802 complex Ada data structures.
20803
20804 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
20805 @ifset vms
20806 located in the GNU:[DOCS] directory,
20807 @end ifset
20808 for full details on the usage of @code{GDB}, including a section on
20809 its usage on programs. This manual should be consulted for full
20810 details. The section that follows is a brief introduction to the
20811 philosophy and use of @code{GDB}.
20812
20813 When GNAT programs are compiled, the compiler optionally writes debugging
20814 information into the generated object file, including information on
20815 line numbers, and on declared types and variables. This information is
20816 separate from the generated code. It makes the object files considerably
20817 larger, but it does not add to the size of the actual executable that
20818 will be loaded into memory, and has no impact on run-time performance. The
20819 generation of debug information is triggered by the use of the
20820 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
20821 used to carry out the compilations. It is important to emphasize that
20822 the use of these options does not change the generated code.
20823
20824 The debugging information is written in standard system formats that
20825 are used by many tools, including debuggers and profilers. The format
20826 of the information is typically designed to describe C types and
20827 semantics, but GNAT implements a translation scheme which allows full
20828 details about Ada types and variables to be encoded into these
20829 standard C formats. Details of this encoding scheme may be found in
20830 the file exp_dbug.ads in the GNAT source distribution. However, the
20831 details of this encoding are, in general, of no interest to a user,
20832 since @code{GDB} automatically performs the necessary decoding.
20833
20834 When a program is bound and linked, the debugging information is
20835 collected from the object files, and stored in the executable image of
20836 the program. Again, this process significantly increases the size of
20837 the generated executable file, but it does not increase the size of
20838 the executable program itself. Furthermore, if this program is run in
20839 the normal manner, it runs exactly as if the debug information were
20840 not present, and takes no more actual memory.
20841
20842 However, if the program is run under control of @code{GDB}, the
20843 debugger is activated. The image of the program is loaded, at which
20844 point it is ready to run. If a run command is given, then the program
20845 will run exactly as it would have if @code{GDB} were not present. This
20846 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
20847 entirely non-intrusive until a breakpoint is encountered. If no
20848 breakpoint is ever hit, the program will run exactly as it would if no
20849 debugger were present. When a breakpoint is hit, @code{GDB} accesses
20850 the debugging information and can respond to user commands to inspect
20851 variables, and more generally to report on the state of execution.
20852
20853 @c **************
20854 @node Running GDB
20855 @section Running GDB
20856
20857 @noindent
20858 This section describes how to initiate the debugger.
20859 @c The above sentence is really just filler, but it was otherwise
20860 @c clumsy to get the first paragraph nonindented given the conditional
20861 @c nature of the description
20862
20863 @ifclear vms
20864 The debugger can be launched from a @code{GPS} menu or
20865 directly from the command line. The description below covers the latter use.
20866 All the commands shown can be used in the @code{GPS} debug console window,
20867 but there are usually more GUI-based ways to achieve the same effect.
20868 @end ifclear
20869
20870 The command to run @code{GDB} is
20871
20872 @smallexample
20873 $ ^gdb program^GDB PROGRAM^
20874 @end smallexample
20875
20876 @noindent
20877 where @code{^program^PROGRAM^} is the name of the executable file. This
20878 activates the debugger and results in a prompt for debugger commands.
20879 The simplest command is simply @code{run}, which causes the program to run
20880 exactly as if the debugger were not present. The following section
20881 describes some of the additional commands that can be given to @code{GDB}.
20882
20883 @c *******************************
20884 @node Introduction to GDB Commands
20885 @section Introduction to GDB Commands
20886
20887 @noindent
20888 @code{GDB} contains a large repertoire of commands. @xref{Top,,
20889 Debugging with GDB, gdb, Debugging with GDB},
20890 @ifset vms
20891 located in the GNU:[DOCS] directory,
20892 @end ifset
20893 for extensive documentation on the use
20894 of these commands, together with examples of their use. Furthermore,
20895 the command @command{help} invoked from within GDB activates a simple help
20896 facility which summarizes the available commands and their options.
20897 In this section we summarize a few of the most commonly
20898 used commands to give an idea of what @code{GDB} is about. You should create
20899 a simple program with debugging information and experiment with the use of
20900 these @code{GDB} commands on the program as you read through the
20901 following section.
20902
20903 @table @code
20904 @item set args @var{arguments}
20905 The @var{arguments} list above is a list of arguments to be passed to
20906 the program on a subsequent run command, just as though the arguments
20907 had been entered on a normal invocation of the program. The @code{set args}
20908 command is not needed if the program does not require arguments.
20909
20910 @item run
20911 The @code{run} command causes execution of the program to start from
20912 the beginning. If the program is already running, that is to say if
20913 you are currently positioned at a breakpoint, then a prompt will ask
20914 for confirmation that you want to abandon the current execution and
20915 restart.
20916
20917 @item breakpoint @var{location}
20918 The breakpoint command sets a breakpoint, that is to say a point at which
20919 execution will halt and @code{GDB} will await further
20920 commands. @var{location} is
20921 either a line number within a file, given in the format @code{file:linenumber},
20922 or it is the name of a subprogram. If you request that a breakpoint be set on
20923 a subprogram that is overloaded, a prompt will ask you to specify on which of
20924 those subprograms you want to breakpoint. You can also
20925 specify that all of them should be breakpointed. If the program is run
20926 and execution encounters the breakpoint, then the program
20927 stops and @code{GDB} signals that the breakpoint was encountered by
20928 printing the line of code before which the program is halted.
20929
20930 @item catch exception @var{name}
20931 This command causes the program execution to stop whenever exception
20932 @var{name} is raised. If @var{name} is omitted, then the execution is
20933 suspended when any exception is raised.
20934
20935 @item print @var{expression}
20936 This will print the value of the given expression. Most simple
20937 Ada expression formats are properly handled by @code{GDB}, so the expression
20938 can contain function calls, variables, operators, and attribute references.
20939
20940 @item continue
20941 Continues execution following a breakpoint, until the next breakpoint or the
20942 termination of the program.
20943
20944 @item step
20945 Executes a single line after a breakpoint. If the next statement
20946 is a subprogram call, execution continues into (the first statement of)
20947 the called subprogram.
20948
20949 @item next
20950 Executes a single line. If this line is a subprogram call, executes and
20951 returns from the call.
20952
20953 @item list
20954 Lists a few lines around the current source location. In practice, it
20955 is usually more convenient to have a separate edit window open with the
20956 relevant source file displayed. Successive applications of this command
20957 print subsequent lines. The command can be given an argument which is a
20958 line number, in which case it displays a few lines around the specified one.
20959
20960 @item backtrace
20961 Displays a backtrace of the call chain. This command is typically
20962 used after a breakpoint has occurred, to examine the sequence of calls that
20963 leads to the current breakpoint. The display includes one line for each
20964 activation record (frame) corresponding to an active subprogram.
20965
20966 @item up
20967 At a breakpoint, @code{GDB} can display the values of variables local
20968 to the current frame. The command @code{up} can be used to
20969 examine the contents of other active frames, by moving the focus up
20970 the stack, that is to say from callee to caller, one frame at a time.
20971
20972 @item down
20973 Moves the focus of @code{GDB} down from the frame currently being
20974 examined to the frame of its callee (the reverse of the previous command),
20975
20976 @item frame @var{n}
20977 Inspect the frame with the given number. The value 0 denotes the frame
20978 of the current breakpoint, that is to say the top of the call stack.
20979
20980 @end table
20981
20982 @noindent
20983 The above list is a very short introduction to the commands that
20984 @code{GDB} provides. Important additional capabilities, including conditional
20985 breakpoints, the ability to execute command sequences on a breakpoint,
20986 the ability to debug at the machine instruction level and many other
20987 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
20988 Debugging with GDB}. Note that most commands can be abbreviated
20989 (for example, c for continue, bt for backtrace).
20990
20991 @node Using Ada Expressions
20992 @section Using Ada Expressions
20993 @cindex Ada expressions
20994
20995 @noindent
20996 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
20997 extensions. The philosophy behind the design of this subset is
20998
20999 @itemize @bullet
21000 @item
21001 That @code{GDB} should provide basic literals and access to operations for
21002 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
21003 leaving more sophisticated computations to subprograms written into the
21004 program (which therefore may be called from @code{GDB}).
21005
21006 @item
21007 That type safety and strict adherence to Ada language restrictions
21008 are not particularly important to the @code{GDB} user.
21009
21010 @item
21011 That brevity is important to the @code{GDB} user.
21012 @end itemize
21013
21014 @noindent
21015 Thus, for brevity, the debugger acts as if there were
21016 implicit @code{with} and @code{use} clauses in effect for all user-written
21017 packages, thus making it unnecessary to fully qualify most names with
21018 their packages, regardless of context. Where this causes ambiguity,
21019 @code{GDB} asks the user's intent.
21020
21021 For details on the supported Ada syntax, see @ref{Top,, Debugging with
21022 GDB, gdb, Debugging with GDB}.
21023
21024 @node Calling User-Defined Subprograms
21025 @section Calling User-Defined Subprograms
21026
21027 @noindent
21028 An important capability of @code{GDB} is the ability to call user-defined
21029 subprograms while debugging. This is achieved simply by entering
21030 a subprogram call statement in the form:
21031
21032 @smallexample
21033 call subprogram-name (parameters)
21034 @end smallexample
21035
21036 @noindent
21037 The keyword @code{call} can be omitted in the normal case where the
21038 @code{subprogram-name} does not coincide with any of the predefined
21039 @code{GDB} commands.
21040
21041 The effect is to invoke the given subprogram, passing it the
21042 list of parameters that is supplied. The parameters can be expressions and
21043 can include variables from the program being debugged. The
21044 subprogram must be defined
21045 at the library level within your program, and @code{GDB} will call the
21046 subprogram within the environment of your program execution (which
21047 means that the subprogram is free to access or even modify variables
21048 within your program).
21049
21050 The most important use of this facility is in allowing the inclusion of
21051 debugging routines that are tailored to particular data structures
21052 in your program. Such debugging routines can be written to provide a suitably
21053 high-level description of an abstract type, rather than a low-level dump
21054 of its physical layout. After all, the standard
21055 @code{GDB print} command only knows the physical layout of your
21056 types, not their abstract meaning. Debugging routines can provide information
21057 at the desired semantic level and are thus enormously useful.
21058
21059 For example, when debugging GNAT itself, it is crucial to have access to
21060 the contents of the tree nodes used to represent the program internally.
21061 But tree nodes are represented simply by an integer value (which in turn
21062 is an index into a table of nodes).
21063 Using the @code{print} command on a tree node would simply print this integer
21064 value, which is not very useful. But the PN routine (defined in file
21065 treepr.adb in the GNAT sources) takes a tree node as input, and displays
21066 a useful high level representation of the tree node, which includes the
21067 syntactic category of the node, its position in the source, the integers
21068 that denote descendant nodes and parent node, as well as varied
21069 semantic information. To study this example in more detail, you might want to
21070 look at the body of the PN procedure in the stated file.
21071
21072 @node Using the Next Command in a Function
21073 @section Using the Next Command in a Function
21074
21075 @noindent
21076 When you use the @code{next} command in a function, the current source
21077 location will advance to the next statement as usual. A special case
21078 arises in the case of a @code{return} statement.
21079
21080 Part of the code for a return statement is the ``epilog'' of the function.
21081 This is the code that returns to the caller. There is only one copy of
21082 this epilog code, and it is typically associated with the last return
21083 statement in the function if there is more than one return. In some
21084 implementations, this epilog is associated with the first statement
21085 of the function.
21086
21087 The result is that if you use the @code{next} command from a return
21088 statement that is not the last return statement of the function you
21089 may see a strange apparent jump to the last return statement or to
21090 the start of the function. You should simply ignore this odd jump.
21091 The value returned is always that from the first return statement
21092 that was stepped through.
21093
21094 @node Ada Exceptions
21095 @section Stopping when Ada Exceptions are Raised
21096 @cindex Exceptions
21097
21098 @noindent
21099 You can set catchpoints that stop the program execution when your program
21100 raises selected exceptions.
21101
21102 @table @code
21103 @item catch exception
21104 Set a catchpoint that stops execution whenever (any task in the) program
21105 raises any exception.
21106
21107 @item catch exception @var{name}
21108 Set a catchpoint that stops execution whenever (any task in the) program
21109 raises the exception @var{name}.
21110
21111 @item catch exception unhandled
21112 Set a catchpoint that stops executing whenever (any task in the) program
21113 raises an exception for which there is no handler.
21114
21115 @item info exceptions
21116 @itemx info exceptions @var{regexp}
21117 The @code{info exceptions} command permits the user to examine all defined
21118 exceptions within Ada programs. With a regular expression, @var{regexp}, as
21119 argument, prints out only those exceptions whose name matches @var{regexp}.
21120 @end table
21121
21122 @node Ada Tasks
21123 @section Ada Tasks
21124 @cindex Tasks
21125
21126 @noindent
21127 @code{GDB} allows the following task-related commands:
21128
21129 @table @code
21130 @item info tasks
21131 This command shows a list of current Ada tasks, as in the following example:
21132
21133 @smallexample
21134 @iftex
21135 @leftskip=0cm
21136 @end iftex
21137 (gdb) info tasks
21138 ID TID P-ID Thread Pri State Name
21139 1 8088000 0 807e000 15 Child Activation Wait main_task
21140 2 80a4000 1 80ae000 15 Accept/Select Wait b
21141 3 809a800 1 80a4800 15 Child Activation Wait a
21142 * 4 80ae800 3 80b8000 15 Running c
21143 @end smallexample
21144
21145 @noindent
21146 In this listing, the asterisk before the first task indicates it to be the
21147 currently running task. The first column lists the task ID that is used
21148 to refer to tasks in the following commands.
21149
21150 @item break @var{linespec} task @var{taskid}
21151 @itemx break @var{linespec} task @var{taskid} if @dots{}
21152 @cindex Breakpoints and tasks
21153 These commands are like the @code{break @dots{} thread @dots{}}.
21154 @var{linespec} specifies source lines.
21155
21156 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
21157 to specify that you only want @code{GDB} to stop the program when a
21158 particular Ada task reaches this breakpoint. @var{taskid} is one of the
21159 numeric task identifiers assigned by @code{GDB}, shown in the first
21160 column of the @samp{info tasks} display.
21161
21162 If you do not specify @samp{task @var{taskid}} when you set a
21163 breakpoint, the breakpoint applies to @emph{all} tasks of your
21164 program.
21165
21166 You can use the @code{task} qualifier on conditional breakpoints as
21167 well; in this case, place @samp{task @var{taskid}} before the
21168 breakpoint condition (before the @code{if}).
21169
21170 @item task @var{taskno}
21171 @cindex Task switching
21172
21173 This command allows to switch to the task referred by @var{taskno}. In
21174 particular, This allows to browse the backtrace of the specified
21175 task. It is advised to switch back to the original task before
21176 continuing execution otherwise the scheduling of the program may be
21177 perturbed.
21178 @end table
21179
21180 @noindent
21181 For more detailed information on the tasking support,
21182 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
21183
21184 @node Debugging Generic Units
21185 @section Debugging Generic Units
21186 @cindex Debugging Generic Units
21187 @cindex Generics
21188
21189 @noindent
21190 GNAT always uses code expansion for generic instantiation. This means that
21191 each time an instantiation occurs, a complete copy of the original code is
21192 made, with appropriate substitutions of formals by actuals.
21193
21194 It is not possible to refer to the original generic entities in
21195 @code{GDB}, but it is always possible to debug a particular instance of
21196 a generic, by using the appropriate expanded names. For example, if we have
21197
21198 @smallexample @c ada
21199 @group
21200 @cartouche
21201 procedure g is
21202
21203 generic package k is
21204 procedure kp (v1 : in out integer);
21205 end k;
21206
21207 package body k is
21208 procedure kp (v1 : in out integer) is
21209 begin
21210 v1 := v1 + 1;
21211 end kp;
21212 end k;
21213
21214 package k1 is new k;
21215 package k2 is new k;
21216
21217 var : integer := 1;
21218
21219 begin
21220 k1.kp (var);
21221 k2.kp (var);
21222 k1.kp (var);
21223 k2.kp (var);
21224 end;
21225 @end cartouche
21226 @end group
21227 @end smallexample
21228
21229 @noindent
21230 Then to break on a call to procedure kp in the k2 instance, simply
21231 use the command:
21232
21233 @smallexample
21234 (gdb) break g.k2.kp
21235 @end smallexample
21236
21237 @noindent
21238 When the breakpoint occurs, you can step through the code of the
21239 instance in the normal manner and examine the values of local variables, as for
21240 other units.
21241
21242 @node Remote Debugging with gdbserver
21243 @section Remote Debugging with gdbserver
21244 @cindex Remote Debugging with gdbserver
21245
21246 @noindent
21247 On platforms where gdbserver is supported, it is possible to use this tool
21248 to debug your application remotely. This can be useful in situations
21249 where the program needs to be run on a target host that is different
21250 from the host used for development, particularly when the target has
21251 a limited amount of resources (either CPU and/or memory).
21252
21253 To do so, start your program using gdbserver on the target machine.
21254 gdbserver then automatically suspends the execution of your program
21255 at its entry point, waiting for a debugger to connect to it. The
21256 following commands starts an application and tells gdbserver to
21257 wait for a connection with the debugger on localhost port 4444.
21258
21259 @smallexample
21260 $ gdbserver localhost:4444 program
21261 Process program created; pid = 5685
21262 Listening on port 4444
21263 @end smallexample
21264
21265 Once gdbserver has started listening, we can tell the debugger to establish
21266 a connection with this gdbserver, and then start the same debugging session
21267 as if the program was being debugged on the same host, directly under
21268 the control of GDB.
21269
21270 @smallexample
21271 $ gdb program
21272 (gdb) target remote targethost:4444
21273 Remote debugging using targethost:4444
21274 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
21275 (gdb) b foo.adb:3
21276 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
21277 (gdb) continue
21278 Continuing.
21279
21280 Breakpoint 1, foo () at foo.adb:4
21281 4 end foo;
21282 @end smallexample
21283
21284 It is also possible to use gdbserver to attach to an already running
21285 program, in which case the execution of that program is simply suspended
21286 until the connection between the debugger and gdbserver is established.
21287
21288 For more information on how to use gdbserver, @ref{Top, Server, Using
21289 the gdbserver Program, gdb, Debugging with GDB}. @value{EDITION} provides support
21290 for gdbserver on x86-linux, x86-windows and x86_64-linux.
21291
21292 @node GNAT Abnormal Termination or Failure to Terminate
21293 @section GNAT Abnormal Termination or Failure to Terminate
21294 @cindex GNAT Abnormal Termination or Failure to Terminate
21295
21296 @noindent
21297 When presented with programs that contain serious errors in syntax
21298 or semantics,
21299 GNAT may on rare occasions experience problems in operation, such
21300 as aborting with a
21301 segmentation fault or illegal memory access, raising an internal
21302 exception, terminating abnormally, or failing to terminate at all.
21303 In such cases, you can activate
21304 various features of GNAT that can help you pinpoint the construct in your
21305 program that is the likely source of the problem.
21306
21307 The following strategies are presented in increasing order of
21308 difficulty, corresponding to your experience in using GNAT and your
21309 familiarity with compiler internals.
21310
21311 @enumerate
21312 @item
21313 Run @command{gcc} with the @option{-gnatf}. This first
21314 switch causes all errors on a given line to be reported. In its absence,
21315 only the first error on a line is displayed.
21316
21317 The @option{-gnatdO} switch causes errors to be displayed as soon as they
21318 are encountered, rather than after compilation is terminated. If GNAT
21319 terminates prematurely or goes into an infinite loop, the last error
21320 message displayed may help to pinpoint the culprit.
21321
21322 @item
21323 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
21324 mode, @command{gcc} produces ongoing information about the progress of the
21325 compilation and provides the name of each procedure as code is
21326 generated. This switch allows you to find which Ada procedure was being
21327 compiled when it encountered a code generation problem.
21328
21329 @item
21330 @cindex @option{-gnatdc} switch
21331 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
21332 switch that does for the front-end what @option{^-v^VERBOSE^} does
21333 for the back end. The system prints the name of each unit,
21334 either a compilation unit or nested unit, as it is being analyzed.
21335 @item
21336 Finally, you can start
21337 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
21338 front-end of GNAT, and can be run independently (normally it is just
21339 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
21340 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
21341 @code{where} command is the first line of attack; the variable
21342 @code{lineno} (seen by @code{print lineno}), used by the second phase of
21343 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
21344 which the execution stopped, and @code{input_file name} indicates the name of
21345 the source file.
21346 @end enumerate
21347
21348 @node Naming Conventions for GNAT Source Files
21349 @section Naming Conventions for GNAT Source Files
21350
21351 @noindent
21352 In order to examine the workings of the GNAT system, the following
21353 brief description of its organization may be helpful:
21354
21355 @itemize @bullet
21356 @item
21357 Files with prefix @file{^sc^SC^} contain the lexical scanner.
21358
21359 @item
21360 All files prefixed with @file{^par^PAR^} are components of the parser. The
21361 numbers correspond to chapters of the Ada Reference Manual. For example,
21362 parsing of select statements can be found in @file{par-ch9.adb}.
21363
21364 @item
21365 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
21366 numbers correspond to chapters of the Ada standard. For example, all
21367 issues involving context clauses can be found in @file{sem_ch10.adb}. In
21368 addition, some features of the language require sufficient special processing
21369 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
21370 dynamic dispatching, etc.
21371
21372 @item
21373 All files prefixed with @file{^exp^EXP^} perform normalization and
21374 expansion of the intermediate representation (abstract syntax tree, or AST).
21375 these files use the same numbering scheme as the parser and semantics files.
21376 For example, the construction of record initialization procedures is done in
21377 @file{exp_ch3.adb}.
21378
21379 @item
21380 The files prefixed with @file{^bind^BIND^} implement the binder, which
21381 verifies the consistency of the compilation, determines an order of
21382 elaboration, and generates the bind file.
21383
21384 @item
21385 The files @file{atree.ads} and @file{atree.adb} detail the low-level
21386 data structures used by the front-end.
21387
21388 @item
21389 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
21390 the abstract syntax tree as produced by the parser.
21391
21392 @item
21393 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
21394 all entities, computed during semantic analysis.
21395
21396 @item
21397 Library management issues are dealt with in files with prefix
21398 @file{^lib^LIB^}.
21399
21400 @item
21401 @findex Ada
21402 @cindex Annex A
21403 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
21404 defined in Annex A.
21405
21406 @item
21407 @findex Interfaces
21408 @cindex Annex B
21409 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
21410 defined in Annex B.
21411
21412 @item
21413 @findex System
21414 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
21415 both language-defined children and GNAT run-time routines.
21416
21417 @item
21418 @findex GNAT
21419 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
21420 general-purpose packages, fully documented in their specs. All
21421 the other @file{.c} files are modifications of common @command{gcc} files.
21422 @end itemize
21423
21424 @node Getting Internal Debugging Information
21425 @section Getting Internal Debugging Information
21426
21427 @noindent
21428 Most compilers have internal debugging switches and modes. GNAT
21429 does also, except GNAT internal debugging switches and modes are not
21430 secret. A summary and full description of all the compiler and binder
21431 debug flags are in the file @file{debug.adb}. You must obtain the
21432 sources of the compiler to see the full detailed effects of these flags.
21433
21434 The switches that print the source of the program (reconstructed from
21435 the internal tree) are of general interest for user programs, as are the
21436 options to print
21437 the full internal tree, and the entity table (the symbol table
21438 information). The reconstructed source provides a readable version of the
21439 program after the front-end has completed analysis and expansion,
21440 and is useful when studying the performance of specific constructs.
21441 For example, constraint checks are indicated, complex aggregates
21442 are replaced with loops and assignments, and tasking primitives
21443 are replaced with run-time calls.
21444
21445 @node Stack Traceback
21446 @section Stack Traceback
21447 @cindex traceback
21448 @cindex stack traceback
21449 @cindex stack unwinding
21450
21451 @noindent
21452 Traceback is a mechanism to display the sequence of subprogram calls that
21453 leads to a specified execution point in a program. Often (but not always)
21454 the execution point is an instruction at which an exception has been raised.
21455 This mechanism is also known as @i{stack unwinding} because it obtains
21456 its information by scanning the run-time stack and recovering the activation
21457 records of all active subprograms. Stack unwinding is one of the most
21458 important tools for program debugging.
21459
21460 The first entry stored in traceback corresponds to the deepest calling level,
21461 that is to say the subprogram currently executing the instruction
21462 from which we want to obtain the traceback.
21463
21464 Note that there is no runtime performance penalty when stack traceback
21465 is enabled, and no exception is raised during program execution.
21466
21467 @menu
21468 * Non-Symbolic Traceback::
21469 * Symbolic Traceback::
21470 @end menu
21471
21472 @node Non-Symbolic Traceback
21473 @subsection Non-Symbolic Traceback
21474 @cindex traceback, non-symbolic
21475
21476 @noindent
21477 Note: this feature is not supported on all platforms. See
21478 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
21479 platforms.
21480
21481 @menu
21482 * Tracebacks From an Unhandled Exception::
21483 * Tracebacks From Exception Occurrences (non-symbolic)::
21484 * Tracebacks From Anywhere in a Program (non-symbolic)::
21485 @end menu
21486
21487 @node Tracebacks From an Unhandled Exception
21488 @subsubsection Tracebacks From an Unhandled Exception
21489
21490 @noindent
21491 A runtime non-symbolic traceback is a list of addresses of call instructions.
21492 To enable this feature you must use the @option{-E}
21493 @code{gnatbind}'s option. With this option a stack traceback is stored as part
21494 of exception information. You can retrieve this information using the
21495 @code{addr2line} tool.
21496
21497 Here is a simple example:
21498
21499 @smallexample @c ada
21500 @cartouche
21501 procedure STB is
21502
21503 procedure P1 is
21504 begin
21505 raise Constraint_Error;
21506 end P1;
21507
21508 procedure P2 is
21509 begin
21510 P1;
21511 end P2;
21512
21513 begin
21514 P2;
21515 end STB;
21516 @end cartouche
21517 @end smallexample
21518
21519 @smallexample
21520 $ gnatmake stb -bargs -E
21521 $ stb
21522
21523 Execution terminated by unhandled exception
21524 Exception name: CONSTRAINT_ERROR
21525 Message: stb.adb:5
21526 Call stack traceback locations:
21527 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21528 @end smallexample
21529
21530 @noindent
21531 As we see the traceback lists a sequence of addresses for the unhandled
21532 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
21533 guess that this exception come from procedure P1. To translate these
21534 addresses into the source lines where the calls appear, the
21535 @code{addr2line} tool, described below, is invaluable. The use of this tool
21536 requires the program to be compiled with debug information.
21537
21538 @smallexample
21539 $ gnatmake -g stb -bargs -E
21540 $ stb
21541
21542 Execution terminated by unhandled exception
21543 Exception name: CONSTRAINT_ERROR
21544 Message: stb.adb:5
21545 Call stack traceback locations:
21546 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21547
21548 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
21549 0x4011f1 0x77e892a4
21550
21551 00401373 at d:/stb/stb.adb:5
21552 0040138B at d:/stb/stb.adb:10
21553 0040139C at d:/stb/stb.adb:14
21554 00401335 at d:/stb/b~stb.adb:104
21555 004011C4 at /build/@dots{}/crt1.c:200
21556 004011F1 at /build/@dots{}/crt1.c:222
21557 77E892A4 in ?? at ??:0
21558 @end smallexample
21559
21560 @noindent
21561 The @code{addr2line} tool has several other useful options:
21562
21563 @table @code
21564 @item --functions
21565 to get the function name corresponding to any location
21566
21567 @item --demangle=gnat
21568 to use the gnat decoding mode for the function names. Note that
21569 for binutils version 2.9.x the option is simply @option{--demangle}.
21570 @end table
21571
21572 @smallexample
21573 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
21574 0x40139c 0x401335 0x4011c4 0x4011f1
21575
21576 00401373 in stb.p1 at d:/stb/stb.adb:5
21577 0040138B in stb.p2 at d:/stb/stb.adb:10
21578 0040139C in stb at d:/stb/stb.adb:14
21579 00401335 in main at d:/stb/b~stb.adb:104
21580 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
21581 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
21582 @end smallexample
21583
21584 @noindent
21585 From this traceback we can see that the exception was raised in
21586 @file{stb.adb} at line 5, which was reached from a procedure call in
21587 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
21588 which contains the call to the main program.
21589 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
21590 and the output will vary from platform to platform.
21591
21592 It is also possible to use @code{GDB} with these traceback addresses to debug
21593 the program. For example, we can break at a given code location, as reported
21594 in the stack traceback:
21595
21596 @smallexample
21597 $ gdb -nw stb
21598 @ifclear vms
21599 @noindent
21600 Furthermore, this feature is not implemented inside Windows DLL. Only
21601 the non-symbolic traceback is reported in this case.
21602 @end ifclear
21603
21604 (gdb) break *0x401373
21605 Breakpoint 1 at 0x401373: file stb.adb, line 5.
21606 @end smallexample
21607
21608 @noindent
21609 It is important to note that the stack traceback addresses
21610 do not change when debug information is included. This is particularly useful
21611 because it makes it possible to release software without debug information (to
21612 minimize object size), get a field report that includes a stack traceback
21613 whenever an internal bug occurs, and then be able to retrieve the sequence
21614 of calls with the same program compiled with debug information.
21615
21616 @node Tracebacks From Exception Occurrences (non-symbolic)
21617 @subsubsection Tracebacks From Exception Occurrences
21618
21619 @noindent
21620 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
21621 The stack traceback is attached to the exception information string, and can
21622 be retrieved in an exception handler within the Ada program, by means of the
21623 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
21624
21625 @smallexample @c ada
21626 with Ada.Text_IO;
21627 with Ada.Exceptions;
21628
21629 procedure STB is
21630
21631 use Ada;
21632 use Ada.Exceptions;
21633
21634 procedure P1 is
21635 K : Positive := 1;
21636 begin
21637 K := K - 1;
21638 exception
21639 when E : others =>
21640 Text_IO.Put_Line (Exception_Information (E));
21641 end P1;
21642
21643 procedure P2 is
21644 begin
21645 P1;
21646 end P2;
21647
21648 begin
21649 P2;
21650 end STB;
21651 @end smallexample
21652
21653 @noindent
21654 This program will output:
21655
21656 @smallexample
21657 $ stb
21658
21659 Exception name: CONSTRAINT_ERROR
21660 Message: stb.adb:12
21661 Call stack traceback locations:
21662 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
21663 @end smallexample
21664
21665 @node Tracebacks From Anywhere in a Program (non-symbolic)
21666 @subsubsection Tracebacks From Anywhere in a Program
21667
21668 @noindent
21669 It is also possible to retrieve a stack traceback from anywhere in a
21670 program. For this you need to
21671 use the @code{GNAT.Traceback} API. This package includes a procedure called
21672 @code{Call_Chain} that computes a complete stack traceback, as well as useful
21673 display procedures described below. It is not necessary to use the
21674 @option{-E gnatbind} option in this case, because the stack traceback mechanism
21675 is invoked explicitly.
21676
21677 @noindent
21678 In the following example we compute a traceback at a specific location in
21679 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
21680 convert addresses to strings:
21681
21682 @smallexample @c ada
21683 with Ada.Text_IO;
21684 with GNAT.Traceback;
21685 with GNAT.Debug_Utilities;
21686
21687 procedure STB is
21688
21689 use Ada;
21690 use GNAT;
21691 use GNAT.Traceback;
21692
21693 procedure P1 is
21694 TB : Tracebacks_Array (1 .. 10);
21695 -- We are asking for a maximum of 10 stack frames.
21696 Len : Natural;
21697 -- Len will receive the actual number of stack frames returned.
21698 begin
21699 Call_Chain (TB, Len);
21700
21701 Text_IO.Put ("In STB.P1 : ");
21702
21703 for K in 1 .. Len loop
21704 Text_IO.Put (Debug_Utilities.Image (TB (K)));
21705 Text_IO.Put (' ');
21706 end loop;
21707
21708 Text_IO.New_Line;
21709 end P1;
21710
21711 procedure P2 is
21712 begin
21713 P1;
21714 end P2;
21715
21716 begin
21717 P2;
21718 end STB;
21719 @end smallexample
21720
21721 @smallexample
21722 $ gnatmake -g stb
21723 $ stb
21724
21725 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
21726 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
21727 @end smallexample
21728
21729 @noindent
21730 You can then get further information by invoking the @code{addr2line}
21731 tool as described earlier (note that the hexadecimal addresses
21732 need to be specified in C format, with a leading ``0x'').
21733
21734 @node Symbolic Traceback
21735 @subsection Symbolic Traceback
21736 @cindex traceback, symbolic
21737
21738 @noindent
21739 A symbolic traceback is a stack traceback in which procedure names are
21740 associated with each code location.
21741
21742 @noindent
21743 Note that this feature is not supported on all platforms. See
21744 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
21745 list of currently supported platforms.
21746
21747 @noindent
21748 Note that the symbolic traceback requires that the program be compiled
21749 with debug information. If it is not compiled with debug information
21750 only the non-symbolic information will be valid.
21751
21752 @menu
21753 * Tracebacks From Exception Occurrences (symbolic)::
21754 * Tracebacks From Anywhere in a Program (symbolic)::
21755 @end menu
21756
21757 @node Tracebacks From Exception Occurrences (symbolic)
21758 @subsubsection Tracebacks From Exception Occurrences
21759
21760 @smallexample @c ada
21761 with Ada.Text_IO;
21762 with GNAT.Traceback.Symbolic;
21763
21764 procedure STB is
21765
21766 procedure P1 is
21767 begin
21768 raise Constraint_Error;
21769 end P1;
21770
21771 procedure P2 is
21772 begin
21773 P1;
21774 end P2;
21775
21776 procedure P3 is
21777 begin
21778 P2;
21779 end P3;
21780
21781 begin
21782 P3;
21783 exception
21784 when E : others =>
21785 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
21786 end STB;
21787 @end smallexample
21788
21789 @smallexample
21790 $ gnatmake -g .\stb -bargs -E
21791 $ stb
21792
21793 0040149F in stb.p1 at stb.adb:8
21794 004014B7 in stb.p2 at stb.adb:13
21795 004014CF in stb.p3 at stb.adb:18
21796 004015DD in ada.stb at stb.adb:22
21797 00401461 in main at b~stb.adb:168
21798 004011C4 in __mingw_CRTStartup at crt1.c:200
21799 004011F1 in mainCRTStartup at crt1.c:222
21800 77E892A4 in ?? at ??:0
21801 @end smallexample
21802
21803 @noindent
21804 In the above example the ``.\'' syntax in the @command{gnatmake} command
21805 is currently required by @command{addr2line} for files that are in
21806 the current working directory.
21807 Moreover, the exact sequence of linker options may vary from platform
21808 to platform.
21809 The above @option{-largs} section is for Windows platforms. By contrast,
21810 under Unix there is no need for the @option{-largs} section.
21811 Differences across platforms are due to details of linker implementation.
21812
21813 @node Tracebacks From Anywhere in a Program (symbolic)
21814 @subsubsection Tracebacks From Anywhere in a Program
21815
21816 @noindent
21817 It is possible to get a symbolic stack traceback
21818 from anywhere in a program, just as for non-symbolic tracebacks.
21819 The first step is to obtain a non-symbolic
21820 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
21821 information. Here is an example:
21822
21823 @smallexample @c ada
21824 with Ada.Text_IO;
21825 with GNAT.Traceback;
21826 with GNAT.Traceback.Symbolic;
21827
21828 procedure STB is
21829
21830 use Ada;
21831 use GNAT.Traceback;
21832 use GNAT.Traceback.Symbolic;
21833
21834 procedure P1 is
21835 TB : Tracebacks_Array (1 .. 10);
21836 -- We are asking for a maximum of 10 stack frames.
21837 Len : Natural;
21838 -- Len will receive the actual number of stack frames returned.
21839 begin
21840 Call_Chain (TB, Len);
21841 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
21842 end P1;
21843
21844 procedure P2 is
21845 begin
21846 P1;
21847 end P2;
21848
21849 begin
21850 P2;
21851 end STB;
21852 @end smallexample
21853
21854 @c ******************************
21855 @ifset vms
21856 @node Compatibility with HP Ada
21857 @chapter Compatibility with HP Ada
21858 @cindex Compatibility
21859
21860 @noindent
21861 @cindex DEC Ada
21862 @cindex HP Ada
21863 @cindex Compatibility between GNAT and HP Ada
21864 This chapter compares HP Ada (formerly known as ``DEC Ada'')
21865 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
21866 GNAT is highly compatible
21867 with HP Ada, and it should generally be straightforward to port code
21868 from the HP Ada environment to GNAT. However, there are a few language
21869 and implementation differences of which the user must be aware. These
21870 differences are discussed in this chapter. In
21871 addition, the operating environment and command structure for the
21872 compiler are different, and these differences are also discussed.
21873
21874 For further details on these and other compatibility issues,
21875 see Appendix E of the HP publication
21876 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
21877
21878 Except where otherwise indicated, the description of GNAT for OpenVMS
21879 applies to both the Alpha and I64 platforms.
21880
21881 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
21882 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
21883
21884 The discussion in this chapter addresses specifically the implementation
21885 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
21886 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
21887 GNAT always follows the Alpha implementation.
21888
21889 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
21890 attributes are recognized, although only a subset of them can sensibly
21891 be implemented. The description of pragmas in
21892 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
21893 indicates whether or not they are applicable to non-VMS systems.
21894
21895 @menu
21896 * Ada Language Compatibility::
21897 * Differences in the Definition of Package System::
21898 * Language-Related Features::
21899 * The Package STANDARD::
21900 * The Package SYSTEM::
21901 * Tasking and Task-Related Features::
21902 * Pragmas and Pragma-Related Features::
21903 * Library of Predefined Units::
21904 * Bindings::
21905 * Main Program Definition::
21906 * Implementation-Defined Attributes::
21907 * Compiler and Run-Time Interfacing::
21908 * Program Compilation and Library Management::
21909 * Input-Output::
21910 * Implementation Limits::
21911 * Tools and Utilities::
21912 @end menu
21913
21914 @node Ada Language Compatibility
21915 @section Ada Language Compatibility
21916
21917 @noindent
21918 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
21919 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
21920 with Ada 83, and therefore Ada 83 programs will compile
21921 and run under GNAT with
21922 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
21923 provides details on specific incompatibilities.
21924
21925 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
21926 as well as the pragma @code{ADA_83}, to force the compiler to
21927 operate in Ada 83 mode. This mode does not guarantee complete
21928 conformance to Ada 83, but in practice is sufficient to
21929 eliminate most sources of incompatibilities.
21930 In particular, it eliminates the recognition of the
21931 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
21932 in Ada 83 programs is legal, and handles the cases of packages
21933 with optional bodies, and generics that instantiate unconstrained
21934 types without the use of @code{(<>)}.
21935
21936 @node Differences in the Definition of Package System
21937 @section Differences in the Definition of Package @code{System}
21938
21939 @noindent
21940 An Ada compiler is allowed to add
21941 implementation-dependent declarations to package @code{System}.
21942 In normal mode,
21943 GNAT does not take advantage of this permission, and the version of
21944 @code{System} provided by GNAT exactly matches that defined in the Ada
21945 Reference Manual.
21946
21947 However, HP Ada adds an extensive set of declarations to package
21948 @code{System},
21949 as fully documented in the HP Ada manuals. To minimize changes required
21950 for programs that make use of these extensions, GNAT provides the pragma
21951 @code{Extend_System} for extending the definition of package System. By using:
21952 @cindex pragma @code{Extend_System}
21953 @cindex @code{Extend_System} pragma
21954
21955 @smallexample @c ada
21956 @group
21957 @cartouche
21958 pragma Extend_System (Aux_DEC);
21959 @end cartouche
21960 @end group
21961 @end smallexample
21962
21963 @noindent
21964 the set of definitions in @code{System} is extended to include those in
21965 package @code{System.Aux_DEC}.
21966 @cindex @code{System.Aux_DEC} package
21967 @cindex @code{Aux_DEC} package (child of @code{System})
21968 These definitions are incorporated directly into package @code{System},
21969 as though they had been declared there. For a
21970 list of the declarations added, see the spec of this package,
21971 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
21972 @cindex @file{s-auxdec.ads} file
21973 The pragma @code{Extend_System} is a configuration pragma, which means that
21974 it can be placed in the file @file{gnat.adc}, so that it will automatically
21975 apply to all subsequent compilations. See @ref{Configuration Pragmas},
21976 for further details.
21977
21978 An alternative approach that avoids the use of the non-standard
21979 @code{Extend_System} pragma is to add a context clause to the unit that
21980 references these facilities:
21981
21982 @smallexample @c ada
21983 @cartouche
21984 with System.Aux_DEC;
21985 use System.Aux_DEC;
21986 @end cartouche
21987 @end smallexample
21988
21989 @noindent
21990 The effect is not quite semantically identical to incorporating
21991 the declarations directly into package @code{System},
21992 but most programs will not notice a difference
21993 unless they use prefix notation (e.g.@: @code{System.Integer_8})
21994 to reference the entities directly in package @code{System}.
21995 For units containing such references,
21996 the prefixes must either be removed, or the pragma @code{Extend_System}
21997 must be used.
21998
21999 @node Language-Related Features
22000 @section Language-Related Features
22001
22002 @noindent
22003 The following sections highlight differences in types,
22004 representations of types, operations, alignment, and
22005 related topics.
22006
22007 @menu
22008 * Integer Types and Representations::
22009 * Floating-Point Types and Representations::
22010 * Pragmas Float_Representation and Long_Float::
22011 * Fixed-Point Types and Representations::
22012 * Record and Array Component Alignment::
22013 * Address Clauses::
22014 * Other Representation Clauses::
22015 @end menu
22016
22017 @node Integer Types and Representations
22018 @subsection Integer Types and Representations
22019
22020 @noindent
22021 The set of predefined integer types is identical in HP Ada and GNAT.
22022 Furthermore the representation of these integer types is also identical,
22023 including the capability of size clauses forcing biased representation.
22024
22025 In addition,
22026 HP Ada for OpenVMS Alpha systems has defined the
22027 following additional integer types in package @code{System}:
22028
22029 @itemize @bullet
22030
22031 @item
22032 @code{INTEGER_8}
22033
22034 @item
22035 @code{INTEGER_16}
22036
22037 @item
22038 @code{INTEGER_32}
22039
22040 @item
22041 @code{INTEGER_64}
22042
22043 @item
22044 @code{LARGEST_INTEGER}
22045 @end itemize
22046
22047 @noindent
22048 In GNAT, the first four of these types may be obtained from the
22049 standard Ada package @code{Interfaces}.
22050 Alternatively, by use of the pragma @code{Extend_System}, identical
22051 declarations can be referenced directly in package @code{System}.
22052 On both GNAT and HP Ada, the maximum integer size is 64 bits.
22053
22054 @node Floating-Point Types and Representations
22055 @subsection Floating-Point Types and Representations
22056 @cindex Floating-Point types
22057
22058 @noindent
22059 The set of predefined floating-point types is identical in HP Ada and GNAT.
22060 Furthermore the representation of these floating-point
22061 types is also identical. One important difference is that the default
22062 representation for HP Ada is @code{VAX_Float}, but the default representation
22063 for GNAT is IEEE.
22064
22065 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
22066 pragma @code{Float_Representation} as described in the HP Ada
22067 documentation.
22068 For example, the declarations:
22069
22070 @smallexample @c ada
22071 @cartouche
22072 type F_Float is digits 6;
22073 pragma Float_Representation (VAX_Float, F_Float);
22074 @end cartouche
22075 @end smallexample
22076
22077 @noindent
22078 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
22079 format.
22080 This set of declarations actually appears in @code{System.Aux_DEC},
22081 which contains
22082 the full set of additional floating-point declarations provided in
22083 the HP Ada version of package @code{System}.
22084 This and similar declarations may be accessed in a user program
22085 by using pragma @code{Extend_System}. The use of this
22086 pragma, and the related pragma @code{Long_Float} is described in further
22087 detail in the following section.
22088
22089 @node Pragmas Float_Representation and Long_Float
22090 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
22091
22092 @noindent
22093 HP Ada provides the pragma @code{Float_Representation}, which
22094 acts as a program library switch to allow control over
22095 the internal representation chosen for the predefined
22096 floating-point types declared in the package @code{Standard}.
22097 The format of this pragma is as follows:
22098
22099 @smallexample @c ada
22100 @cartouche
22101 pragma Float_Representation(VAX_Float | IEEE_Float);
22102 @end cartouche
22103 @end smallexample
22104
22105 @noindent
22106 This pragma controls the representation of floating-point
22107 types as follows:
22108
22109 @itemize @bullet
22110 @item
22111 @code{VAX_Float} specifies that floating-point
22112 types are represented by default with the VAX system hardware types
22113 @code{F-floating}, @code{D-floating}, @code{G-floating}.
22114 Note that the @code{H-floating}
22115 type was available only on VAX systems, and is not available
22116 in either HP Ada or GNAT.
22117
22118 @item
22119 @code{IEEE_Float} specifies that floating-point
22120 types are represented by default with the IEEE single and
22121 double floating-point types.
22122 @end itemize
22123
22124 @noindent
22125 GNAT provides an identical implementation of the pragma
22126 @code{Float_Representation}, except that it functions as a
22127 configuration pragma. Note that the
22128 notion of configuration pragma corresponds closely to the
22129 HP Ada notion of a program library switch.
22130
22131 When no pragma is used in GNAT, the default is @code{IEEE_Float},
22132 which is different
22133 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
22134 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
22135 advisable to change the format of numbers passed to standard library
22136 routines, and if necessary explicit type conversions may be needed.
22137
22138 The use of @code{IEEE_Float} is recommended in GNAT since it is more
22139 efficient, and (given that it conforms to an international standard)
22140 potentially more portable.
22141 The situation in which @code{VAX_Float} may be useful is in interfacing
22142 to existing code and data that expect the use of @code{VAX_Float}.
22143 In such a situation use the predefined @code{VAX_Float}
22144 types in package @code{System}, as extended by
22145 @code{Extend_System}. For example, use @code{System.F_Float}
22146 to specify the 32-bit @code{F-Float} format.
22147
22148 @noindent
22149 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
22150 to allow control over the internal representation chosen
22151 for the predefined type @code{Long_Float} and for floating-point
22152 type declarations with digits specified in the range 7 .. 15.
22153 The format of this pragma is as follows:
22154
22155 @smallexample @c ada
22156 @cartouche
22157 pragma Long_Float (D_FLOAT | G_FLOAT);
22158 @end cartouche
22159 @end smallexample
22160
22161 @node Fixed-Point Types and Representations
22162 @subsection Fixed-Point Types and Representations
22163
22164 @noindent
22165 On HP Ada for OpenVMS Alpha systems, rounding is
22166 away from zero for both positive and negative numbers.
22167 Therefore, @code{+0.5} rounds to @code{1},
22168 and @code{-0.5} rounds to @code{-1}.
22169
22170 On GNAT the results of operations
22171 on fixed-point types are in accordance with the Ada
22172 rules. In particular, results of operations on decimal
22173 fixed-point types are truncated.
22174
22175 @node Record and Array Component Alignment
22176 @subsection Record and Array Component Alignment
22177
22178 @noindent
22179 On HP Ada for OpenVMS Alpha, all non-composite components
22180 are aligned on natural boundaries. For example, 1-byte
22181 components are aligned on byte boundaries, 2-byte
22182 components on 2-byte boundaries, 4-byte components on 4-byte
22183 byte boundaries, and so on. The OpenVMS Alpha hardware
22184 runs more efficiently with naturally aligned data.
22185
22186 On GNAT, alignment rules are compatible
22187 with HP Ada for OpenVMS Alpha.
22188
22189 @node Address Clauses
22190 @subsection Address Clauses
22191
22192 @noindent
22193 In HP Ada and GNAT, address clauses are supported for
22194 objects and imported subprograms.
22195 The predefined type @code{System.Address} is a private type
22196 in both compilers on Alpha OpenVMS, with the same representation
22197 (it is simply a machine pointer). Addition, subtraction, and comparison
22198 operations are available in the standard Ada package
22199 @code{System.Storage_Elements}, or in package @code{System}
22200 if it is extended to include @code{System.Aux_DEC} using a
22201 pragma @code{Extend_System} as previously described.
22202
22203 Note that code that @code{with}'s both this extended package @code{System}
22204 and the package @code{System.Storage_Elements} should not @code{use}
22205 both packages, or ambiguities will result. In general it is better
22206 not to mix these two sets of facilities. The Ada package was
22207 designed specifically to provide the kind of features that HP Ada
22208 adds directly to package @code{System}.
22209
22210 The type @code{System.Address} is a 64-bit integer type in GNAT for
22211 I64 OpenVMS. For more information,
22212 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22213
22214 GNAT is compatible with HP Ada in its handling of address
22215 clauses, except for some limitations in
22216 the form of address clauses for composite objects with
22217 initialization. Such address clauses are easily replaced
22218 by the use of an explicitly-defined constant as described
22219 in the Ada Reference Manual (13.1(22)). For example, the sequence
22220 of declarations:
22221
22222 @smallexample @c ada
22223 @cartouche
22224 X, Y : Integer := Init_Func;
22225 Q : String (X .. Y) := "abc";
22226 @dots{}
22227 for Q'Address use Compute_Address;
22228 @end cartouche
22229 @end smallexample
22230
22231 @noindent
22232 will be rejected by GNAT, since the address cannot be computed at the time
22233 that @code{Q} is declared. To achieve the intended effect, write instead:
22234
22235 @smallexample @c ada
22236 @group
22237 @cartouche
22238 X, Y : Integer := Init_Func;
22239 Q_Address : constant Address := Compute_Address;
22240 Q : String (X .. Y) := "abc";
22241 @dots{}
22242 for Q'Address use Q_Address;
22243 @end cartouche
22244 @end group
22245 @end smallexample
22246
22247 @noindent
22248 which will be accepted by GNAT (and other Ada compilers), and is also
22249 compatible with Ada 83. A fuller description of the restrictions
22250 on address specifications is found in @ref{Top, GNAT Reference Manual,
22251 About This Guide, gnat_rm, GNAT Reference Manual}.
22252
22253 @node Other Representation Clauses
22254 @subsection Other Representation Clauses
22255
22256 @noindent
22257 GNAT implements in a compatible manner all the representation
22258 clauses supported by HP Ada. In addition, GNAT
22259 implements the representation clause forms that were introduced in Ada 95,
22260 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
22261
22262 @node The Package STANDARD
22263 @section The Package @code{STANDARD}
22264
22265 @noindent
22266 The package @code{STANDARD}, as implemented by HP Ada, is fully
22267 described in the @cite{Ada Reference Manual} and in the
22268 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
22269 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
22270
22271 In addition, HP Ada supports the Latin-1 character set in
22272 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
22273 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
22274 the type @code{WIDE_CHARACTER}.
22275
22276 The floating-point types supported by GNAT are those
22277 supported by HP Ada, but the defaults are different, and are controlled by
22278 pragmas. See @ref{Floating-Point Types and Representations}, for details.
22279
22280 @node The Package SYSTEM
22281 @section The Package @code{SYSTEM}
22282
22283 @noindent
22284 HP Ada provides a specific version of the package
22285 @code{SYSTEM} for each platform on which the language is implemented.
22286 For the complete spec of the package @code{SYSTEM}, see
22287 Appendix F of the @cite{HP Ada Language Reference Manual}.
22288
22289 On HP Ada, the package @code{SYSTEM} includes the following conversion
22290 functions:
22291 @itemize @bullet
22292 @item @code{TO_ADDRESS(INTEGER)}
22293
22294 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
22295
22296 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
22297
22298 @item @code{TO_INTEGER(ADDRESS)}
22299
22300 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
22301
22302 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
22303 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
22304 @end itemize
22305
22306 @noindent
22307 By default, GNAT supplies a version of @code{SYSTEM} that matches
22308 the definition given in the @cite{Ada Reference Manual}.
22309 This
22310 is a subset of the HP system definitions, which is as
22311 close as possible to the original definitions. The only difference
22312 is that the definition of @code{SYSTEM_NAME} is different:
22313
22314 @smallexample @c ada
22315 @cartouche
22316 type Name is (SYSTEM_NAME_GNAT);
22317 System_Name : constant Name := SYSTEM_NAME_GNAT;
22318 @end cartouche
22319 @end smallexample
22320
22321 @noindent
22322 Also, GNAT adds the Ada declarations for
22323 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
22324
22325 However, the use of the following pragma causes GNAT
22326 to extend the definition of package @code{SYSTEM} so that it
22327 encompasses the full set of HP-specific extensions,
22328 including the functions listed above:
22329
22330 @smallexample @c ada
22331 @cartouche
22332 pragma Extend_System (Aux_DEC);
22333 @end cartouche
22334 @end smallexample
22335
22336 @noindent
22337 The pragma @code{Extend_System} is a configuration pragma that
22338 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
22339 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
22340
22341 HP Ada does not allow the recompilation of the package
22342 @code{SYSTEM}. Instead HP Ada provides several pragmas
22343 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
22344 to modify values in the package @code{SYSTEM}.
22345 On OpenVMS Alpha systems, the pragma
22346 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
22347 its single argument.
22348
22349 GNAT does permit the recompilation of package @code{SYSTEM} using
22350 the special switch @option{-gnatg}, and this switch can be used if
22351 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
22352 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
22353 or @code{MEMORY_SIZE} by any other means.
22354
22355 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
22356 enumeration literal @code{SYSTEM_NAME_GNAT}.
22357
22358 The definitions provided by the use of
22359
22360 @smallexample @c ada
22361 pragma Extend_System (AUX_Dec);
22362 @end smallexample
22363
22364 @noindent
22365 are virtually identical to those provided by the HP Ada 83 package
22366 @code{SYSTEM}. One important difference is that the name of the
22367 @code{TO_ADDRESS}
22368 function for type @code{UNSIGNED_LONGWORD} is changed to
22369 @code{TO_ADDRESS_LONG}.
22370 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
22371 discussion of why this change was necessary.
22372
22373 @noindent
22374 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
22375 is in fact
22376 an extension to Ada 83 not strictly compatible with the reference manual.
22377 GNAT, in order to be exactly compatible with the standard,
22378 does not provide this capability. In HP Ada 83, the
22379 point of this definition is to deal with a call like:
22380
22381 @smallexample @c ada
22382 TO_ADDRESS (16#12777#);
22383 @end smallexample
22384
22385 @noindent
22386 Normally, according to Ada 83 semantics, one would expect this to be
22387 ambiguous, since it matches both the @code{INTEGER} and
22388 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
22389 However, in HP Ada 83, there is no ambiguity, since the
22390 definition using @i{universal_integer} takes precedence.
22391
22392 In GNAT, since the version with @i{universal_integer} cannot be supplied,
22393 it is
22394 not possible to be 100% compatible. Since there are many programs using
22395 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
22396 GNAT was
22397 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
22398 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
22399
22400 @smallexample @c ada
22401 function To_Address (X : Integer) return Address;
22402 pragma Pure_Function (To_Address);
22403
22404 function To_Address_Long (X : Unsigned_Longword) return Address;
22405 pragma Pure_Function (To_Address_Long);
22406 @end smallexample
22407
22408 @noindent
22409 This means that programs using @code{TO_ADDRESS} for
22410 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
22411
22412 @node Tasking and Task-Related Features
22413 @section Tasking and Task-Related Features
22414
22415 @noindent
22416 This section compares the treatment of tasking in GNAT
22417 and in HP Ada for OpenVMS Alpha.
22418 The GNAT description applies to both Alpha and I64 OpenVMS.
22419 For detailed information on tasking in
22420 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
22421 relevant run-time reference manual.
22422
22423 @menu
22424 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
22425 * Assigning Task IDs::
22426 * Task IDs and Delays::
22427 * Task-Related Pragmas::
22428 * Scheduling and Task Priority::
22429 * The Task Stack::
22430 * External Interrupts::
22431 @end menu
22432
22433 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22434 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22435
22436 @noindent
22437 On OpenVMS Alpha systems, each Ada task (except a passive
22438 task) is implemented as a single stream of execution
22439 that is created and managed by the kernel. On these
22440 systems, HP Ada tasking support is based on DECthreads,
22441 an implementation of the POSIX standard for threads.
22442
22443 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
22444 code that calls DECthreads routines can be used together.
22445 The interaction between Ada tasks and DECthreads routines
22446 can have some benefits. For example when on OpenVMS Alpha,
22447 HP Ada can call C code that is already threaded.
22448
22449 GNAT uses the facilities of DECthreads,
22450 and Ada tasks are mapped to threads.
22451
22452 @node Assigning Task IDs
22453 @subsection Assigning Task IDs
22454
22455 @noindent
22456 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
22457 the environment task that executes the main program. On
22458 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
22459 that have been created but are not yet activated.
22460
22461 On OpenVMS Alpha systems, task IDs are assigned at
22462 activation. On GNAT systems, task IDs are also assigned at
22463 task creation but do not have the same form or values as
22464 task ID values in HP Ada. There is no null task, and the
22465 environment task does not have a specific task ID value.
22466
22467 @node Task IDs and Delays
22468 @subsection Task IDs and Delays
22469
22470 @noindent
22471 On OpenVMS Alpha systems, tasking delays are implemented
22472 using Timer System Services. The Task ID is used for the
22473 identification of the timer request (the @code{REQIDT} parameter).
22474 If Timers are used in the application take care not to use
22475 @code{0} for the identification, because cancelling such a timer
22476 will cancel all timers and may lead to unpredictable results.
22477
22478 @node Task-Related Pragmas
22479 @subsection Task-Related Pragmas
22480
22481 @noindent
22482 Ada supplies the pragma @code{TASK_STORAGE}, which allows
22483 specification of the size of the guard area for a task
22484 stack. (The guard area forms an area of memory that has no
22485 read or write access and thus helps in the detection of
22486 stack overflow.) On OpenVMS Alpha systems, if the pragma
22487 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
22488 area is created. In the absence of a pragma @code{TASK_STORAGE},
22489 a default guard area is created.
22490
22491 GNAT supplies the following task-related pragmas:
22492
22493 @itemize @bullet
22494 @item @code{TASK_INFO}
22495
22496 This pragma appears within a task definition and
22497 applies to the task in which it appears. The argument
22498 must be of type @code{SYSTEM.TASK_INFO.TASK_INFO_TYPE}.
22499
22500 @item @code{TASK_STORAGE}
22501
22502 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
22503 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
22504 @code{SUPPRESS}, and @code{VOLATILE}.
22505 @end itemize
22506 @node Scheduling and Task Priority
22507 @subsection Scheduling and Task Priority
22508
22509 @noindent
22510 HP Ada implements the Ada language requirement that
22511 when two tasks are eligible for execution and they have
22512 different priorities, the lower priority task does not
22513 execute while the higher priority task is waiting. The HP
22514 Ada Run-Time Library keeps a task running until either the
22515 task is suspended or a higher priority task becomes ready.
22516
22517 On OpenVMS Alpha systems, the default strategy is round-
22518 robin with preemption. Tasks of equal priority take turns
22519 at the processor. A task is run for a certain period of
22520 time and then placed at the tail of the ready queue for
22521 its priority level.
22522
22523 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
22524 which can be used to enable or disable round-robin
22525 scheduling of tasks with the same priority.
22526 See the relevant HP Ada run-time reference manual for
22527 information on using the pragmas to control HP Ada task
22528 scheduling.
22529
22530 GNAT follows the scheduling rules of Annex D (Real-Time
22531 Annex) of the @cite{Ada Reference Manual}. In general, this
22532 scheduling strategy is fully compatible with HP Ada
22533 although it provides some additional constraints (as
22534 fully documented in Annex D).
22535 GNAT implements time slicing control in a manner compatible with
22536 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
22537 are identical to the HP Ada 83 pragma of the same name.
22538 Note that it is not possible to mix GNAT tasking and
22539 HP Ada 83 tasking in the same program, since the two run-time
22540 libraries are not compatible.
22541
22542 @node The Task Stack
22543 @subsection The Task Stack
22544
22545 @noindent
22546 In HP Ada, a task stack is allocated each time a
22547 non-passive task is activated. As soon as the task is
22548 terminated, the storage for the task stack is deallocated.
22549 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
22550 a default stack size is used. Also, regardless of the size
22551 specified, some additional space is allocated for task
22552 management purposes. On OpenVMS Alpha systems, at least
22553 one page is allocated.
22554
22555 GNAT handles task stacks in a similar manner. In accordance with
22556 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
22557 an alternative method for controlling the task stack size.
22558 The specification of the attribute @code{T'STORAGE_SIZE} is also
22559 supported in a manner compatible with HP Ada.
22560
22561 @node External Interrupts
22562 @subsection External Interrupts
22563
22564 @noindent
22565 On HP Ada, external interrupts can be associated with task entries.
22566 GNAT is compatible with HP Ada in its handling of external interrupts.
22567
22568 @node Pragmas and Pragma-Related Features
22569 @section Pragmas and Pragma-Related Features
22570
22571 @noindent
22572 Both HP Ada and GNAT supply all language-defined pragmas
22573 as specified by the Ada 83 standard. GNAT also supplies all
22574 language-defined pragmas introduced by Ada 95 and Ada 2005.
22575 In addition, GNAT implements the implementation-defined pragmas
22576 from HP Ada 83.
22577
22578 @itemize @bullet
22579 @item @code{AST_ENTRY}
22580
22581 @item @code{COMMON_OBJECT}
22582
22583 @item @code{COMPONENT_ALIGNMENT}
22584
22585 @item @code{EXPORT_EXCEPTION}
22586
22587 @item @code{EXPORT_FUNCTION}
22588
22589 @item @code{EXPORT_OBJECT}
22590
22591 @item @code{EXPORT_PROCEDURE}
22592
22593 @item @code{EXPORT_VALUED_PROCEDURE}
22594
22595 @item @code{FLOAT_REPRESENTATION}
22596
22597 @item @code{IDENT}
22598
22599 @item @code{IMPORT_EXCEPTION}
22600
22601 @item @code{IMPORT_FUNCTION}
22602
22603 @item @code{IMPORT_OBJECT}
22604
22605 @item @code{IMPORT_PROCEDURE}
22606
22607 @item @code{IMPORT_VALUED_PROCEDURE}
22608
22609 @item @code{INLINE_GENERIC}
22610
22611 @item @code{INTERFACE_NAME}
22612
22613 @item @code{LONG_FLOAT}
22614
22615 @item @code{MAIN_STORAGE}
22616
22617 @item @code{PASSIVE}
22618
22619 @item @code{PSECT_OBJECT}
22620
22621 @item @code{SHARE_GENERIC}
22622
22623 @item @code{SUPPRESS_ALL}
22624
22625 @item @code{TASK_STORAGE}
22626
22627 @item @code{TIME_SLICE}
22628
22629 @item @code{TITLE}
22630 @end itemize
22631
22632 @noindent
22633 These pragmas are all fully implemented, with the exception of @code{TITLE},
22634 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
22635 recognized, but which have no
22636 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
22637 use of Ada protected objects. In GNAT, all generics are inlined.
22638
22639 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
22640 a separate subprogram specification which must appear before the
22641 subprogram body.
22642
22643 GNAT also supplies a number of implementation-defined pragmas including the
22644 following:
22645
22646 @itemize @bullet
22647 @item @code{ABORT_DEFER}
22648
22649 @item @code{ADA_83}
22650
22651 @item @code{ADA_95}
22652
22653 @item @code{ADA_05}
22654
22655 @item @code{Ada_2005}
22656
22657 @item @code{Ada_12}
22658
22659 @item @code{Ada_2012}
22660
22661 @item @code{ANNOTATE}
22662
22663 @item @code{ASSERT}
22664
22665 @item @code{C_PASS_BY_COPY}
22666
22667 @item @code{CPP_CLASS}
22668
22669 @item @code{CPP_CONSTRUCTOR}
22670
22671 @item @code{CPP_DESTRUCTOR}
22672
22673 @item @code{DEBUG}
22674
22675 @item @code{EXTEND_SYSTEM}
22676
22677 @item @code{LINKER_ALIAS}
22678
22679 @item @code{LINKER_SECTION}
22680
22681 @item @code{MACHINE_ATTRIBUTE}
22682
22683 @item @code{NO_RETURN}
22684
22685 @item @code{PURE_FUNCTION}
22686
22687 @item @code{SOURCE_FILE_NAME}
22688
22689 @item @code{SOURCE_REFERENCE}
22690
22691 @item @code{TASK_INFO}
22692
22693 @item @code{UNCHECKED_UNION}
22694
22695 @item @code{UNIMPLEMENTED_UNIT}
22696
22697 @item @code{UNIVERSAL_DATA}
22698
22699 @item @code{UNSUPPRESS}
22700
22701 @item @code{WARNINGS}
22702
22703 @item @code{WEAK_EXTERNAL}
22704 @end itemize
22705
22706 @noindent
22707 For full details on these and other GNAT implementation-defined pragmas,
22708 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
22709 Manual}.
22710
22711 @menu
22712 * Restrictions on the Pragma INLINE::
22713 * Restrictions on the Pragma INTERFACE::
22714 * Restrictions on the Pragma SYSTEM_NAME::
22715 @end menu
22716
22717 @node Restrictions on the Pragma INLINE
22718 @subsection Restrictions on Pragma @code{INLINE}
22719
22720 @noindent
22721 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
22722 @itemize @bullet
22723 @item Parameters cannot have a task type.
22724
22725 @item Function results cannot be task types, unconstrained
22726 array types, or unconstrained types with discriminants.
22727
22728 @item Bodies cannot declare the following:
22729 @itemize @bullet
22730 @item Subprogram body or stub (imported subprogram is allowed)
22731
22732 @item Tasks
22733
22734 @item Generic declarations
22735
22736 @item Instantiations
22737
22738 @item Exceptions
22739
22740 @item Access types (types derived from access types allowed)
22741
22742 @item Array or record types
22743
22744 @item Dependent tasks
22745
22746 @item Direct recursive calls of subprogram or containing
22747 subprogram, directly or via a renaming
22748
22749 @end itemize
22750 @end itemize
22751
22752 @noindent
22753 In GNAT, the only restriction on pragma @code{INLINE} is that the
22754 body must occur before the call if both are in the same
22755 unit, and the size must be appropriately small. There are
22756 no other specific restrictions which cause subprograms to
22757 be incapable of being inlined.
22758
22759 @node Restrictions on the Pragma INTERFACE
22760 @subsection Restrictions on Pragma @code{INTERFACE}
22761
22762 @noindent
22763 The following restrictions on pragma @code{INTERFACE}
22764 are enforced by both HP Ada and GNAT:
22765 @itemize @bullet
22766 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
22767 Default is the default on OpenVMS Alpha systems.
22768
22769 @item Parameter passing: Language specifies default
22770 mechanisms but can be overridden with an @code{EXPORT} pragma.
22771
22772 @itemize @bullet
22773 @item Ada: Use internal Ada rules.
22774
22775 @item Bliss, C: Parameters must be mode @code{in}; cannot be
22776 record or task type. Result cannot be a string, an
22777 array, or a record.
22778
22779 @item Fortran: Parameters cannot have a task type. Result cannot
22780 be a string, an array, or a record.
22781 @end itemize
22782 @end itemize
22783
22784 @noindent
22785 GNAT is entirely upwards compatible with HP Ada, and in addition allows
22786 record parameters for all languages.
22787
22788 @node Restrictions on the Pragma SYSTEM_NAME
22789 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
22790
22791 @noindent
22792 For HP Ada for OpenVMS Alpha, the enumeration literal
22793 for the type @code{NAME} is @code{OPENVMS_AXP}.
22794 In GNAT, the enumeration
22795 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
22796
22797 @node Library of Predefined Units
22798 @section Library of Predefined Units
22799
22800 @noindent
22801 A library of predefined units is provided as part of the
22802 HP Ada and GNAT implementations. HP Ada does not provide
22803 the package @code{MACHINE_CODE} but instead recommends importing
22804 assembler code.
22805
22806 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
22807 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
22808 version.
22809 The HP Ada Predefined Library units are modified to remove post-Ada 83
22810 incompatibilities and to make them interoperable with GNAT
22811 (@pxref{Changes to DECLIB}, for details).
22812 The units are located in the @file{DECLIB} directory.
22813
22814 The GNAT RTL is contained in
22815 the @file{ADALIB} directory, and
22816 the default search path is set up to find @code{DECLIB} units in preference
22817 to @code{ADALIB} units with the same name (@code{TEXT_IO},
22818 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
22819
22820 @menu
22821 * Changes to DECLIB::
22822 @end menu
22823
22824 @node Changes to DECLIB
22825 @subsection Changes to @code{DECLIB}
22826
22827 @noindent
22828 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
22829 compatibility are minor and include the following:
22830
22831 @itemize @bullet
22832 @item Adjusting the location of pragmas and record representation
22833 clauses to obey Ada 95 (and thus Ada 2005) rules
22834
22835 @item Adding the proper notation to generic formal parameters
22836 that take unconstrained types in instantiation
22837
22838 @item Adding pragma @code{ELABORATE_BODY} to package specs
22839 that have package bodies not otherwise allowed
22840
22841 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
22842 ``@code{PROTECTD}''.
22843 Currently these are found only in the @code{STARLET} package spec.
22844
22845 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
22846 where the address size is constrained to 32 bits.
22847 @end itemize
22848
22849 @noindent
22850 None of the above changes is visible to users.
22851
22852 @node Bindings
22853 @section Bindings
22854
22855 @noindent
22856 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
22857 @itemize @bullet
22858
22859 @item Command Language Interpreter (CLI interface)
22860
22861 @item DECtalk Run-Time Library (DTK interface)
22862
22863 @item Librarian utility routines (LBR interface)
22864
22865 @item General Purpose Run-Time Library (LIB interface)
22866
22867 @item Math Run-Time Library (MTH interface)
22868
22869 @item National Character Set Run-Time Library (NCS interface)
22870
22871 @item Compiled Code Support Run-Time Library (OTS interface)
22872
22873 @item Parallel Processing Run-Time Library (PPL interface)
22874
22875 @item Screen Management Run-Time Library (SMG interface)
22876
22877 @item Sort Run-Time Library (SOR interface)
22878
22879 @item String Run-Time Library (STR interface)
22880
22881 @item STARLET System Library
22882 @findex Starlet
22883
22884 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
22885
22886 @item X Windows Toolkit (XT interface)
22887
22888 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
22889 @end itemize
22890
22891 @noindent
22892 GNAT provides implementations of these HP bindings in the @code{DECLIB}
22893 directory, on both the Alpha and I64 OpenVMS platforms.
22894
22895 The X components of DECLIB compatibility package are located in a separate
22896 library, called XDECGNAT, which is not linked with by default; this library
22897 must be explicitly linked with any application that makes use of any X facilities,
22898 with a command similar to
22899
22900 @code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
22901
22902 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
22903 in the
22904 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
22905 A pragma @code{Linker_Options} has been added to packages @code{Xm},
22906 @code{Xt}, and @code{X_Lib}
22907 causing the default X/Motif sharable image libraries to be linked in. This
22908 is done via options files named @file{xm.opt}, @file{xt.opt}, and
22909 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
22910
22911 It may be necessary to edit these options files to update or correct the
22912 library names if, for example, the newer X/Motif bindings from
22913 @file{ADA$EXAMPLES}
22914 had been (previous to installing GNAT) copied and renamed to supersede the
22915 default @file{ADA$PREDEFINED} versions.
22916
22917 @menu
22918 * Shared Libraries and Options Files::
22919 * Interfaces to C::
22920 @end menu
22921
22922 @node Shared Libraries and Options Files
22923 @subsection Shared Libraries and Options Files
22924
22925 @noindent
22926 When using the HP Ada
22927 predefined X and Motif bindings, the linking with their sharable images is
22928 done automatically by @command{GNAT LINK}.
22929 When using other X and Motif bindings, you need
22930 to add the corresponding sharable images to the command line for
22931 @code{GNAT LINK}. When linking with shared libraries, or with
22932 @file{.OPT} files, you must
22933 also add them to the command line for @command{GNAT LINK}.
22934
22935 A shared library to be used with GNAT is built in the same way as other
22936 libraries under VMS. The VMS Link command can be used in standard fashion.
22937
22938 @node Interfaces to C
22939 @subsection Interfaces to C
22940
22941 @noindent
22942 HP Ada
22943 provides the following Ada types and operations:
22944
22945 @itemize @bullet
22946 @item C types package (@code{C_TYPES})
22947
22948 @item C strings (@code{C_TYPES.NULL_TERMINATED})
22949
22950 @item Other_types (@code{SHORT_INT})
22951 @end itemize
22952
22953 @noindent
22954 Interfacing to C with GNAT, you can use the above approach
22955 described for HP Ada or the facilities of Annex B of
22956 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
22957 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
22958 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
22959
22960 The @option{-gnatF} qualifier forces default and explicit
22961 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
22962 to be uppercased for compatibility with the default behavior
22963 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
22964
22965 @node Main Program Definition
22966 @section Main Program Definition
22967
22968 @noindent
22969 The following section discusses differences in the
22970 definition of main programs on HP Ada and GNAT.
22971 On HP Ada, main programs are defined to meet the
22972 following conditions:
22973 @itemize @bullet
22974 @item Procedure with no formal parameters (returns @code{0} upon
22975 normal completion)
22976
22977 @item Procedure with no formal parameters (returns @code{42} when
22978 an unhandled exception is raised)
22979
22980 @item Function with no formal parameters whose returned value
22981 is of a discrete type
22982
22983 @item Procedure with one @code{out} formal of a discrete type for
22984 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
22985
22986 @end itemize
22987
22988 @noindent
22989 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
22990 a main function or main procedure returns a discrete
22991 value whose size is less than 64 bits (32 on VAX systems),
22992 the value is zero- or sign-extended as appropriate.
22993 On GNAT, main programs are defined as follows:
22994 @itemize @bullet
22995 @item Must be a non-generic, parameterless subprogram that
22996 is either a procedure or function returning an Ada
22997 @code{STANDARD.INTEGER} (the predefined type)
22998
22999 @item Cannot be a generic subprogram or an instantiation of a
23000 generic subprogram
23001 @end itemize
23002
23003 @node Implementation-Defined Attributes
23004 @section Implementation-Defined Attributes
23005
23006 @noindent
23007 GNAT provides all HP Ada implementation-defined
23008 attributes.
23009
23010 @node Compiler and Run-Time Interfacing
23011 @section Compiler and Run-Time Interfacing
23012
23013 @noindent
23014 HP Ada provides the following qualifiers to pass options to the linker
23015 (ACS LINK):
23016 @itemize @bullet
23017 @item @option{/WAIT} and @option{/SUBMIT}
23018
23019 @item @option{/COMMAND}
23020
23021 @item @option{/@r{[}NO@r{]}MAP}
23022
23023 @item @option{/OUTPUT=@var{file-spec}}
23024
23025 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
23026 @end itemize
23027
23028 @noindent
23029 To pass options to the linker, GNAT provides the following
23030 switches:
23031
23032 @itemize @bullet
23033 @item @option{/EXECUTABLE=@var{exec-name}}
23034
23035 @item @option{/VERBOSE}
23036
23037 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
23038 @end itemize
23039
23040 @noindent
23041 For more information on these switches, see
23042 @ref{Switches for gnatlink}.
23043 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
23044 to control optimization. HP Ada also supplies the
23045 following pragmas:
23046 @itemize @bullet
23047 @item @code{OPTIMIZE}
23048
23049 @item @code{INLINE}
23050
23051 @item @code{INLINE_GENERIC}
23052
23053 @item @code{SUPPRESS_ALL}
23054
23055 @item @code{PASSIVE}
23056 @end itemize
23057
23058 @noindent
23059 In GNAT, optimization is controlled strictly by command
23060 line parameters, as described in the corresponding section of this guide.
23061 The HP pragmas for control of optimization are
23062 recognized but ignored.
23063
23064 Note that in GNAT, the default is optimization off, whereas in HP Ada
23065 the default is that optimization is turned on.
23066
23067 @node Program Compilation and Library Management
23068 @section Program Compilation and Library Management
23069
23070 @noindent
23071 HP Ada and GNAT provide a comparable set of commands to
23072 build programs. HP Ada also provides a program library,
23073 which is a concept that does not exist on GNAT. Instead,
23074 GNAT provides directories of sources that are compiled as
23075 needed.
23076
23077 The following table summarizes
23078 the HP Ada commands and provides
23079 equivalent GNAT commands. In this table, some GNAT
23080 equivalents reflect the fact that GNAT does not use the
23081 concept of a program library. Instead, it uses a model
23082 in which collections of source and object files are used
23083 in a manner consistent with other languages like C and
23084 Fortran. Therefore, standard system file commands are used
23085 to manipulate these elements. Those GNAT commands are marked with
23086 an asterisk.
23087 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
23088
23089 @need 1500
23090 @multitable @columnfractions .35 .65
23091
23092 @item @emph{HP Ada Command}
23093 @tab @emph{GNAT Equivalent / Description}
23094
23095 @item @command{ADA}
23096 @tab @command{GNAT COMPILE}@*
23097 Invokes the compiler to compile one or more Ada source files.
23098
23099 @item @command{ACS ATTACH}@*
23100 @tab [No equivalent]@*
23101 Switches control of terminal from current process running the program
23102 library manager.
23103
23104 @item @command{ACS CHECK}
23105 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
23106 Forms the execution closure of one
23107 or more compiled units and checks completeness and currency.
23108
23109 @item @command{ACS COMPILE}
23110 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23111 Forms the execution closure of one or
23112 more specified units, checks completeness and currency,
23113 identifies units that have revised source files, compiles same,
23114 and recompiles units that are or will become obsolete.
23115 Also completes incomplete generic instantiations.
23116
23117 @item @command{ACS COPY FOREIGN}
23118 @tab Copy (*)@*
23119 Copies a foreign object file into the program library as a
23120 library unit body.
23121
23122 @item @command{ACS COPY UNIT}
23123 @tab Copy (*)@*
23124 Copies a compiled unit from one program library to another.
23125
23126 @item @command{ACS CREATE LIBRARY}
23127 @tab Create /directory (*)@*
23128 Creates a program library.
23129
23130 @item @command{ACS CREATE SUBLIBRARY}
23131 @tab Create /directory (*)@*
23132 Creates a program sublibrary.
23133
23134 @item @command{ACS DELETE LIBRARY}
23135 @tab @*
23136 Deletes a program library and its contents.
23137
23138 @item @command{ACS DELETE SUBLIBRARY}
23139 @tab @*
23140 Deletes a program sublibrary and its contents.
23141
23142 @item @command{ACS DELETE UNIT}
23143 @tab Delete file (*)@*
23144 On OpenVMS systems, deletes one or more compiled units from
23145 the current program library.
23146
23147 @item @command{ACS DIRECTORY}
23148 @tab Directory (*)@*
23149 On OpenVMS systems, lists units contained in the current
23150 program library.
23151
23152 @item @command{ACS ENTER FOREIGN}
23153 @tab Copy (*)@*
23154 Allows the import of a foreign body as an Ada library
23155 spec and enters a reference to a pointer.
23156
23157 @item @command{ACS ENTER UNIT}
23158 @tab Copy (*)@*
23159 Enters a reference (pointer) from the current program library to
23160 a unit compiled into another program library.
23161
23162 @item @command{ACS EXIT}
23163 @tab [No equivalent]@*
23164 Exits from the program library manager.
23165
23166 @item @command{ACS EXPORT}
23167 @tab Copy (*)@*
23168 Creates an object file that contains system-specific object code
23169 for one or more units. With GNAT, object files can simply be copied
23170 into the desired directory.
23171
23172 @item @command{ACS EXTRACT SOURCE}
23173 @tab Copy (*)@*
23174 Allows access to the copied source file for each Ada compilation unit
23175
23176 @item @command{ACS HELP}
23177 @tab @command{HELP GNAT}@*
23178 Provides online help.
23179
23180 @item @command{ACS LINK}
23181 @tab @command{GNAT LINK}@*
23182 Links an object file containing Ada units into an executable file.
23183
23184 @item @command{ACS LOAD}
23185 @tab Copy (*)@*
23186 Loads (partially compiles) Ada units into the program library.
23187 Allows loading a program from a collection of files into a library
23188 without knowing the relationship among units.
23189
23190 @item @command{ACS MERGE}
23191 @tab Copy (*)@*
23192 Merges into the current program library, one or more units from
23193 another library where they were modified.
23194
23195 @item @command{ACS RECOMPILE}
23196 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23197 Recompiles from external or copied source files any obsolete
23198 unit in the closure. Also, completes any incomplete generic
23199 instantiations.
23200
23201 @item @command{ACS REENTER}
23202 @tab @command{GNAT MAKE}@*
23203 Reenters current references to units compiled after last entered
23204 with the @command{ACS ENTER UNIT} command.
23205
23206 @item @command{ACS SET LIBRARY}
23207 @tab Set default (*)@*
23208 Defines a program library to be the compilation context as well
23209 as the target library for compiler output and commands in general.
23210
23211 @item @command{ACS SET PRAGMA}
23212 @tab Edit @file{gnat.adc} (*)@*
23213 Redefines specified values of the library characteristics
23214 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
23215 and @code{Float_Representation}.
23216
23217 @item @command{ACS SET SOURCE}
23218 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
23219 Defines the source file search list for the @command{ACS COMPILE} command.
23220
23221 @item @command{ACS SHOW LIBRARY}
23222 @tab Directory (*)@*
23223 Lists information about one or more program libraries.
23224
23225 @item @command{ACS SHOW PROGRAM}
23226 @tab [No equivalent]@*
23227 Lists information about the execution closure of one or
23228 more units in the program library.
23229
23230 @item @command{ACS SHOW SOURCE}
23231 @tab Show logical @code{ADA_INCLUDE_PATH}@*
23232 Shows the source file search used when compiling units.
23233
23234 @item @command{ACS SHOW VERSION}
23235 @tab Compile with @option{VERBOSE} option
23236 Displays the version number of the compiler and program library
23237 manager used.
23238
23239 @item @command{ACS SPAWN}
23240 @tab [No equivalent]@*
23241 Creates a subprocess of the current process (same as @command{DCL SPAWN}
23242 command).
23243
23244 @item @command{ACS VERIFY}
23245 @tab [No equivalent]@*
23246 Performs a series of consistency checks on a program library to
23247 determine whether the library structure and library files are in
23248 valid form.
23249 @end multitable
23250
23251 @noindent
23252
23253 @node Input-Output
23254 @section Input-Output
23255
23256 @noindent
23257 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
23258 Management Services (RMS) to perform operations on
23259 external files.
23260
23261 @noindent
23262 HP Ada and GNAT predefine an identical set of input-
23263 output packages. To make the use of the
23264 generic @code{TEXT_IO} operations more convenient, HP Ada
23265 provides predefined library packages that instantiate the
23266 integer and floating-point operations for the predefined
23267 integer and floating-point types as shown in the following table.
23268
23269 @multitable @columnfractions .45 .55
23270 @item @emph{Package Name} @tab Instantiation
23271
23272 @item @code{INTEGER_TEXT_IO}
23273 @tab @code{INTEGER_IO(INTEGER)}
23274
23275 @item @code{SHORT_INTEGER_TEXT_IO}
23276 @tab @code{INTEGER_IO(SHORT_INTEGER)}
23277
23278 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
23279 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
23280
23281 @item @code{FLOAT_TEXT_IO}
23282 @tab @code{FLOAT_IO(FLOAT)}
23283
23284 @item @code{LONG_FLOAT_TEXT_IO}
23285 @tab @code{FLOAT_IO(LONG_FLOAT)}
23286 @end multitable
23287
23288 @noindent
23289 The HP Ada predefined packages and their operations
23290 are implemented using OpenVMS Alpha files and input-output
23291 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
23292 Familiarity with the following is recommended:
23293 @itemize @bullet
23294 @item RMS file organizations and access methods
23295
23296 @item OpenVMS file specifications and directories
23297
23298 @item OpenVMS File Definition Language (FDL)
23299 @end itemize
23300
23301 @noindent
23302 GNAT provides I/O facilities that are completely
23303 compatible with HP Ada. The distribution includes the
23304 standard HP Ada versions of all I/O packages, operating
23305 in a manner compatible with HP Ada. In particular, the
23306 following packages are by default the HP Ada (Ada 83)
23307 versions of these packages rather than the renamings
23308 suggested in Annex J of the Ada Reference Manual:
23309 @itemize @bullet
23310 @item @code{TEXT_IO}
23311
23312 @item @code{SEQUENTIAL_IO}
23313
23314 @item @code{DIRECT_IO}
23315 @end itemize
23316
23317 @noindent
23318 The use of the standard child package syntax (for
23319 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
23320 packages.
23321 GNAT provides HP-compatible predefined instantiations
23322 of the @code{TEXT_IO} packages, and also
23323 provides the standard predefined instantiations required
23324 by the @cite{Ada Reference Manual}.
23325
23326 For further information on how GNAT interfaces to the file
23327 system or how I/O is implemented in programs written in
23328 mixed languages, see @ref{Implementation of the Standard I/O,,,
23329 gnat_rm, GNAT Reference Manual}.
23330 This chapter covers the following:
23331 @itemize @bullet
23332 @item Standard I/O packages
23333
23334 @item @code{FORM} strings
23335
23336 @item @code{ADA.DIRECT_IO}
23337
23338 @item @code{ADA.SEQUENTIAL_IO}
23339
23340 @item @code{ADA.TEXT_IO}
23341
23342 @item Stream pointer positioning
23343
23344 @item Reading and writing non-regular files
23345
23346 @item @code{GET_IMMEDIATE}
23347
23348 @item Treating @code{TEXT_IO} files as streams
23349
23350 @item Shared files
23351
23352 @item Open modes
23353 @end itemize
23354
23355 @node Implementation Limits
23356 @section Implementation Limits
23357
23358 @noindent
23359 The following table lists implementation limits for HP Ada
23360 and GNAT systems.
23361 @multitable @columnfractions .60 .20 .20
23362 @sp 1
23363 @item @emph{Compilation Parameter}
23364 @tab @emph{HP Ada}
23365 @tab @emph{GNAT}
23366 @sp 1
23367
23368 @item In a subprogram or entry declaration, maximum number of
23369 formal parameters that are of an unconstrained record type
23370 @tab 32
23371 @tab No set limit
23372 @sp 1
23373
23374 @item Maximum identifier length (number of characters)
23375 @tab 255
23376 @tab 32766
23377 @sp 1
23378
23379 @item Maximum number of characters in a source line
23380 @tab 255
23381 @tab 32766
23382 @sp 1
23383
23384 @item Maximum collection size (number of bytes)
23385 @tab 2**31-1
23386 @tab 2**31-1
23387 @sp 1
23388
23389 @item Maximum number of discriminants for a record type
23390 @tab 245
23391 @tab No set limit
23392 @sp 1
23393
23394 @item Maximum number of formal parameters in an entry or
23395 subprogram declaration
23396 @tab 246
23397 @tab No set limit
23398 @sp 1
23399
23400 @item Maximum number of dimensions in an array type
23401 @tab 255
23402 @tab No set limit
23403 @sp 1
23404
23405 @item Maximum number of library units and subunits in a compilation.
23406 @tab 4095
23407 @tab No set limit
23408 @sp 1
23409
23410 @item Maximum number of library units and subunits in an execution.
23411 @tab 16383
23412 @tab No set limit
23413 @sp 1
23414
23415 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
23416 or @code{PSECT_OBJECT}
23417 @tab 32757
23418 @tab No set limit
23419 @sp 1
23420
23421 @item Maximum number of enumeration literals in an enumeration type
23422 definition
23423 @tab 65535
23424 @tab No set limit
23425 @sp 1
23426
23427 @item Maximum number of lines in a source file
23428 @tab 65534
23429 @tab No set limit
23430 @sp 1
23431
23432 @item Maximum number of bits in any object
23433 @tab 2**31-1
23434 @tab 2**31-1
23435 @sp 1
23436
23437 @item Maximum size of the static portion of a stack frame (approximate)
23438 @tab 2**31-1
23439 @tab 2**31-1
23440 @end multitable
23441
23442 @node Tools and Utilities
23443 @section Tools and Utilities
23444
23445 @noindent
23446 The following table lists some of the OpenVMS development tools
23447 available for HP Ada, and the corresponding tools for
23448 use with @value{EDITION} on Alpha and I64 platforms.
23449 Aside from the debugger, all the OpenVMS tools identified are part
23450 of the DECset package.
23451
23452 @iftex
23453 @c Specify table in TeX since Texinfo does a poor job
23454 @tex
23455 \smallskip
23456 \smallskip
23457 \settabs\+Language-Sensitive Editor\quad
23458 &Product with HP Ada\quad
23459 &\cr
23460 \+\it Tool
23461 &\it Product with HP Ada
23462 & \it Product with @value{EDITION}\cr
23463 \smallskip
23464 \+Code Management System
23465 &HP CMS
23466 & HP CMS\cr
23467 \smallskip
23468 \+Language-Sensitive Editor
23469 &HP LSE
23470 & emacs or HP LSE (Alpha)\cr
23471 \+
23472 &
23473 & HP LSE (I64)\cr
23474 \smallskip
23475 \+Debugger
23476 &OpenVMS Debug
23477 & gdb (Alpha),\cr
23478 \+
23479 &
23480 & OpenVMS Debug (I64)\cr
23481 \smallskip
23482 \+Source Code Analyzer /
23483 &HP SCA
23484 & GNAT XREF\cr
23485 \+Cross Referencer
23486 &
23487 &\cr
23488 \smallskip
23489 \+Test Manager
23490 &HP Digital Test
23491 & HP DTM\cr
23492 \+
23493 &Manager (DTM)
23494 &\cr
23495 \smallskip
23496 \+Performance and
23497 & HP PCA
23498 & HP PCA\cr
23499 \+Coverage Analyzer
23500 &
23501 &\cr
23502 \smallskip
23503 \+Module Management
23504 & HP MMS
23505 & Not applicable\cr
23506 \+ System
23507 &
23508 &\cr
23509 \smallskip
23510 \smallskip
23511 @end tex
23512 @end iftex
23513
23514 @ifnottex
23515 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
23516 @c the TeX version above for the printed version
23517 @flushleft
23518 @c @multitable @columnfractions .3 .4 .4
23519 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
23520 @item @i{Tool}
23521 @tab @i{Tool with HP Ada}
23522 @tab @i{Tool with @value{EDITION}}
23523 @item Code Management@*System
23524 @tab HP CMS
23525 @tab HP CMS
23526 @item Language-Sensitive@*Editor
23527 @tab HP LSE
23528 @tab emacs or HP LSE (Alpha)
23529 @item
23530 @tab
23531 @tab HP LSE (I64)
23532 @item Debugger
23533 @tab OpenVMS Debug
23534 @tab gdb (Alpha),
23535 @item
23536 @tab
23537 @tab OpenVMS Debug (I64)
23538 @item Source Code Analyzer /@*Cross Referencer
23539 @tab HP SCA
23540 @tab GNAT XREF
23541 @item Test Manager
23542 @tab HP Digital Test@*Manager (DTM)
23543 @tab HP DTM
23544 @item Performance and@*Coverage Analyzer
23545 @tab HP PCA
23546 @tab HP PCA
23547 @item Module Management@*System
23548 @tab HP MMS
23549 @tab Not applicable
23550 @end multitable
23551 @end flushleft
23552 @end ifnottex
23553
23554 @end ifset
23555
23556 @c **************************************
23557 @node Platform-Specific Information for the Run-Time Libraries
23558 @appendix Platform-Specific Information for the Run-Time Libraries
23559 @cindex Tasking and threads libraries
23560 @cindex Threads libraries and tasking
23561 @cindex Run-time libraries (platform-specific information)
23562
23563 @noindent
23564 The GNAT run-time implementation may vary with respect to both the
23565 underlying threads library and the exception handling scheme.
23566 For threads support, one or more of the following are supplied:
23567 @itemize @bullet
23568 @item @b{native threads library}, a binding to the thread package from
23569 the underlying operating system
23570
23571 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
23572 POSIX thread package
23573 @end itemize
23574
23575 @noindent
23576 For exception handling, either or both of two models are supplied:
23577 @itemize @bullet
23578 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
23579 Most programs should experience a substantial speed improvement by
23580 being compiled with a ZCX run-time.
23581 This is especially true for
23582 tasking applications or applications with many exception handlers.}
23583 @cindex Zero-Cost Exceptions
23584 @cindex ZCX (Zero-Cost Exceptions)
23585 which uses binder-generated tables that
23586 are interrogated at run time to locate a handler
23587
23588 @item @b{setjmp / longjmp} (``SJLJ''),
23589 @cindex setjmp/longjmp Exception Model
23590 @cindex SJLJ (setjmp/longjmp Exception Model)
23591 which uses dynamically-set data to establish
23592 the set of handlers
23593 @end itemize
23594
23595 @noindent
23596 This appendix summarizes which combinations of threads and exception support
23597 are supplied on various GNAT platforms.
23598 It then shows how to select a particular library either
23599 permanently or temporarily,
23600 explains the properties of (and tradeoffs among) the various threads
23601 libraries, and provides some additional
23602 information about several specific platforms.
23603
23604 @menu
23605 * Summary of Run-Time Configurations::
23606 * Specifying a Run-Time Library::
23607 * Choosing the Scheduling Policy::
23608 * Solaris-Specific Considerations::
23609 * Linux-Specific Considerations::
23610 * AIX-Specific Considerations::
23611 * RTX-Specific Considerations::
23612 * HP-UX-Specific Considerations::
23613 @end menu
23614
23615 @node Summary of Run-Time Configurations
23616 @section Summary of Run-Time Configurations
23617
23618 @multitable @columnfractions .30 .70
23619 @item @b{alpha-openvms}
23620 @item @code{@ @ }@i{rts-native (default)}
23621 @item @code{@ @ @ @ }Tasking @tab native VMS threads
23622 @item @code{@ @ @ @ }Exceptions @tab ZCX
23623 @*
23624 @item @code{@ @ }@i{rts-sjlj}
23625 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
23626 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23627 @*
23628 @item @b{ia64-hp_linux}
23629 @item @code{@ @ }@i{rts-native (default)}
23630 @item @code{@ @ @ @ }Tasking @tab pthread library
23631 @item @code{@ @ @ @ }Exceptions @tab ZCX
23632 @*
23633 @item @b{ia64-hpux}
23634 @item @code{@ @ }@i{rts-native (default)}
23635 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
23636 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23637 @*
23638 @item @b{ia64-openvms}
23639 @item @code{@ @ }@i{rts-native (default)}
23640 @item @code{@ @ @ @ }Tasking @tab native VMS threads
23641 @item @code{@ @ @ @ }Exceptions @tab ZCX
23642 @*
23643 @item @b{ia64-sgi_linux}
23644 @item @code{@ @ }@i{rts-native (default)}
23645 @item @code{@ @ @ @ }Tasking @tab pthread library
23646 @item @code{@ @ @ @ }Exceptions @tab ZCX
23647 @*
23648 @item @b{pa-hpux}
23649 @item @code{@ @ }@i{rts-native (default)}
23650 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
23651 @item @code{@ @ @ @ }Exceptions @tab ZCX
23652 @*
23653 @item @code{@ @ }@i{rts-sjlj}
23654 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
23655 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23656 @*
23657 @item @b{ppc-aix}
23658 @item @code{@ @ }@i{rts-native (default)}
23659 @item @code{@ @ @ @ }Tasking @tab native AIX threads
23660 @item @code{@ @ @ @ }Exceptions @tab ZCX
23661 @*
23662 @item @code{@ @ }@i{rts-sjlj}
23663 @item @code{@ @ @ @ }Tasking @tab native AIX threads
23664 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23665 @*
23666 @item @b{ppc-darwin}
23667 @item @code{@ @ }@i{rts-native (default)}
23668 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
23669 @item @code{@ @ @ @ }Exceptions @tab ZCX
23670 @*
23671 @item @b{sparc-solaris} @tab
23672 @item @code{@ @ }@i{rts-native (default)}
23673 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
23674 @item @code{@ @ @ @ }Exceptions @tab ZCX
23675 @*
23676 @item @code{@ @ }@i{rts-pthread}
23677 @item @code{@ @ @ @ }Tasking @tab pthread library
23678 @item @code{@ @ @ @ }Exceptions @tab ZCX
23679 @*
23680 @item @code{@ @ }@i{rts-sjlj}
23681 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
23682 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23683 @*
23684 @item @b{sparc64-solaris} @tab
23685 @item @code{@ @ }@i{rts-native (default)}
23686 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
23687 @item @code{@ @ @ @ }Exceptions @tab ZCX
23688 @*
23689 @item @b{x86-linux}
23690 @item @code{@ @ }@i{rts-native (default)}
23691 @item @code{@ @ @ @ }Tasking @tab pthread library
23692 @item @code{@ @ @ @ }Exceptions @tab ZCX
23693 @*
23694 @item @code{@ @ }@i{rts-sjlj}
23695 @item @code{@ @ @ @ }Tasking @tab pthread library
23696 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23697 @*
23698 @item @b{x86-lynx}
23699 @item @code{@ @ }@i{rts-native (default)}
23700 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
23701 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23702 @*
23703 @item @b{x86-solaris}
23704 @item @code{@ @ }@i{rts-native (default)}
23705 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
23706 @item @code{@ @ @ @ }Exceptions @tab ZCX
23707 @*
23708 @item @code{@ @ }@i{rts-sjlj}
23709 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
23710 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23711 @*
23712 @item @b{x86-windows}
23713 @item @code{@ @ }@i{rts-native (default)}
23714 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
23715 @item @code{@ @ @ @ }Exceptions @tab ZCX
23716 @*
23717 @item @code{@ @ }@i{rts-sjlj}
23718 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
23719 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23720 @*
23721 @item @b{x86-windows-rtx}
23722 @item @code{@ @ }@i{rts-rtx-rtss (default)}
23723 @item @code{@ @ @ @ }Tasking @tab RTX real-time subsystem RTSS threads (kernel mode)
23724 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23725 @*
23726 @item @code{@ @ }@i{rts-rtx-w32}
23727 @item @code{@ @ @ @ }Tasking @tab RTX Win32 threads (user mode)
23728 @item @code{@ @ @ @ }Exceptions @tab ZCX
23729 @*
23730 @item @b{x86_64-linux}
23731 @item @code{@ @ }@i{rts-native (default)}
23732 @item @code{@ @ @ @ }Tasking @tab pthread library
23733 @item @code{@ @ @ @ }Exceptions @tab ZCX
23734 @*
23735 @item @code{@ @ }@i{rts-sjlj}
23736 @item @code{@ @ @ @ }Tasking @tab pthread library
23737 @item @code{@ @ @ @ }Exceptions @tab SJLJ
23738 @*
23739 @end multitable
23740
23741 @node Specifying a Run-Time Library
23742 @section Specifying a Run-Time Library
23743
23744 @noindent
23745 The @file{adainclude} subdirectory containing the sources of the GNAT
23746 run-time library, and the @file{adalib} subdirectory containing the
23747 @file{ALI} files and the static and/or shared GNAT library, are located
23748 in the gcc target-dependent area:
23749
23750 @smallexample
23751 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
23752 @end smallexample
23753
23754 @noindent
23755 As indicated above, on some platforms several run-time libraries are supplied.
23756 These libraries are installed in the target dependent area and
23757 contain a complete source and binary subdirectory. The detailed description
23758 below explains the differences between the different libraries in terms of
23759 their thread support.
23760
23761 The default run-time library (when GNAT is installed) is @emph{rts-native}.
23762 This default run time is selected by the means of soft links.
23763 For example on x86-linux:
23764
23765 @smallexample
23766 @group
23767 $(target-dir)
23768 |
23769 +--- adainclude----------+
23770 | |
23771 +--- adalib-----------+ |
23772 | | |
23773 +--- rts-native | |
23774 | | | |
23775 | +--- adainclude <---+
23776 | | |
23777 | +--- adalib <----+
23778 |
23779 +--- rts-sjlj
23780 |
23781 +--- adainclude
23782 |
23783 +--- adalib
23784 @end group
23785 @end smallexample
23786
23787 @noindent
23788 If the @i{rts-sjlj} library is to be selected on a permanent basis,
23789 these soft links can be modified with the following commands:
23790
23791 @smallexample
23792 $ cd $target
23793 $ rm -f adainclude adalib
23794 $ ln -s rts-sjlj/adainclude adainclude
23795 $ ln -s rts-sjlj/adalib adalib
23796 @end smallexample
23797
23798 @noindent
23799 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
23800 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
23801 @file{$target/ada_object_path}.
23802
23803 Selecting another run-time library temporarily can be
23804 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
23805 @cindex @option{--RTS} option
23806
23807 @node Choosing the Scheduling Policy
23808 @section Choosing the Scheduling Policy
23809
23810 @noindent
23811 When using a POSIX threads implementation, you have a choice of several
23812 scheduling policies: @code{SCHED_FIFO},
23813 @cindex @code{SCHED_FIFO} scheduling policy
23814 @code{SCHED_RR}
23815 @cindex @code{SCHED_RR} scheduling policy
23816 and @code{SCHED_OTHER}.
23817 @cindex @code{SCHED_OTHER} scheduling policy
23818 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
23819 or @code{SCHED_RR} requires special (e.g., root) privileges.
23820
23821 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
23822 @code{SCHED_FIFO},
23823 @cindex @code{SCHED_FIFO} scheduling policy
23824 you can use one of the following:
23825
23826 @itemize @bullet
23827 @item
23828 @code{pragma Time_Slice (0.0)}
23829 @cindex pragma Time_Slice
23830 @item
23831 the corresponding binder option @option{-T0}
23832 @cindex @option{-T0} option
23833 @item
23834 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23835 @cindex pragma Task_Dispatching_Policy
23836 @end itemize
23837
23838 @noindent
23839 To specify @code{SCHED_RR},
23840 @cindex @code{SCHED_RR} scheduling policy
23841 you should use @code{pragma Time_Slice} with a
23842 value greater than @code{0.0}, or else use the corresponding @option{-T}
23843 binder option.
23844
23845 @node Solaris-Specific Considerations
23846 @section Solaris-Specific Considerations
23847 @cindex Solaris Sparc threads libraries
23848
23849 @noindent
23850 This section addresses some topics related to the various threads libraries
23851 on Sparc Solaris.
23852
23853 @menu
23854 * Solaris Threads Issues::
23855 @end menu
23856
23857 @node Solaris Threads Issues
23858 @subsection Solaris Threads Issues
23859
23860 @noindent
23861 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
23862 library based on POSIX threads --- @emph{rts-pthread}.
23863 @cindex rts-pthread threads library
23864 This run-time library has the advantage of being mostly shared across all
23865 POSIX-compliant thread implementations, and it also provides under
23866 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
23867 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
23868 and @code{PTHREAD_PRIO_PROTECT}
23869 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
23870 semantics that can be selected using the predefined pragma
23871 @code{Locking_Policy}
23872 @cindex pragma Locking_Policy (under rts-pthread)
23873 with respectively
23874 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
23875 @cindex @code{Inheritance_Locking} (under rts-pthread)
23876 @cindex @code{Ceiling_Locking} (under rts-pthread)
23877
23878 As explained above, the native run-time library is based on the Solaris thread
23879 library (@code{libthread}) and is the default library.
23880
23881 When the Solaris threads library is used (this is the default), programs
23882 compiled with GNAT can automatically take advantage of
23883 and can thus execute on multiple processors.
23884 The user can alternatively specify a processor on which the program should run
23885 to emulate a single-processor system. The multiprocessor / uniprocessor choice
23886 is made by
23887 setting the environment variable @env{GNAT_PROCESSOR}
23888 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
23889 to one of the following:
23890
23891 @table @code
23892 @item -2
23893 Use the default configuration (run the program on all
23894 available processors) - this is the same as having @code{GNAT_PROCESSOR}
23895 unset
23896
23897 @item -1
23898 Let the run-time implementation choose one processor and run the program on
23899 that processor
23900
23901 @item 0 .. Last_Proc
23902 Run the program on the specified processor.
23903 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
23904 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
23905 @end table
23906
23907 @node Linux-Specific Considerations
23908 @section Linux-Specific Considerations
23909 @cindex Linux threads libraries
23910
23911 @noindent
23912 On GNU/Linux without NPTL support (usually system with GNU C Library
23913 older than 2.3), the signal model is not POSIX compliant, which means
23914 that to send a signal to the process, you need to send the signal to all
23915 threads, e.g.@: by using @code{killpg()}.
23916
23917 @node AIX-Specific Considerations
23918 @section AIX-Specific Considerations
23919 @cindex AIX resolver library
23920
23921 @noindent
23922 On AIX, the resolver library initializes some internal structure on
23923 the first call to @code{get*by*} functions, which are used to implement
23924 @code{GNAT.Sockets.Get_Host_By_Name} and
23925 @code{GNAT.Sockets.Get_Host_By_Address}.
23926 If such initialization occurs within an Ada task, and the stack size for
23927 the task is the default size, a stack overflow may occur.
23928
23929 To avoid this overflow, the user should either ensure that the first call
23930 to @code{GNAT.Sockets.Get_Host_By_Name} or
23931 @code{GNAT.Sockets.Get_Host_By_Addrss}
23932 occurs in the environment task, or use @code{pragma Storage_Size} to
23933 specify a sufficiently large size for the stack of the task that contains
23934 this call.
23935
23936 @node RTX-Specific Considerations
23937 @section RTX-Specific Considerations
23938 @cindex RTX libraries
23939
23940 @noindent
23941 The Real-time Extension (RTX) to Windows is based on the Windows Win32
23942 API. Applications can be built to work in two different modes:
23943
23944 @itemize @bullet
23945 @item
23946 Windows executables that run in Ring 3 to utilize memory protection
23947 (@emph{rts-rtx-w32}).
23948
23949 @item
23950 Real-time subsystem (RTSS) executables that run in Ring 0, where
23951 performance can be optimized with RTSS applications taking precedent
23952 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
23953 the Microsoft linker to handle RTSS libraries.
23954
23955 @end itemize
23956
23957 @node HP-UX-Specific Considerations
23958 @section HP-UX-Specific Considerations
23959 @cindex HP-UX Scheduling
23960
23961 @noindent
23962 On HP-UX, appropriate privileges are required to change the scheduling
23963 parameters of a task. The calling process must have appropriate
23964 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
23965 successfully change the scheduling parameters.
23966
23967 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
23968 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
23969 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
23970
23971 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
23972 one of the following:
23973
23974 @itemize @bullet
23975 @item
23976 @code{pragma Time_Slice (0.0)}
23977 @cindex pragma Time_Slice
23978 @item
23979 the corresponding binder option @option{-T0}
23980 @cindex @option{-T0} option
23981 @item
23982 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
23983 @cindex pragma Task_Dispatching_Policy
23984 @end itemize
23985
23986 @noindent
23987 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
23988 you should use @code{pragma Time_Slice} with a
23989 value greater than @code{0.0}, or use the corresponding @option{-T}
23990 binder option, or set the @code{pragma Task_Dispatching_Policy
23991 (Round_Robin_Within_Priorities)}.
23992
23993 @c *******************************
23994 @node Example of Binder Output File
23995 @appendix Example of Binder Output File
23996
23997 @noindent
23998 This Appendix displays the source code for @command{gnatbind}'s output
23999 file generated for a simple ``Hello World'' program.
24000 Comments have been added for clarification purposes.
24001
24002 @smallexample @c adanocomment
24003 @iftex
24004 @leftskip=0cm
24005 @end iftex
24006 -- The package is called Ada_Main unless this name is actually used
24007 -- as a unit name in the partition, in which case some other unique
24008 -- name is used.
24009
24010 with System;
24011 package ada_main is
24012
24013 Elab_Final_Code : Integer;
24014 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
24015
24016 -- The main program saves the parameters (argument count,
24017 -- argument values, environment pointer) in global variables
24018 -- for later access by other units including
24019 -- Ada.Command_Line.
24020
24021 gnat_argc : Integer;
24022 gnat_argv : System.Address;
24023 gnat_envp : System.Address;
24024
24025 -- The actual variables are stored in a library routine. This
24026 -- is useful for some shared library situations, where there
24027 -- are problems if variables are not in the library.
24028
24029 pragma Import (C, gnat_argc);
24030 pragma Import (C, gnat_argv);
24031 pragma Import (C, gnat_envp);
24032
24033 -- The exit status is similarly an external location
24034
24035 gnat_exit_status : Integer;
24036 pragma Import (C, gnat_exit_status);
24037
24038 GNAT_Version : constant String :=
24039 "GNAT Version: 6.0.0w (20061115)";
24040 pragma Export (C, GNAT_Version, "__gnat_version");
24041
24042 -- This is the generated adafinal routine that performs
24043 -- finalization at the end of execution. In the case where
24044 -- Ada is the main program, this main program makes a call
24045 -- to adafinal at program termination.
24046
24047 procedure adafinal;
24048 pragma Export (C, adafinal, "adafinal");
24049
24050 -- This is the generated adainit routine that performs
24051 -- initialization at the start of execution. In the case
24052 -- where Ada is the main program, this main program makes
24053 -- a call to adainit at program startup.
24054
24055 procedure adainit;
24056 pragma Export (C, adainit, "adainit");
24057
24058 -- This routine is called at the start of execution. It is
24059 -- a dummy routine that is used by the debugger to breakpoint
24060 -- at the start of execution.
24061
24062 procedure Break_Start;
24063 pragma Import (C, Break_Start, "__gnat_break_start");
24064
24065 -- This is the actual generated main program (it would be
24066 -- suppressed if the no main program switch were used). As
24067 -- required by standard system conventions, this program has
24068 -- the external name main.
24069
24070 function main
24071 (argc : Integer;
24072 argv : System.Address;
24073 envp : System.Address)
24074 return Integer;
24075 pragma Export (C, main, "main");
24076
24077 -- The following set of constants give the version
24078 -- identification values for every unit in the bound
24079 -- partition. This identification is computed from all
24080 -- dependent semantic units, and corresponds to the
24081 -- string that would be returned by use of the
24082 -- Body_Version or Version attributes.
24083
24084 type Version_32 is mod 2 ** 32;
24085 u00001 : constant Version_32 := 16#7880BEB3#;
24086 u00002 : constant Version_32 := 16#0D24CBD0#;
24087 u00003 : constant Version_32 := 16#3283DBEB#;
24088 u00004 : constant Version_32 := 16#2359F9ED#;
24089 u00005 : constant Version_32 := 16#664FB847#;
24090 u00006 : constant Version_32 := 16#68E803DF#;
24091 u00007 : constant Version_32 := 16#5572E604#;
24092 u00008 : constant Version_32 := 16#46B173D8#;
24093 u00009 : constant Version_32 := 16#156A40CF#;
24094 u00010 : constant Version_32 := 16#033DABE0#;
24095 u00011 : constant Version_32 := 16#6AB38FEA#;
24096 u00012 : constant Version_32 := 16#22B6217D#;
24097 u00013 : constant Version_32 := 16#68A22947#;
24098 u00014 : constant Version_32 := 16#18CC4A56#;
24099 u00015 : constant Version_32 := 16#08258E1B#;
24100 u00016 : constant Version_32 := 16#367D5222#;
24101 u00017 : constant Version_32 := 16#20C9ECA4#;
24102 u00018 : constant Version_32 := 16#50D32CB6#;
24103 u00019 : constant Version_32 := 16#39A8BB77#;
24104 u00020 : constant Version_32 := 16#5CF8FA2B#;
24105 u00021 : constant Version_32 := 16#2F1EB794#;
24106 u00022 : constant Version_32 := 16#31AB6444#;
24107 u00023 : constant Version_32 := 16#1574B6E9#;
24108 u00024 : constant Version_32 := 16#5109C189#;
24109 u00025 : constant Version_32 := 16#56D770CD#;
24110 u00026 : constant Version_32 := 16#02F9DE3D#;
24111 u00027 : constant Version_32 := 16#08AB6B2C#;
24112 u00028 : constant Version_32 := 16#3FA37670#;
24113 u00029 : constant Version_32 := 16#476457A0#;
24114 u00030 : constant Version_32 := 16#731E1B6E#;
24115 u00031 : constant Version_32 := 16#23C2E789#;
24116 u00032 : constant Version_32 := 16#0F1BD6A1#;
24117 u00033 : constant Version_32 := 16#7C25DE96#;
24118 u00034 : constant Version_32 := 16#39ADFFA2#;
24119 u00035 : constant Version_32 := 16#571DE3E7#;
24120 u00036 : constant Version_32 := 16#5EB646AB#;
24121 u00037 : constant Version_32 := 16#4249379B#;
24122 u00038 : constant Version_32 := 16#0357E00A#;
24123 u00039 : constant Version_32 := 16#3784FB72#;
24124 u00040 : constant Version_32 := 16#2E723019#;
24125 u00041 : constant Version_32 := 16#623358EA#;
24126 u00042 : constant Version_32 := 16#107F9465#;
24127 u00043 : constant Version_32 := 16#6843F68A#;
24128 u00044 : constant Version_32 := 16#63305874#;
24129 u00045 : constant Version_32 := 16#31E56CE1#;
24130 u00046 : constant Version_32 := 16#02917970#;
24131 u00047 : constant Version_32 := 16#6CCBA70E#;
24132 u00048 : constant Version_32 := 16#41CD4204#;
24133 u00049 : constant Version_32 := 16#572E3F58#;
24134 u00050 : constant Version_32 := 16#20729FF5#;
24135 u00051 : constant Version_32 := 16#1D4F93E8#;
24136 u00052 : constant Version_32 := 16#30B2EC3D#;
24137 u00053 : constant Version_32 := 16#34054F96#;
24138 u00054 : constant Version_32 := 16#5A199860#;
24139 u00055 : constant Version_32 := 16#0E7F912B#;
24140 u00056 : constant Version_32 := 16#5760634A#;
24141 u00057 : constant Version_32 := 16#5D851835#;
24142
24143 -- The following Export pragmas export the version numbers
24144 -- with symbolic names ending in B (for body) or S
24145 -- (for spec) so that they can be located in a link. The
24146 -- information provided here is sufficient to track down
24147 -- the exact versions of units used in a given build.
24148
24149 pragma Export (C, u00001, "helloB");
24150 pragma Export (C, u00002, "system__standard_libraryB");
24151 pragma Export (C, u00003, "system__standard_libraryS");
24152 pragma Export (C, u00004, "adaS");
24153 pragma Export (C, u00005, "ada__text_ioB");
24154 pragma Export (C, u00006, "ada__text_ioS");
24155 pragma Export (C, u00007, "ada__exceptionsB");
24156 pragma Export (C, u00008, "ada__exceptionsS");
24157 pragma Export (C, u00009, "gnatS");
24158 pragma Export (C, u00010, "gnat__heap_sort_aB");
24159 pragma Export (C, u00011, "gnat__heap_sort_aS");
24160 pragma Export (C, u00012, "systemS");
24161 pragma Export (C, u00013, "system__exception_tableB");
24162 pragma Export (C, u00014, "system__exception_tableS");
24163 pragma Export (C, u00015, "gnat__htableB");
24164 pragma Export (C, u00016, "gnat__htableS");
24165 pragma Export (C, u00017, "system__exceptionsS");
24166 pragma Export (C, u00018, "system__machine_state_operationsB");
24167 pragma Export (C, u00019, "system__machine_state_operationsS");
24168 pragma Export (C, u00020, "system__machine_codeS");
24169 pragma Export (C, u00021, "system__storage_elementsB");
24170 pragma Export (C, u00022, "system__storage_elementsS");
24171 pragma Export (C, u00023, "system__secondary_stackB");
24172 pragma Export (C, u00024, "system__secondary_stackS");
24173 pragma Export (C, u00025, "system__parametersB");
24174 pragma Export (C, u00026, "system__parametersS");
24175 pragma Export (C, u00027, "system__soft_linksB");
24176 pragma Export (C, u00028, "system__soft_linksS");
24177 pragma Export (C, u00029, "system__stack_checkingB");
24178 pragma Export (C, u00030, "system__stack_checkingS");
24179 pragma Export (C, u00031, "system__tracebackB");
24180 pragma Export (C, u00032, "system__tracebackS");
24181 pragma Export (C, u00033, "ada__streamsS");
24182 pragma Export (C, u00034, "ada__tagsB");
24183 pragma Export (C, u00035, "ada__tagsS");
24184 pragma Export (C, u00036, "system__string_opsB");
24185 pragma Export (C, u00037, "system__string_opsS");
24186 pragma Export (C, u00038, "interfacesS");
24187 pragma Export (C, u00039, "interfaces__c_streamsB");
24188 pragma Export (C, u00040, "interfaces__c_streamsS");
24189 pragma Export (C, u00041, "system__file_ioB");
24190 pragma Export (C, u00042, "system__file_ioS");
24191 pragma Export (C, u00043, "ada__finalizationB");
24192 pragma Export (C, u00044, "ada__finalizationS");
24193 pragma Export (C, u00045, "system__finalization_rootB");
24194 pragma Export (C, u00046, "system__finalization_rootS");
24195 pragma Export (C, u00047, "system__finalization_implementationB");
24196 pragma Export (C, u00048, "system__finalization_implementationS");
24197 pragma Export (C, u00049, "system__string_ops_concat_3B");
24198 pragma Export (C, u00050, "system__string_ops_concat_3S");
24199 pragma Export (C, u00051, "system__stream_attributesB");
24200 pragma Export (C, u00052, "system__stream_attributesS");
24201 pragma Export (C, u00053, "ada__io_exceptionsS");
24202 pragma Export (C, u00054, "system__unsigned_typesS");
24203 pragma Export (C, u00055, "system__file_control_blockS");
24204 pragma Export (C, u00056, "ada__finalization__list_controllerB");
24205 pragma Export (C, u00057, "ada__finalization__list_controllerS");
24206
24207 -- BEGIN ELABORATION ORDER
24208 -- ada (spec)
24209 -- gnat (spec)
24210 -- gnat.heap_sort_a (spec)
24211 -- gnat.heap_sort_a (body)
24212 -- gnat.htable (spec)
24213 -- gnat.htable (body)
24214 -- interfaces (spec)
24215 -- system (spec)
24216 -- system.machine_code (spec)
24217 -- system.parameters (spec)
24218 -- system.parameters (body)
24219 -- interfaces.c_streams (spec)
24220 -- interfaces.c_streams (body)
24221 -- system.standard_library (spec)
24222 -- ada.exceptions (spec)
24223 -- system.exception_table (spec)
24224 -- system.exception_table (body)
24225 -- ada.io_exceptions (spec)
24226 -- system.exceptions (spec)
24227 -- system.storage_elements (spec)
24228 -- system.storage_elements (body)
24229 -- system.machine_state_operations (spec)
24230 -- system.machine_state_operations (body)
24231 -- system.secondary_stack (spec)
24232 -- system.stack_checking (spec)
24233 -- system.soft_links (spec)
24234 -- system.soft_links (body)
24235 -- system.stack_checking (body)
24236 -- system.secondary_stack (body)
24237 -- system.standard_library (body)
24238 -- system.string_ops (spec)
24239 -- system.string_ops (body)
24240 -- ada.tags (spec)
24241 -- ada.tags (body)
24242 -- ada.streams (spec)
24243 -- system.finalization_root (spec)
24244 -- system.finalization_root (body)
24245 -- system.string_ops_concat_3 (spec)
24246 -- system.string_ops_concat_3 (body)
24247 -- system.traceback (spec)
24248 -- system.traceback (body)
24249 -- ada.exceptions (body)
24250 -- system.unsigned_types (spec)
24251 -- system.stream_attributes (spec)
24252 -- system.stream_attributes (body)
24253 -- system.finalization_implementation (spec)
24254 -- system.finalization_implementation (body)
24255 -- ada.finalization (spec)
24256 -- ada.finalization (body)
24257 -- ada.finalization.list_controller (spec)
24258 -- ada.finalization.list_controller (body)
24259 -- system.file_control_block (spec)
24260 -- system.file_io (spec)
24261 -- system.file_io (body)
24262 -- ada.text_io (spec)
24263 -- ada.text_io (body)
24264 -- hello (body)
24265 -- END ELABORATION ORDER
24266
24267 end ada_main;
24268
24269 -- The following source file name pragmas allow the generated file
24270 -- names to be unique for different main programs. They are needed
24271 -- since the package name will always be Ada_Main.
24272
24273 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
24274 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
24275
24276 -- Generated package body for Ada_Main starts here
24277
24278 package body ada_main is
24279
24280 -- The actual finalization is performed by calling the
24281 -- library routine in System.Standard_Library.Adafinal
24282
24283 procedure Do_Finalize;
24284 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
24285
24286 -------------
24287 -- adainit --
24288 -------------
24289
24290 @findex adainit
24291 procedure adainit is
24292
24293 -- These booleans are set to True once the associated unit has
24294 -- been elaborated. It is also used to avoid elaborating the
24295 -- same unit twice.
24296
24297 E040 : Boolean;
24298 pragma Import (Ada, E040, "interfaces__c_streams_E");
24299
24300 E008 : Boolean;
24301 pragma Import (Ada, E008, "ada__exceptions_E");
24302
24303 E014 : Boolean;
24304 pragma Import (Ada, E014, "system__exception_table_E");
24305
24306 E053 : Boolean;
24307 pragma Import (Ada, E053, "ada__io_exceptions_E");
24308
24309 E017 : Boolean;
24310 pragma Import (Ada, E017, "system__exceptions_E");
24311
24312 E024 : Boolean;
24313 pragma Import (Ada, E024, "system__secondary_stack_E");
24314
24315 E030 : Boolean;
24316 pragma Import (Ada, E030, "system__stack_checking_E");
24317
24318 E028 : Boolean;
24319 pragma Import (Ada, E028, "system__soft_links_E");
24320
24321 E035 : Boolean;
24322 pragma Import (Ada, E035, "ada__tags_E");
24323
24324 E033 : Boolean;
24325 pragma Import (Ada, E033, "ada__streams_E");
24326
24327 E046 : Boolean;
24328 pragma Import (Ada, E046, "system__finalization_root_E");
24329
24330 E048 : Boolean;
24331 pragma Import (Ada, E048, "system__finalization_implementation_E");
24332
24333 E044 : Boolean;
24334 pragma Import (Ada, E044, "ada__finalization_E");
24335
24336 E057 : Boolean;
24337 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
24338
24339 E055 : Boolean;
24340 pragma Import (Ada, E055, "system__file_control_block_E");
24341
24342 E042 : Boolean;
24343 pragma Import (Ada, E042, "system__file_io_E");
24344
24345 E006 : Boolean;
24346 pragma Import (Ada, E006, "ada__text_io_E");
24347
24348 -- Set_Globals is a library routine that stores away the
24349 -- value of the indicated set of global values in global
24350 -- variables within the library.
24351
24352 procedure Set_Globals
24353 (Main_Priority : Integer;
24354 Time_Slice_Value : Integer;
24355 WC_Encoding : Character;
24356 Locking_Policy : Character;
24357 Queuing_Policy : Character;
24358 Task_Dispatching_Policy : Character;
24359 Adafinal : System.Address;
24360 Unreserve_All_Interrupts : Integer;
24361 Exception_Tracebacks : Integer);
24362 @findex __gnat_set_globals
24363 pragma Import (C, Set_Globals, "__gnat_set_globals");
24364
24365 -- SDP_Table_Build is a library routine used to build the
24366 -- exception tables. See unit Ada.Exceptions in files
24367 -- a-except.ads/adb for full details of how zero cost
24368 -- exception handling works. This procedure, the call to
24369 -- it, and the two following tables are all omitted if the
24370 -- build is in longjmp/setjmp exception mode.
24371
24372 @findex SDP_Table_Build
24373 @findex Zero Cost Exceptions
24374 procedure SDP_Table_Build
24375 (SDP_Addresses : System.Address;
24376 SDP_Count : Natural;
24377 Elab_Addresses : System.Address;
24378 Elab_Addr_Count : Natural);
24379 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
24380
24381 -- Table of Unit_Exception_Table addresses. Used for zero
24382 -- cost exception handling to build the top level table.
24383
24384 ST : aliased constant array (1 .. 23) of System.Address := (
24385 Hello'UET_Address,
24386 Ada.Text_Io'UET_Address,
24387 Ada.Exceptions'UET_Address,
24388 Gnat.Heap_Sort_A'UET_Address,
24389 System.Exception_Table'UET_Address,
24390 System.Machine_State_Operations'UET_Address,
24391 System.Secondary_Stack'UET_Address,
24392 System.Parameters'UET_Address,
24393 System.Soft_Links'UET_Address,
24394 System.Stack_Checking'UET_Address,
24395 System.Traceback'UET_Address,
24396 Ada.Streams'UET_Address,
24397 Ada.Tags'UET_Address,
24398 System.String_Ops'UET_Address,
24399 Interfaces.C_Streams'UET_Address,
24400 System.File_Io'UET_Address,
24401 Ada.Finalization'UET_Address,
24402 System.Finalization_Root'UET_Address,
24403 System.Finalization_Implementation'UET_Address,
24404 System.String_Ops_Concat_3'UET_Address,
24405 System.Stream_Attributes'UET_Address,
24406 System.File_Control_Block'UET_Address,
24407 Ada.Finalization.List_Controller'UET_Address);
24408
24409 -- Table of addresses of elaboration routines. Used for
24410 -- zero cost exception handling to make sure these
24411 -- addresses are included in the top level procedure
24412 -- address table.
24413
24414 EA : aliased constant array (1 .. 23) of System.Address := (
24415 adainit'Code_Address,
24416 Do_Finalize'Code_Address,
24417 Ada.Exceptions'Elab_Spec'Address,
24418 System.Exceptions'Elab_Spec'Address,
24419 Interfaces.C_Streams'Elab_Spec'Address,
24420 System.Exception_Table'Elab_Body'Address,
24421 Ada.Io_Exceptions'Elab_Spec'Address,
24422 System.Stack_Checking'Elab_Spec'Address,
24423 System.Soft_Links'Elab_Body'Address,
24424 System.Secondary_Stack'Elab_Body'Address,
24425 Ada.Tags'Elab_Spec'Address,
24426 Ada.Tags'Elab_Body'Address,
24427 Ada.Streams'Elab_Spec'Address,
24428 System.Finalization_Root'Elab_Spec'Address,
24429 Ada.Exceptions'Elab_Body'Address,
24430 System.Finalization_Implementation'Elab_Spec'Address,
24431 System.Finalization_Implementation'Elab_Body'Address,
24432 Ada.Finalization'Elab_Spec'Address,
24433 Ada.Finalization.List_Controller'Elab_Spec'Address,
24434 System.File_Control_Block'Elab_Spec'Address,
24435 System.File_Io'Elab_Body'Address,
24436 Ada.Text_Io'Elab_Spec'Address,
24437 Ada.Text_Io'Elab_Body'Address);
24438
24439 -- Start of processing for adainit
24440
24441 begin
24442
24443 -- Call SDP_Table_Build to build the top level procedure
24444 -- table for zero cost exception handling (omitted in
24445 -- longjmp/setjmp mode).
24446
24447 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
24448
24449 -- Call Set_Globals to record various information for
24450 -- this partition. The values are derived by the binder
24451 -- from information stored in the ali files by the compiler.
24452
24453 @findex __gnat_set_globals
24454 Set_Globals
24455 (Main_Priority => -1,
24456 -- Priority of main program, -1 if no pragma Priority used
24457
24458 Time_Slice_Value => -1,
24459 -- Time slice from Time_Slice pragma, -1 if none used
24460
24461 WC_Encoding => 'b',
24462 -- Wide_Character encoding used, default is brackets
24463
24464 Locking_Policy => ' ',
24465 -- Locking_Policy used, default of space means not
24466 -- specified, otherwise it is the first character of
24467 -- the policy name.
24468
24469 Queuing_Policy => ' ',
24470 -- Queuing_Policy used, default of space means not
24471 -- specified, otherwise it is the first character of
24472 -- the policy name.
24473
24474 Task_Dispatching_Policy => ' ',
24475 -- Task_Dispatching_Policy used, default of space means
24476 -- not specified, otherwise first character of the
24477 -- policy name.
24478
24479 Adafinal => System.Null_Address,
24480 -- Address of Adafinal routine, not used anymore
24481
24482 Unreserve_All_Interrupts => 0,
24483 -- Set true if pragma Unreserve_All_Interrupts was used
24484
24485 Exception_Tracebacks => 0);
24486 -- Indicates if exception tracebacks are enabled
24487
24488 Elab_Final_Code := 1;
24489
24490 -- Now we have the elaboration calls for all units in the partition.
24491 -- The Elab_Spec and Elab_Body attributes generate references to the
24492 -- implicit elaboration procedures generated by the compiler for
24493 -- each unit that requires elaboration.
24494
24495 if not E040 then
24496 Interfaces.C_Streams'Elab_Spec;
24497 end if;
24498 E040 := True;
24499 if not E008 then
24500 Ada.Exceptions'Elab_Spec;
24501 end if;
24502 if not E014 then
24503 System.Exception_Table'Elab_Body;
24504 E014 := True;
24505 end if;
24506 if not E053 then
24507 Ada.Io_Exceptions'Elab_Spec;
24508 E053 := True;
24509 end if;
24510 if not E017 then
24511 System.Exceptions'Elab_Spec;
24512 E017 := True;
24513 end if;
24514 if not E030 then
24515 System.Stack_Checking'Elab_Spec;
24516 end if;
24517 if not E028 then
24518 System.Soft_Links'Elab_Body;
24519 E028 := True;
24520 end if;
24521 E030 := True;
24522 if not E024 then
24523 System.Secondary_Stack'Elab_Body;
24524 E024 := True;
24525 end if;
24526 if not E035 then
24527 Ada.Tags'Elab_Spec;
24528 end if;
24529 if not E035 then
24530 Ada.Tags'Elab_Body;
24531 E035 := True;
24532 end if;
24533 if not E033 then
24534 Ada.Streams'Elab_Spec;
24535 E033 := True;
24536 end if;
24537 if not E046 then
24538 System.Finalization_Root'Elab_Spec;
24539 end if;
24540 E046 := True;
24541 if not E008 then
24542 Ada.Exceptions'Elab_Body;
24543 E008 := True;
24544 end if;
24545 if not E048 then
24546 System.Finalization_Implementation'Elab_Spec;
24547 end if;
24548 if not E048 then
24549 System.Finalization_Implementation'Elab_Body;
24550 E048 := True;
24551 end if;
24552 if not E044 then
24553 Ada.Finalization'Elab_Spec;
24554 end if;
24555 E044 := True;
24556 if not E057 then
24557 Ada.Finalization.List_Controller'Elab_Spec;
24558 end if;
24559 E057 := True;
24560 if not E055 then
24561 System.File_Control_Block'Elab_Spec;
24562 E055 := True;
24563 end if;
24564 if not E042 then
24565 System.File_Io'Elab_Body;
24566 E042 := True;
24567 end if;
24568 if not E006 then
24569 Ada.Text_Io'Elab_Spec;
24570 end if;
24571 if not E006 then
24572 Ada.Text_Io'Elab_Body;
24573 E006 := True;
24574 end if;
24575
24576 Elab_Final_Code := 0;
24577 end adainit;
24578
24579 --------------
24580 -- adafinal --
24581 --------------
24582
24583 @findex adafinal
24584 procedure adafinal is
24585 begin
24586 Do_Finalize;
24587 end adafinal;
24588
24589 ----------
24590 -- main --
24591 ----------
24592
24593 -- main is actually a function, as in the ANSI C standard,
24594 -- defined to return the exit status. The three parameters
24595 -- are the argument count, argument values and environment
24596 -- pointer.
24597
24598 @findex Main Program
24599 function main
24600 (argc : Integer;
24601 argv : System.Address;
24602 envp : System.Address)
24603 return Integer
24604 is
24605 -- The initialize routine performs low level system
24606 -- initialization using a standard library routine which
24607 -- sets up signal handling and performs any other
24608 -- required setup. The routine can be found in file
24609 -- a-init.c.
24610
24611 @findex __gnat_initialize
24612 procedure initialize;
24613 pragma Import (C, initialize, "__gnat_initialize");
24614
24615 -- The finalize routine performs low level system
24616 -- finalization using a standard library routine. The
24617 -- routine is found in file a-final.c and in the standard
24618 -- distribution is a dummy routine that does nothing, so
24619 -- really this is a hook for special user finalization.
24620
24621 @findex __gnat_finalize
24622 procedure finalize;
24623 pragma Import (C, finalize, "__gnat_finalize");
24624
24625 -- We get to the main program of the partition by using
24626 -- pragma Import because if we try to with the unit and
24627 -- call it Ada style, then not only do we waste time
24628 -- recompiling it, but also, we don't really know the right
24629 -- switches (e.g.@: identifier character set) to be used
24630 -- to compile it.
24631
24632 procedure Ada_Main_Program;
24633 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
24634
24635 -- Start of processing for main
24636
24637 begin
24638 -- Save global variables
24639
24640 gnat_argc := argc;
24641 gnat_argv := argv;
24642 gnat_envp := envp;
24643
24644 -- Call low level system initialization
24645
24646 Initialize;
24647
24648 -- Call our generated Ada initialization routine
24649
24650 adainit;
24651
24652 -- This is the point at which we want the debugger to get
24653 -- control
24654
24655 Break_Start;
24656
24657 -- Now we call the main program of the partition
24658
24659 Ada_Main_Program;
24660
24661 -- Perform Ada finalization
24662
24663 adafinal;
24664
24665 -- Perform low level system finalization
24666
24667 Finalize;
24668
24669 -- Return the proper exit status
24670 return (gnat_exit_status);
24671 end;
24672
24673 -- This section is entirely comments, so it has no effect on the
24674 -- compilation of the Ada_Main package. It provides the list of
24675 -- object files and linker options, as well as some standard
24676 -- libraries needed for the link. The gnatlink utility parses
24677 -- this b~hello.adb file to read these comment lines to generate
24678 -- the appropriate command line arguments for the call to the
24679 -- system linker. The BEGIN/END lines are used for sentinels for
24680 -- this parsing operation.
24681
24682 -- The exact file names will of course depend on the environment,
24683 -- host/target and location of files on the host system.
24684
24685 @findex Object file list
24686 -- BEGIN Object file/option list
24687 -- ./hello.o
24688 -- -L./
24689 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
24690 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
24691 -- END Object file/option list
24692
24693 end ada_main;
24694 @end smallexample
24695
24696 @noindent
24697 The Ada code in the above example is exactly what is generated by the
24698 binder. We have added comments to more clearly indicate the function
24699 of each part of the generated @code{Ada_Main} package.
24700
24701 The code is standard Ada in all respects, and can be processed by any
24702 tools that handle Ada. In particular, it is possible to use the debugger
24703 in Ada mode to debug the generated @code{Ada_Main} package. For example,
24704 suppose that for reasons that you do not understand, your program is crashing
24705 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
24706 you can place a breakpoint on the call:
24707
24708 @smallexample @c ada
24709 Ada.Text_Io'Elab_Body;
24710 @end smallexample
24711
24712 @noindent
24713 and trace the elaboration routine for this package to find out where
24714 the problem might be (more usually of course you would be debugging
24715 elaboration code in your own application).
24716
24717 @node Elaboration Order Handling in GNAT
24718 @appendix Elaboration Order Handling in GNAT
24719 @cindex Order of elaboration
24720 @cindex Elaboration control
24721
24722 @menu
24723 * Elaboration Code::
24724 * Checking the Elaboration Order::
24725 * Controlling the Elaboration Order::
24726 * Controlling Elaboration in GNAT - Internal Calls::
24727 * Controlling Elaboration in GNAT - External Calls::
24728 * Default Behavior in GNAT - Ensuring Safety::
24729 * Treatment of Pragma Elaborate::
24730 * Elaboration Issues for Library Tasks::
24731 * Mixing Elaboration Models::
24732 * What to Do If the Default Elaboration Behavior Fails::
24733 * Elaboration for Dispatching Calls::
24734 * Summary of Procedures for Elaboration Control::
24735 * Other Elaboration Order Considerations::
24736 @end menu
24737
24738 @noindent
24739 This chapter describes the handling of elaboration code in Ada and
24740 in GNAT, and discusses how the order of elaboration of program units can
24741 be controlled in GNAT, either automatically or with explicit programming
24742 features.
24743
24744 @node Elaboration Code
24745 @section Elaboration Code
24746
24747 @noindent
24748 Ada provides rather general mechanisms for executing code at elaboration
24749 time, that is to say before the main program starts executing. Such code arises
24750 in three contexts:
24751
24752 @table @asis
24753 @item Initializers for variables.
24754 Variables declared at the library level, in package specs or bodies, can
24755 require initialization that is performed at elaboration time, as in:
24756 @smallexample @c ada
24757 @cartouche
24758 Sqrt_Half : Float := Sqrt (0.5);
24759 @end cartouche
24760 @end smallexample
24761
24762 @item Package initialization code
24763 Code in a @code{BEGIN-END} section at the outer level of a package body is
24764 executed as part of the package body elaboration code.
24765
24766 @item Library level task allocators
24767 Tasks that are declared using task allocators at the library level
24768 start executing immediately and hence can execute at elaboration time.
24769 @end table
24770
24771 @noindent
24772 Subprogram calls are possible in any of these contexts, which means that
24773 any arbitrary part of the program may be executed as part of the elaboration
24774 code. It is even possible to write a program which does all its work at
24775 elaboration time, with a null main program, although stylistically this
24776 would usually be considered an inappropriate way to structure
24777 a program.
24778
24779 An important concern arises in the context of elaboration code:
24780 we have to be sure that it is executed in an appropriate order. What we
24781 have is a series of elaboration code sections, potentially one section
24782 for each unit in the program. It is important that these execute
24783 in the correct order. Correctness here means that, taking the above
24784 example of the declaration of @code{Sqrt_Half},
24785 if some other piece of
24786 elaboration code references @code{Sqrt_Half},
24787 then it must run after the
24788 section of elaboration code that contains the declaration of
24789 @code{Sqrt_Half}.
24790
24791 There would never be any order of elaboration problem if we made a rule
24792 that whenever you @code{with} a unit, you must elaborate both the spec and body
24793 of that unit before elaborating the unit doing the @code{with}'ing:
24794
24795 @smallexample @c ada
24796 @group
24797 @cartouche
24798 with Unit_1;
24799 package Unit_2 is @dots{}
24800 @end cartouche
24801 @end group
24802 @end smallexample
24803
24804 @noindent
24805 would require that both the body and spec of @code{Unit_1} be elaborated
24806 before the spec of @code{Unit_2}. However, a rule like that would be far too
24807 restrictive. In particular, it would make it impossible to have routines
24808 in separate packages that were mutually recursive.
24809
24810 You might think that a clever enough compiler could look at the actual
24811 elaboration code and determine an appropriate correct order of elaboration,
24812 but in the general case, this is not possible. Consider the following
24813 example.
24814
24815 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
24816 that references
24817 the variable @code{Sqrt_1}, which is declared in the elaboration code
24818 of the body of @code{Unit_1}:
24819
24820 @smallexample @c ada
24821 @cartouche
24822 Sqrt_1 : Float := Sqrt (0.1);
24823 @end cartouche
24824 @end smallexample
24825
24826 @noindent
24827 The elaboration code of the body of @code{Unit_1} also contains:
24828
24829 @smallexample @c ada
24830 @group
24831 @cartouche
24832 if expression_1 = 1 then
24833 Q := Unit_2.Func_2;
24834 end if;
24835 @end cartouche
24836 @end group
24837 @end smallexample
24838
24839 @noindent
24840 @code{Unit_2} is exactly parallel,
24841 it has a procedure @code{Func_2} that references
24842 the variable @code{Sqrt_2}, which is declared in the elaboration code of
24843 the body @code{Unit_2}:
24844
24845 @smallexample @c ada
24846 @cartouche
24847 Sqrt_2 : Float := Sqrt (0.1);
24848 @end cartouche
24849 @end smallexample
24850
24851 @noindent
24852 The elaboration code of the body of @code{Unit_2} also contains:
24853
24854 @smallexample @c ada
24855 @group
24856 @cartouche
24857 if expression_2 = 2 then
24858 Q := Unit_1.Func_1;
24859 end if;
24860 @end cartouche
24861 @end group
24862 @end smallexample
24863
24864 @noindent
24865 Now the question is, which of the following orders of elaboration is
24866 acceptable:
24867
24868 @smallexample
24869 @group
24870 Spec of Unit_1
24871 Spec of Unit_2
24872 Body of Unit_1
24873 Body of Unit_2
24874 @end group
24875 @end smallexample
24876
24877 @noindent
24878 or
24879
24880 @smallexample
24881 @group
24882 Spec of Unit_2
24883 Spec of Unit_1
24884 Body of Unit_2
24885 Body of Unit_1
24886 @end group
24887 @end smallexample
24888
24889 @noindent
24890 If you carefully analyze the flow here, you will see that you cannot tell
24891 at compile time the answer to this question.
24892 If @code{expression_1} is not equal to 1,
24893 and @code{expression_2} is not equal to 2,
24894 then either order is acceptable, because neither of the function calls is
24895 executed. If both tests evaluate to true, then neither order is acceptable
24896 and in fact there is no correct order.
24897
24898 If one of the two expressions is true, and the other is false, then one
24899 of the above orders is correct, and the other is incorrect. For example,
24900 if @code{expression_1} /= 1 and @code{expression_2} = 2,
24901 then the call to @code{Func_1}
24902 will occur, but not the call to @code{Func_2.}
24903 This means that it is essential
24904 to elaborate the body of @code{Unit_1} before
24905 the body of @code{Unit_2}, so the first
24906 order of elaboration is correct and the second is wrong.
24907
24908 By making @code{expression_1} and @code{expression_2}
24909 depend on input data, or perhaps
24910 the time of day, we can make it impossible for the compiler or binder
24911 to figure out which of these expressions will be true, and hence it
24912 is impossible to guarantee a safe order of elaboration at run time.
24913
24914 @node Checking the Elaboration Order
24915 @section Checking the Elaboration Order
24916
24917 @noindent
24918 In some languages that involve the same kind of elaboration problems,
24919 e.g.@: Java and C++, the programmer is expected to worry about these
24920 ordering problems himself, and it is common to
24921 write a program in which an incorrect elaboration order gives
24922 surprising results, because it references variables before they
24923 are initialized.
24924 Ada is designed to be a safe language, and a programmer-beware approach is
24925 clearly not sufficient. Consequently, the language provides three lines
24926 of defense:
24927
24928 @table @asis
24929 @item Standard rules
24930 Some standard rules restrict the possible choice of elaboration
24931 order. In particular, if you @code{with} a unit, then its spec is always
24932 elaborated before the unit doing the @code{with}. Similarly, a parent
24933 spec is always elaborated before the child spec, and finally
24934 a spec is always elaborated before its corresponding body.
24935
24936 @item Dynamic elaboration checks
24937 @cindex Elaboration checks
24938 @cindex Checks, elaboration
24939 Dynamic checks are made at run time, so that if some entity is accessed
24940 before it is elaborated (typically by means of a subprogram call)
24941 then the exception (@code{Program_Error}) is raised.
24942
24943 @item Elaboration control
24944 Facilities are provided for the programmer to specify the desired order
24945 of elaboration.
24946 @end table
24947
24948 Let's look at these facilities in more detail. First, the rules for
24949 dynamic checking. One possible rule would be simply to say that the
24950 exception is raised if you access a variable which has not yet been
24951 elaborated. The trouble with this approach is that it could require
24952 expensive checks on every variable reference. Instead Ada has two
24953 rules which are a little more restrictive, but easier to check, and
24954 easier to state:
24955
24956 @table @asis
24957 @item Restrictions on calls
24958 A subprogram can only be called at elaboration time if its body
24959 has been elaborated. The rules for elaboration given above guarantee
24960 that the spec of the subprogram has been elaborated before the
24961 call, but not the body. If this rule is violated, then the
24962 exception @code{Program_Error} is raised.
24963
24964 @item Restrictions on instantiations
24965 A generic unit can only be instantiated if the body of the generic
24966 unit has been elaborated. Again, the rules for elaboration given above
24967 guarantee that the spec of the generic unit has been elaborated
24968 before the instantiation, but not the body. If this rule is
24969 violated, then the exception @code{Program_Error} is raised.
24970 @end table
24971
24972 @noindent
24973 The idea is that if the body has been elaborated, then any variables
24974 it references must have been elaborated; by checking for the body being
24975 elaborated we guarantee that none of its references causes any
24976 trouble. As we noted above, this is a little too restrictive, because a
24977 subprogram that has no non-local references in its body may in fact be safe
24978 to call. However, it really would be unsafe to rely on this, because
24979 it would mean that the caller was aware of details of the implementation
24980 in the body. This goes against the basic tenets of Ada.
24981
24982 A plausible implementation can be described as follows.
24983 A Boolean variable is associated with each subprogram
24984 and each generic unit. This variable is initialized to False, and is set to
24985 True at the point body is elaborated. Every call or instantiation checks the
24986 variable, and raises @code{Program_Error} if the variable is False.
24987
24988 Note that one might think that it would be good enough to have one Boolean
24989 variable for each package, but that would not deal with cases of trying
24990 to call a body in the same package as the call
24991 that has not been elaborated yet.
24992 Of course a compiler may be able to do enough analysis to optimize away
24993 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
24994 does such optimizations, but still the easiest conceptual model is to
24995 think of there being one variable per subprogram.
24996
24997 @node Controlling the Elaboration Order
24998 @section Controlling the Elaboration Order
24999
25000 @noindent
25001 In the previous section we discussed the rules in Ada which ensure
25002 that @code{Program_Error} is raised if an incorrect elaboration order is
25003 chosen. This prevents erroneous executions, but we need mechanisms to
25004 specify a correct execution and avoid the exception altogether.
25005 To achieve this, Ada provides a number of features for controlling
25006 the order of elaboration. We discuss these features in this section.
25007
25008 First, there are several ways of indicating to the compiler that a given
25009 unit has no elaboration problems:
25010
25011 @table @asis
25012 @item packages that do not require a body
25013 A library package that does not require a body does not permit
25014 a body (this rule was introduced in Ada 95).
25015 Thus if we have a such a package, as in:
25016
25017 @smallexample @c ada
25018 @group
25019 @cartouche
25020 package Definitions is
25021 generic
25022 type m is new integer;
25023 package Subp is
25024 type a is array (1 .. 10) of m;
25025 type b is array (1 .. 20) of m;
25026 end Subp;
25027 end Definitions;
25028 @end cartouche
25029 @end group
25030 @end smallexample
25031
25032 @noindent
25033 A package that @code{with}'s @code{Definitions} may safely instantiate
25034 @code{Definitions.Subp} because the compiler can determine that there
25035 definitely is no package body to worry about in this case
25036
25037 @item pragma Pure
25038 @cindex pragma Pure
25039 @findex Pure
25040 Places sufficient restrictions on a unit to guarantee that
25041 no call to any subprogram in the unit can result in an
25042 elaboration problem. This means that the compiler does not need
25043 to worry about the point of elaboration of such units, and in
25044 particular, does not need to check any calls to any subprograms
25045 in this unit.
25046
25047 @item pragma Preelaborate
25048 @findex Preelaborate
25049 @cindex pragma Preelaborate
25050 This pragma places slightly less stringent restrictions on a unit than
25051 does pragma Pure,
25052 but these restrictions are still sufficient to ensure that there
25053 are no elaboration problems with any calls to the unit.
25054
25055 @item pragma Elaborate_Body
25056 @findex Elaborate_Body
25057 @cindex pragma Elaborate_Body
25058 This pragma requires that the body of a unit be elaborated immediately
25059 after its spec. Suppose a unit @code{A} has such a pragma,
25060 and unit @code{B} does
25061 a @code{with} of unit @code{A}. Recall that the standard rules require
25062 the spec of unit @code{A}
25063 to be elaborated before the @code{with}'ing unit; given the pragma in
25064 @code{A}, we also know that the body of @code{A}
25065 will be elaborated before @code{B}, so
25066 that calls to @code{A} are safe and do not need a check.
25067 @end table
25068
25069 @noindent
25070 Note that,
25071 unlike pragma @code{Pure} and pragma @code{Preelaborate},
25072 the use of
25073 @code{Elaborate_Body} does not guarantee that the program is
25074 free of elaboration problems, because it may not be possible
25075 to satisfy the requested elaboration order.
25076 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
25077 If a programmer
25078 marks @code{Unit_1} as @code{Elaborate_Body},
25079 and not @code{Unit_2,} then the order of
25080 elaboration will be:
25081
25082 @smallexample
25083 @group
25084 Spec of Unit_2
25085 Spec of Unit_1
25086 Body of Unit_1
25087 Body of Unit_2
25088 @end group
25089 @end smallexample
25090
25091 @noindent
25092 Now that means that the call to @code{Func_1} in @code{Unit_2}
25093 need not be checked,
25094 it must be safe. But the call to @code{Func_2} in
25095 @code{Unit_1} may still fail if
25096 @code{Expression_1} is equal to 1,
25097 and the programmer must still take
25098 responsibility for this not being the case.
25099
25100 If all units carry a pragma @code{Elaborate_Body}, then all problems are
25101 eliminated, except for calls entirely within a body, which are
25102 in any case fully under programmer control. However, using the pragma
25103 everywhere is not always possible.
25104 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
25105 we marked both of them as having pragma @code{Elaborate_Body}, then
25106 clearly there would be no possible elaboration order.
25107
25108 The above pragmas allow a server to guarantee safe use by clients, and
25109 clearly this is the preferable approach. Consequently a good rule
25110 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
25111 and if this is not possible,
25112 mark them as @code{Elaborate_Body} if possible.
25113 As we have seen, there are situations where neither of these
25114 three pragmas can be used.
25115 So we also provide methods for clients to control the
25116 order of elaboration of the servers on which they depend:
25117
25118 @table @asis
25119 @item pragma Elaborate (unit)
25120 @findex Elaborate
25121 @cindex pragma Elaborate
25122 This pragma is placed in the context clause, after a @code{with} clause,
25123 and it requires that the body of the named unit be elaborated before
25124 the unit in which the pragma occurs. The idea is to use this pragma
25125 if the current unit calls at elaboration time, directly or indirectly,
25126 some subprogram in the named unit.
25127
25128 @item pragma Elaborate_All (unit)
25129 @findex Elaborate_All
25130 @cindex pragma Elaborate_All
25131 This is a stronger version of the Elaborate pragma. Consider the
25132 following example:
25133
25134 @smallexample
25135 Unit A @code{with}'s unit B and calls B.Func in elab code
25136 Unit B @code{with}'s unit C, and B.Func calls C.Func
25137 @end smallexample
25138
25139 @noindent
25140 Now if we put a pragma @code{Elaborate (B)}
25141 in unit @code{A}, this ensures that the
25142 body of @code{B} is elaborated before the call, but not the
25143 body of @code{C}, so
25144 the call to @code{C.Func} could still cause @code{Program_Error} to
25145 be raised.
25146
25147 The effect of a pragma @code{Elaborate_All} is stronger, it requires
25148 not only that the body of the named unit be elaborated before the
25149 unit doing the @code{with}, but also the bodies of all units that the
25150 named unit uses, following @code{with} links transitively. For example,
25151 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
25152 then it requires
25153 not only that the body of @code{B} be elaborated before @code{A},
25154 but also the
25155 body of @code{C}, because @code{B} @code{with}'s @code{C}.
25156 @end table
25157
25158 @noindent
25159 We are now in a position to give a usage rule in Ada for avoiding
25160 elaboration problems, at least if dynamic dispatching and access to
25161 subprogram values are not used. We will handle these cases separately
25162 later.
25163
25164 The rule is simple. If a unit has elaboration code that can directly or
25165 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
25166 a generic package in a @code{with}'ed unit,
25167 then if the @code{with}'ed unit does not have
25168 pragma @code{Pure} or @code{Preelaborate}, then the client should have
25169 a pragma @code{Elaborate_All}
25170 for the @code{with}'ed unit. By following this rule a client is
25171 assured that calls can be made without risk of an exception.
25172
25173 For generic subprogram instantiations, the rule can be relaxed to
25174 require only a pragma @code{Elaborate} since elaborating the body
25175 of a subprogram cannot cause any transitive elaboration (we are
25176 not calling the subprogram in this case, just elaborating its
25177 declaration).
25178
25179 If this rule is not followed, then a program may be in one of four
25180 states:
25181
25182 @table @asis
25183 @item No order exists
25184 No order of elaboration exists which follows the rules, taking into
25185 account any @code{Elaborate}, @code{Elaborate_All},
25186 or @code{Elaborate_Body} pragmas. In
25187 this case, an Ada compiler must diagnose the situation at bind
25188 time, and refuse to build an executable program.
25189
25190 @item One or more orders exist, all incorrect
25191 One or more acceptable elaboration orders exist, and all of them
25192 generate an elaboration order problem. In this case, the binder
25193 can build an executable program, but @code{Program_Error} will be raised
25194 when the program is run.
25195
25196 @item Several orders exist, some right, some incorrect
25197 One or more acceptable elaboration orders exists, and some of them
25198 work, and some do not. The programmer has not controlled
25199 the order of elaboration, so the binder may or may not pick one of
25200 the correct orders, and the program may or may not raise an
25201 exception when it is run. This is the worst case, because it means
25202 that the program may fail when moved to another compiler, or even
25203 another version of the same compiler.
25204
25205 @item One or more orders exists, all correct
25206 One ore more acceptable elaboration orders exist, and all of them
25207 work. In this case the program runs successfully. This state of
25208 affairs can be guaranteed by following the rule we gave above, but
25209 may be true even if the rule is not followed.
25210 @end table
25211
25212 @noindent
25213 Note that one additional advantage of following our rules on the use
25214 of @code{Elaborate} and @code{Elaborate_All}
25215 is that the program continues to stay in the ideal (all orders OK) state
25216 even if maintenance
25217 changes some bodies of some units. Conversely, if a program that does
25218 not follow this rule happens to be safe at some point, this state of affairs
25219 may deteriorate silently as a result of maintenance changes.
25220
25221 You may have noticed that the above discussion did not mention
25222 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
25223 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
25224 code in the body makes calls to some other unit, so it is still necessary
25225 to use @code{Elaborate_All} on such units.
25226
25227 @node Controlling Elaboration in GNAT - Internal Calls
25228 @section Controlling Elaboration in GNAT - Internal Calls
25229
25230 @noindent
25231 In the case of internal calls, i.e., calls within a single package, the
25232 programmer has full control over the order of elaboration, and it is up
25233 to the programmer to elaborate declarations in an appropriate order. For
25234 example writing:
25235
25236 @smallexample @c ada
25237 @group
25238 @cartouche
25239 function One return Float;
25240
25241 Q : Float := One;
25242
25243 function One return Float is
25244 begin
25245 return 1.0;
25246 end One;
25247 @end cartouche
25248 @end group
25249 @end smallexample
25250
25251 @noindent
25252 will obviously raise @code{Program_Error} at run time, because function
25253 One will be called before its body is elaborated. In this case GNAT will
25254 generate a warning that the call will raise @code{Program_Error}:
25255
25256 @smallexample
25257 @group
25258 @cartouche
25259 1. procedure y is
25260 2. function One return Float;
25261 3.
25262 4. Q : Float := One;
25263 |
25264 >>> warning: cannot call "One" before body is elaborated
25265 >>> warning: Program_Error will be raised at run time
25266
25267 5.
25268 6. function One return Float is
25269 7. begin
25270 8. return 1.0;
25271 9. end One;
25272 10.
25273 11. begin
25274 12. null;
25275 13. end;
25276 @end cartouche
25277 @end group
25278 @end smallexample
25279
25280 @noindent
25281 Note that in this particular case, it is likely that the call is safe, because
25282 the function @code{One} does not access any global variables.
25283 Nevertheless in Ada, we do not want the validity of the check to depend on
25284 the contents of the body (think about the separate compilation case), so this
25285 is still wrong, as we discussed in the previous sections.
25286
25287 The error is easily corrected by rearranging the declarations so that the
25288 body of @code{One} appears before the declaration containing the call
25289 (note that in Ada 95 and Ada 2005,
25290 declarations can appear in any order, so there is no restriction that
25291 would prevent this reordering, and if we write:
25292
25293 @smallexample @c ada
25294 @group
25295 @cartouche
25296 function One return Float;
25297
25298 function One return Float is
25299 begin
25300 return 1.0;
25301 end One;
25302
25303 Q : Float := One;
25304 @end cartouche
25305 @end group
25306 @end smallexample
25307
25308 @noindent
25309 then all is well, no warning is generated, and no
25310 @code{Program_Error} exception
25311 will be raised.
25312 Things are more complicated when a chain of subprograms is executed:
25313
25314 @smallexample @c ada
25315 @group
25316 @cartouche
25317 function A return Integer;
25318 function B return Integer;
25319 function C return Integer;
25320
25321 function B return Integer is begin return A; end;
25322 function C return Integer is begin return B; end;
25323
25324 X : Integer := C;
25325
25326 function A return Integer is begin return 1; end;
25327 @end cartouche
25328 @end group
25329 @end smallexample
25330
25331 @noindent
25332 Now the call to @code{C}
25333 at elaboration time in the declaration of @code{X} is correct, because
25334 the body of @code{C} is already elaborated,
25335 and the call to @code{B} within the body of
25336 @code{C} is correct, but the call
25337 to @code{A} within the body of @code{B} is incorrect, because the body
25338 of @code{A} has not been elaborated, so @code{Program_Error}
25339 will be raised on the call to @code{A}.
25340 In this case GNAT will generate a
25341 warning that @code{Program_Error} may be
25342 raised at the point of the call. Let's look at the warning:
25343
25344 @smallexample
25345 @group
25346 @cartouche
25347 1. procedure x is
25348 2. function A return Integer;
25349 3. function B return Integer;
25350 4. function C return Integer;
25351 5.
25352 6. function B return Integer is begin return A; end;
25353 |
25354 >>> warning: call to "A" before body is elaborated may
25355 raise Program_Error
25356 >>> warning: "B" called at line 7
25357 >>> warning: "C" called at line 9
25358
25359 7. function C return Integer is begin return B; end;
25360 8.
25361 9. X : Integer := C;
25362 10.
25363 11. function A return Integer is begin return 1; end;
25364 12.
25365 13. begin
25366 14. null;
25367 15. end;
25368 @end cartouche
25369 @end group
25370 @end smallexample
25371
25372 @noindent
25373 Note that the message here says ``may raise'', instead of the direct case,
25374 where the message says ``will be raised''. That's because whether
25375 @code{A} is
25376 actually called depends in general on run-time flow of control.
25377 For example, if the body of @code{B} said
25378
25379 @smallexample @c ada
25380 @group
25381 @cartouche
25382 function B return Integer is
25383 begin
25384 if some-condition-depending-on-input-data then
25385 return A;
25386 else
25387 return 1;
25388 end if;
25389 end B;
25390 @end cartouche
25391 @end group
25392 @end smallexample
25393
25394 @noindent
25395 then we could not know until run time whether the incorrect call to A would
25396 actually occur, so @code{Program_Error} might
25397 or might not be raised. It is possible for a compiler to
25398 do a better job of analyzing bodies, to
25399 determine whether or not @code{Program_Error}
25400 might be raised, but it certainly
25401 couldn't do a perfect job (that would require solving the halting problem
25402 and is provably impossible), and because this is a warning anyway, it does
25403 not seem worth the effort to do the analysis. Cases in which it
25404 would be relevant are rare.
25405
25406 In practice, warnings of either of the forms given
25407 above will usually correspond to
25408 real errors, and should be examined carefully and eliminated.
25409 In the rare case where a warning is bogus, it can be suppressed by any of
25410 the following methods:
25411
25412 @itemize @bullet
25413 @item
25414 Compile with the @option{-gnatws} switch set
25415
25416 @item
25417 Suppress @code{Elaboration_Check} for the called subprogram
25418
25419 @item
25420 Use pragma @code{Warnings_Off} to turn warnings off for the call
25421 @end itemize
25422
25423 @noindent
25424 For the internal elaboration check case,
25425 GNAT by default generates the
25426 necessary run-time checks to ensure
25427 that @code{Program_Error} is raised if any
25428 call fails an elaboration check. Of course this can only happen if a
25429 warning has been issued as described above. The use of pragma
25430 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
25431 some of these checks, meaning that it may be possible (but is not
25432 guaranteed) for a program to be able to call a subprogram whose body
25433 is not yet elaborated, without raising a @code{Program_Error} exception.
25434
25435 @node Controlling Elaboration in GNAT - External Calls
25436 @section Controlling Elaboration in GNAT - External Calls
25437
25438 @noindent
25439 The previous section discussed the case in which the execution of a
25440 particular thread of elaboration code occurred entirely within a
25441 single unit. This is the easy case to handle, because a programmer
25442 has direct and total control over the order of elaboration, and
25443 furthermore, checks need only be generated in cases which are rare
25444 and which the compiler can easily detect.
25445 The situation is more complex when separate compilation is taken into account.
25446 Consider the following:
25447
25448 @smallexample @c ada
25449 @cartouche
25450 @group
25451 package Math is
25452 function Sqrt (Arg : Float) return Float;
25453 end Math;
25454
25455 package body Math is
25456 function Sqrt (Arg : Float) return Float is
25457 begin
25458 @dots{}
25459 end Sqrt;
25460 end Math;
25461 @end group
25462 @group
25463 with Math;
25464 package Stuff is
25465 X : Float := Math.Sqrt (0.5);
25466 end Stuff;
25467
25468 with Stuff;
25469 procedure Main is
25470 begin
25471 @dots{}
25472 end Main;
25473 @end group
25474 @end cartouche
25475 @end smallexample
25476
25477 @noindent
25478 where @code{Main} is the main program. When this program is executed, the
25479 elaboration code must first be executed, and one of the jobs of the
25480 binder is to determine the order in which the units of a program are
25481 to be elaborated. In this case we have four units: the spec and body
25482 of @code{Math},
25483 the spec of @code{Stuff} and the body of @code{Main}).
25484 In what order should the four separate sections of elaboration code
25485 be executed?
25486
25487 There are some restrictions in the order of elaboration that the binder
25488 can choose. In particular, if unit U has a @code{with}
25489 for a package @code{X}, then you
25490 are assured that the spec of @code{X}
25491 is elaborated before U , but you are
25492 not assured that the body of @code{X}
25493 is elaborated before U.
25494 This means that in the above case, the binder is allowed to choose the
25495 order:
25496
25497 @smallexample
25498 spec of Math
25499 spec of Stuff
25500 body of Math
25501 body of Main
25502 @end smallexample
25503
25504 @noindent
25505 but that's not good, because now the call to @code{Math.Sqrt}
25506 that happens during
25507 the elaboration of the @code{Stuff}
25508 spec happens before the body of @code{Math.Sqrt} is
25509 elaborated, and hence causes @code{Program_Error} exception to be raised.
25510 At first glance, one might say that the binder is misbehaving, because
25511 obviously you want to elaborate the body of something you @code{with}
25512 first, but
25513 that is not a general rule that can be followed in all cases. Consider
25514
25515 @smallexample @c ada
25516 @group
25517 @cartouche
25518 package X is @dots{}
25519
25520 package Y is @dots{}
25521
25522 with X;
25523 package body Y is @dots{}
25524
25525 with Y;
25526 package body X is @dots{}
25527 @end cartouche
25528 @end group
25529 @end smallexample
25530
25531 @noindent
25532 This is a common arrangement, and, apart from the order of elaboration
25533 problems that might arise in connection with elaboration code, this works fine.
25534 A rule that says that you must first elaborate the body of anything you
25535 @code{with} cannot work in this case:
25536 the body of @code{X} @code{with}'s @code{Y},
25537 which means you would have to
25538 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
25539 which means
25540 you have to elaborate the body of @code{X} first, but @dots{} and we have a
25541 loop that cannot be broken.
25542
25543 It is true that the binder can in many cases guess an order of elaboration
25544 that is unlikely to cause a @code{Program_Error}
25545 exception to be raised, and it tries to do so (in the
25546 above example of @code{Math/Stuff/Spec}, the GNAT binder will
25547 by default
25548 elaborate the body of @code{Math} right after its spec, so all will be well).
25549
25550 However, a program that blindly relies on the binder to be helpful can
25551 get into trouble, as we discussed in the previous sections, so
25552 GNAT
25553 provides a number of facilities for assisting the programmer in
25554 developing programs that are robust with respect to elaboration order.
25555
25556 @node Default Behavior in GNAT - Ensuring Safety
25557 @section Default Behavior in GNAT - Ensuring Safety
25558
25559 @noindent
25560 The default behavior in GNAT ensures elaboration safety. In its
25561 default mode GNAT implements the
25562 rule we previously described as the right approach. Let's restate it:
25563
25564 @itemize
25565 @item
25566 @emph{If a unit has elaboration code that can directly or indirectly make a
25567 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
25568 package in a @code{with}'ed unit, then if the @code{with}'ed unit
25569 does not have pragma @code{Pure} or
25570 @code{Preelaborate}, then the client should have an
25571 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
25572
25573 @emph{In the case of instantiating a generic subprogram, it is always
25574 sufficient to have only an @code{Elaborate} pragma for the
25575 @code{with}'ed unit.}
25576 @end itemize
25577
25578 @noindent
25579 By following this rule a client is assured that calls and instantiations
25580 can be made without risk of an exception.
25581
25582 In this mode GNAT traces all calls that are potentially made from
25583 elaboration code, and puts in any missing implicit @code{Elaborate}
25584 and @code{Elaborate_All} pragmas.
25585 The advantage of this approach is that no elaboration problems
25586 are possible if the binder can find an elaboration order that is
25587 consistent with these implicit @code{Elaborate} and
25588 @code{Elaborate_All} pragmas. The
25589 disadvantage of this approach is that no such order may exist.
25590
25591 If the binder does not generate any diagnostics, then it means that it has
25592 found an elaboration order that is guaranteed to be safe. However, the binder
25593 may still be relying on implicitly generated @code{Elaborate} and
25594 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
25595 guaranteed.
25596
25597 If it is important to guarantee portability, then the compilations should
25598 use the
25599 @option{-gnatwl}
25600 (warn on elaboration problems) switch. This will cause warning messages
25601 to be generated indicating the missing @code{Elaborate} and
25602 @code{Elaborate_All} pragmas.
25603 Consider the following source program:
25604
25605 @smallexample @c ada
25606 @group
25607 @cartouche
25608 with k;
25609 package j is
25610 m : integer := k.r;
25611 end;
25612 @end cartouche
25613 @end group
25614 @end smallexample
25615
25616 @noindent
25617 where it is clear that there
25618 should be a pragma @code{Elaborate_All}
25619 for unit @code{k}. An implicit pragma will be generated, and it is
25620 likely that the binder will be able to honor it. However, if you want
25621 to port this program to some other Ada compiler than GNAT.
25622 it is safer to include the pragma explicitly in the source. If this
25623 unit is compiled with the
25624 @option{-gnatwl}
25625 switch, then the compiler outputs a warning:
25626
25627 @smallexample
25628 @group
25629 @cartouche
25630 1. with k;
25631 2. package j is
25632 3. m : integer := k.r;
25633 |
25634 >>> warning: call to "r" may raise Program_Error
25635 >>> warning: missing pragma Elaborate_All for "k"
25636
25637 4. end;
25638 @end cartouche
25639 @end group
25640 @end smallexample
25641
25642 @noindent
25643 and these warnings can be used as a guide for supplying manually
25644 the missing pragmas. It is usually a bad idea to use this warning
25645 option during development. That's because it will warn you when
25646 you need to put in a pragma, but cannot warn you when it is time
25647 to take it out. So the use of pragma @code{Elaborate_All} may lead to
25648 unnecessary dependencies and even false circularities.
25649
25650 This default mode is more restrictive than the Ada Reference
25651 Manual, and it is possible to construct programs which will compile
25652 using the dynamic model described there, but will run into a
25653 circularity using the safer static model we have described.
25654
25655 Of course any Ada compiler must be able to operate in a mode
25656 consistent with the requirements of the Ada Reference Manual,
25657 and in particular must have the capability of implementing the
25658 standard dynamic model of elaboration with run-time checks.
25659
25660 In GNAT, this standard mode can be achieved either by the use of
25661 the @option{-gnatE} switch on the compiler (@command{gcc} or
25662 @command{gnatmake}) command, or by the use of the configuration pragma:
25663
25664 @smallexample @c ada
25665 pragma Elaboration_Checks (DYNAMIC);
25666 @end smallexample
25667
25668 @noindent
25669 Either approach will cause the unit affected to be compiled using the
25670 standard dynamic run-time elaboration checks described in the Ada
25671 Reference Manual. The static model is generally preferable, since it
25672 is clearly safer to rely on compile and link time checks rather than
25673 run-time checks. However, in the case of legacy code, it may be
25674 difficult to meet the requirements of the static model. This
25675 issue is further discussed in
25676 @ref{What to Do If the Default Elaboration Behavior Fails}.
25677
25678 Note that the static model provides a strict subset of the allowed
25679 behavior and programs of the Ada Reference Manual, so if you do
25680 adhere to the static model and no circularities exist,
25681 then you are assured that your program will
25682 work using the dynamic model, providing that you remove any
25683 pragma Elaborate statements from the source.
25684
25685 @node Treatment of Pragma Elaborate
25686 @section Treatment of Pragma Elaborate
25687 @cindex Pragma Elaborate
25688
25689 @noindent
25690 The use of @code{pragma Elaborate}
25691 should generally be avoided in Ada 95 and Ada 2005 programs,
25692 since there is no guarantee that transitive calls
25693 will be properly handled. Indeed at one point, this pragma was placed
25694 in Annex J (Obsolescent Features), on the grounds that it is never useful.
25695
25696 Now that's a bit restrictive. In practice, the case in which
25697 @code{pragma Elaborate} is useful is when the caller knows that there
25698 are no transitive calls, or that the called unit contains all necessary
25699 transitive @code{pragma Elaborate} statements, and legacy code often
25700 contains such uses.
25701
25702 Strictly speaking the static mode in GNAT should ignore such pragmas,
25703 since there is no assurance at compile time that the necessary safety
25704 conditions are met. In practice, this would cause GNAT to be incompatible
25705 with correctly written Ada 83 code that had all necessary
25706 @code{pragma Elaborate} statements in place. Consequently, we made the
25707 decision that GNAT in its default mode will believe that if it encounters
25708 a @code{pragma Elaborate} then the programmer knows what they are doing,
25709 and it will trust that no elaboration errors can occur.
25710
25711 The result of this decision is two-fold. First to be safe using the
25712 static mode, you should remove all @code{pragma Elaborate} statements.
25713 Second, when fixing circularities in existing code, you can selectively
25714 use @code{pragma Elaborate} statements to convince the static mode of
25715 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
25716 statement.
25717
25718 When using the static mode with @option{-gnatwl}, any use of
25719 @code{pragma Elaborate} will generate a warning about possible
25720 problems.
25721
25722 @node Elaboration Issues for Library Tasks
25723 @section Elaboration Issues for Library Tasks
25724 @cindex Library tasks, elaboration issues
25725 @cindex Elaboration of library tasks
25726
25727 @noindent
25728 In this section we examine special elaboration issues that arise for
25729 programs that declare library level tasks.
25730
25731 Generally the model of execution of an Ada program is that all units are
25732 elaborated, and then execution of the program starts. However, the
25733 declaration of library tasks definitely does not fit this model. The
25734 reason for this is that library tasks start as soon as they are declared
25735 (more precisely, as soon as the statement part of the enclosing package
25736 body is reached), that is to say before elaboration
25737 of the program is complete. This means that if such a task calls a
25738 subprogram, or an entry in another task, the callee may or may not be
25739 elaborated yet, and in the standard
25740 Reference Manual model of dynamic elaboration checks, you can even
25741 get timing dependent Program_Error exceptions, since there can be
25742 a race between the elaboration code and the task code.
25743
25744 The static model of elaboration in GNAT seeks to avoid all such
25745 dynamic behavior, by being conservative, and the conservative
25746 approach in this particular case is to assume that all the code
25747 in a task body is potentially executed at elaboration time if
25748 a task is declared at the library level.
25749
25750 This can definitely result in unexpected circularities. Consider
25751 the following example
25752
25753 @smallexample @c ada
25754 package Decls is
25755 task Lib_Task is
25756 entry Start;
25757 end Lib_Task;
25758
25759 type My_Int is new Integer;
25760
25761 function Ident (M : My_Int) return My_Int;
25762 end Decls;
25763
25764 with Utils;
25765 package body Decls is
25766 task body Lib_Task is
25767 begin
25768 accept Start;
25769 Utils.Put_Val (2);
25770 end Lib_Task;
25771
25772 function Ident (M : My_Int) return My_Int is
25773 begin
25774 return M;
25775 end Ident;
25776 end Decls;
25777
25778 with Decls;
25779 package Utils is
25780 procedure Put_Val (Arg : Decls.My_Int);
25781 end Utils;
25782
25783 with Text_IO;
25784 package body Utils is
25785 procedure Put_Val (Arg : Decls.My_Int) is
25786 begin
25787 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
25788 end Put_Val;
25789 end Utils;
25790
25791 with Decls;
25792 procedure Main is
25793 begin
25794 Decls.Lib_Task.Start;
25795 end;
25796 @end smallexample
25797
25798 @noindent
25799 If the above example is compiled in the default static elaboration
25800 mode, then a circularity occurs. The circularity comes from the call
25801 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
25802 this call occurs in elaboration code, we need an implicit pragma
25803 @code{Elaborate_All} for @code{Utils}. This means that not only must
25804 the spec and body of @code{Utils} be elaborated before the body
25805 of @code{Decls}, but also the spec and body of any unit that is
25806 @code{with'ed} by the body of @code{Utils} must also be elaborated before
25807 the body of @code{Decls}. This is the transitive implication of
25808 pragma @code{Elaborate_All} and it makes sense, because in general
25809 the body of @code{Put_Val} might have a call to something in a
25810 @code{with'ed} unit.
25811
25812 In this case, the body of Utils (actually its spec) @code{with's}
25813 @code{Decls}. Unfortunately this means that the body of @code{Decls}
25814 must be elaborated before itself, in case there is a call from the
25815 body of @code{Utils}.
25816
25817 Here is the exact chain of events we are worrying about:
25818
25819 @enumerate
25820 @item
25821 In the body of @code{Decls} a call is made from within the body of a library
25822 task to a subprogram in the package @code{Utils}. Since this call may
25823 occur at elaboration time (given that the task is activated at elaboration
25824 time), we have to assume the worst, i.e., that the
25825 call does happen at elaboration time.
25826
25827 @item
25828 This means that the body and spec of @code{Util} must be elaborated before
25829 the body of @code{Decls} so that this call does not cause an access before
25830 elaboration.
25831
25832 @item
25833 Within the body of @code{Util}, specifically within the body of
25834 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
25835 by this package.
25836
25837 @item
25838 One such @code{with}'ed package is package @code{Decls}, so there
25839 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
25840 In fact there is such a call in this example, but we would have to
25841 assume that there was such a call even if it were not there, since
25842 we are not supposed to write the body of @code{Decls} knowing what
25843 is in the body of @code{Utils}; certainly in the case of the
25844 static elaboration model, the compiler does not know what is in
25845 other bodies and must assume the worst.
25846
25847 @item
25848 This means that the spec and body of @code{Decls} must also be
25849 elaborated before we elaborate the unit containing the call, but
25850 that unit is @code{Decls}! This means that the body of @code{Decls}
25851 must be elaborated before itself, and that's a circularity.
25852 @end enumerate
25853
25854 @noindent
25855 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
25856 the body of @code{Decls} you will get a true Ada Reference Manual
25857 circularity that makes the program illegal.
25858
25859 In practice, we have found that problems with the static model of
25860 elaboration in existing code often arise from library tasks, so
25861 we must address this particular situation.
25862
25863 Note that if we compile and run the program above, using the dynamic model of
25864 elaboration (that is to say use the @option{-gnatE} switch),
25865 then it compiles, binds,
25866 links, and runs, printing the expected result of 2. Therefore in some sense
25867 the circularity here is only apparent, and we need to capture
25868 the properties of this program that distinguish it from other library-level
25869 tasks that have real elaboration problems.
25870
25871 We have four possible answers to this question:
25872
25873 @itemize @bullet
25874
25875 @item
25876 Use the dynamic model of elaboration.
25877
25878 If we use the @option{-gnatE} switch, then as noted above, the program works.
25879 Why is this? If we examine the task body, it is apparent that the task cannot
25880 proceed past the
25881 @code{accept} statement until after elaboration has been completed, because
25882 the corresponding entry call comes from the main program, not earlier.
25883 This is why the dynamic model works here. But that's really giving
25884 up on a precise analysis, and we prefer to take this approach only if we cannot
25885 solve the
25886 problem in any other manner. So let us examine two ways to reorganize
25887 the program to avoid the potential elaboration problem.
25888
25889 @item
25890 Split library tasks into separate packages.
25891
25892 Write separate packages, so that library tasks are isolated from
25893 other declarations as much as possible. Let us look at a variation on
25894 the above program.
25895
25896 @smallexample @c ada
25897 package Decls1 is
25898 task Lib_Task is
25899 entry Start;
25900 end Lib_Task;
25901 end Decls1;
25902
25903 with Utils;
25904 package body Decls1 is
25905 task body Lib_Task is
25906 begin
25907 accept Start;
25908 Utils.Put_Val (2);
25909 end Lib_Task;
25910 end Decls1;
25911
25912 package Decls2 is
25913 type My_Int is new Integer;
25914 function Ident (M : My_Int) return My_Int;
25915 end Decls2;
25916
25917 with Utils;
25918 package body Decls2 is
25919 function Ident (M : My_Int) return My_Int is
25920 begin
25921 return M;
25922 end Ident;
25923 end Decls2;
25924
25925 with Decls2;
25926 package Utils is
25927 procedure Put_Val (Arg : Decls2.My_Int);
25928 end Utils;
25929
25930 with Text_IO;
25931 package body Utils is
25932 procedure Put_Val (Arg : Decls2.My_Int) is
25933 begin
25934 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
25935 end Put_Val;
25936 end Utils;
25937
25938 with Decls1;
25939 procedure Main is
25940 begin
25941 Decls1.Lib_Task.Start;
25942 end;
25943 @end smallexample
25944
25945 @noindent
25946 All we have done is to split @code{Decls} into two packages, one
25947 containing the library task, and one containing everything else. Now
25948 there is no cycle, and the program compiles, binds, links and executes
25949 using the default static model of elaboration.
25950
25951 @item
25952 Declare separate task types.
25953
25954 A significant part of the problem arises because of the use of the
25955 single task declaration form. This means that the elaboration of
25956 the task type, and the elaboration of the task itself (i.e.@: the
25957 creation of the task) happen at the same time. A good rule
25958 of style in Ada is to always create explicit task types. By
25959 following the additional step of placing task objects in separate
25960 packages from the task type declaration, many elaboration problems
25961 are avoided. Here is another modified example of the example program:
25962
25963 @smallexample @c ada
25964 package Decls is
25965 task type Lib_Task_Type is
25966 entry Start;
25967 end Lib_Task_Type;
25968
25969 type My_Int is new Integer;
25970
25971 function Ident (M : My_Int) return My_Int;
25972 end Decls;
25973
25974 with Utils;
25975 package body Decls is
25976 task body Lib_Task_Type is
25977 begin
25978 accept Start;
25979 Utils.Put_Val (2);
25980 end Lib_Task_Type;
25981
25982 function Ident (M : My_Int) return My_Int is
25983 begin
25984 return M;
25985 end Ident;
25986 end Decls;
25987
25988 with Decls;
25989 package Utils is
25990 procedure Put_Val (Arg : Decls.My_Int);
25991 end Utils;
25992
25993 with Text_IO;
25994 package body Utils is
25995 procedure Put_Val (Arg : Decls.My_Int) is
25996 begin
25997 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
25998 end Put_Val;
25999 end Utils;
26000
26001 with Decls;
26002 package Declst is
26003 Lib_Task : Decls.Lib_Task_Type;
26004 end Declst;
26005
26006 with Declst;
26007 procedure Main is
26008 begin
26009 Declst.Lib_Task.Start;
26010 end;
26011 @end smallexample
26012
26013 @noindent
26014 What we have done here is to replace the @code{task} declaration in
26015 package @code{Decls} with a @code{task type} declaration. Then we
26016 introduce a separate package @code{Declst} to contain the actual
26017 task object. This separates the elaboration issues for
26018 the @code{task type}
26019 declaration, which causes no trouble, from the elaboration issues
26020 of the task object, which is also unproblematic, since it is now independent
26021 of the elaboration of @code{Utils}.
26022 This separation of concerns also corresponds to
26023 a generally sound engineering principle of separating declarations
26024 from instances. This version of the program also compiles, binds, links,
26025 and executes, generating the expected output.
26026
26027 @item
26028 Use No_Entry_Calls_In_Elaboration_Code restriction.
26029 @cindex No_Entry_Calls_In_Elaboration_Code
26030
26031 The previous two approaches described how a program can be restructured
26032 to avoid the special problems caused by library task bodies. in practice,
26033 however, such restructuring may be difficult to apply to existing legacy code,
26034 so we must consider solutions that do not require massive rewriting.
26035
26036 Let us consider more carefully why our original sample program works
26037 under the dynamic model of elaboration. The reason is that the code
26038 in the task body blocks immediately on the @code{accept}
26039 statement. Now of course there is nothing to prohibit elaboration
26040 code from making entry calls (for example from another library level task),
26041 so we cannot tell in isolation that
26042 the task will not execute the accept statement during elaboration.
26043
26044 However, in practice it is very unusual to see elaboration code
26045 make any entry calls, and the pattern of tasks starting
26046 at elaboration time and then immediately blocking on @code{accept} or
26047 @code{select} statements is very common. What this means is that
26048 the compiler is being too pessimistic when it analyzes the
26049 whole package body as though it might be executed at elaboration
26050 time.
26051
26052 If we know that the elaboration code contains no entry calls, (a very safe
26053 assumption most of the time, that could almost be made the default
26054 behavior), then we can compile all units of the program under control
26055 of the following configuration pragma:
26056
26057 @smallexample
26058 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
26059 @end smallexample
26060
26061 @noindent
26062 This pragma can be placed in the @file{gnat.adc} file in the usual
26063 manner. If we take our original unmodified program and compile it
26064 in the presence of a @file{gnat.adc} containing the above pragma,
26065 then once again, we can compile, bind, link, and execute, obtaining
26066 the expected result. In the presence of this pragma, the compiler does
26067 not trace calls in a task body, that appear after the first @code{accept}
26068 or @code{select} statement, and therefore does not report a potential
26069 circularity in the original program.
26070
26071 The compiler will check to the extent it can that the above
26072 restriction is not violated, but it is not always possible to do a
26073 complete check at compile time, so it is important to use this
26074 pragma only if the stated restriction is in fact met, that is to say
26075 no task receives an entry call before elaboration of all units is completed.
26076
26077 @end itemize
26078
26079 @node Mixing Elaboration Models
26080 @section Mixing Elaboration Models
26081 @noindent
26082 So far, we have assumed that the entire program is either compiled
26083 using the dynamic model or static model, ensuring consistency. It
26084 is possible to mix the two models, but rules have to be followed
26085 if this mixing is done to ensure that elaboration checks are not
26086 omitted.
26087
26088 The basic rule is that @emph{a unit compiled with the static model cannot
26089 be @code{with'ed} by a unit compiled with the dynamic model}. The
26090 reason for this is that in the static model, a unit assumes that
26091 its clients guarantee to use (the equivalent of) pragma
26092 @code{Elaborate_All} so that no elaboration checks are required
26093 in inner subprograms, and this assumption is violated if the
26094 client is compiled with dynamic checks.
26095
26096 The precise rule is as follows. A unit that is compiled with dynamic
26097 checks can only @code{with} a unit that meets at least one of the
26098 following criteria:
26099
26100 @itemize @bullet
26101
26102 @item
26103 The @code{with'ed} unit is itself compiled with dynamic elaboration
26104 checks (that is with the @option{-gnatE} switch.
26105
26106 @item
26107 The @code{with'ed} unit is an internal GNAT implementation unit from
26108 the System, Interfaces, Ada, or GNAT hierarchies.
26109
26110 @item
26111 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
26112
26113 @item
26114 The @code{with'ing} unit (that is the client) has an explicit pragma
26115 @code{Elaborate_All} for the @code{with'ed} unit.
26116
26117 @end itemize
26118
26119 @noindent
26120 If this rule is violated, that is if a unit with dynamic elaboration
26121 checks @code{with's} a unit that does not meet one of the above four
26122 criteria, then the binder (@code{gnatbind}) will issue a warning
26123 similar to that in the following example:
26124
26125 @smallexample
26126 warning: "x.ads" has dynamic elaboration checks and with's
26127 warning: "y.ads" which has static elaboration checks
26128 @end smallexample
26129
26130 @noindent
26131 These warnings indicate that the rule has been violated, and that as a result
26132 elaboration checks may be missed in the resulting executable file.
26133 This warning may be suppressed using the @option{-ws} binder switch
26134 in the usual manner.
26135
26136 One useful application of this mixing rule is in the case of a subsystem
26137 which does not itself @code{with} units from the remainder of the
26138 application. In this case, the entire subsystem can be compiled with
26139 dynamic checks to resolve a circularity in the subsystem, while
26140 allowing the main application that uses this subsystem to be compiled
26141 using the more reliable default static model.
26142
26143 @node What to Do If the Default Elaboration Behavior Fails
26144 @section What to Do If the Default Elaboration Behavior Fails
26145
26146 @noindent
26147 If the binder cannot find an acceptable order, it outputs detailed
26148 diagnostics. For example:
26149 @smallexample
26150 @group
26151 @iftex
26152 @leftskip=0cm
26153 @end iftex
26154 error: elaboration circularity detected
26155 info: "proc (body)" must be elaborated before "pack (body)"
26156 info: reason: Elaborate_All probably needed in unit "pack (body)"
26157 info: recompile "pack (body)" with -gnatwl
26158 info: for full details
26159 info: "proc (body)"
26160 info: is needed by its spec:
26161 info: "proc (spec)"
26162 info: which is withed by:
26163 info: "pack (body)"
26164 info: "pack (body)" must be elaborated before "proc (body)"
26165 info: reason: pragma Elaborate in unit "proc (body)"
26166 @end group
26167
26168 @end smallexample
26169
26170 @noindent
26171 In this case we have a cycle that the binder cannot break. On the one
26172 hand, there is an explicit pragma Elaborate in @code{proc} for
26173 @code{pack}. This means that the body of @code{pack} must be elaborated
26174 before the body of @code{proc}. On the other hand, there is elaboration
26175 code in @code{pack} that calls a subprogram in @code{proc}. This means
26176 that for maximum safety, there should really be a pragma
26177 Elaborate_All in @code{pack} for @code{proc} which would require that
26178 the body of @code{proc} be elaborated before the body of
26179 @code{pack}. Clearly both requirements cannot be satisfied.
26180 Faced with a circularity of this kind, you have three different options.
26181
26182 @table @asis
26183 @item Fix the program
26184 The most desirable option from the point of view of long-term maintenance
26185 is to rearrange the program so that the elaboration problems are avoided.
26186 One useful technique is to place the elaboration code into separate
26187 child packages. Another is to move some of the initialization code to
26188 explicitly called subprograms, where the program controls the order
26189 of initialization explicitly. Although this is the most desirable option,
26190 it may be impractical and involve too much modification, especially in
26191 the case of complex legacy code.
26192
26193 @item Perform dynamic checks
26194 If the compilations are done using the
26195 @option{-gnatE}
26196 (dynamic elaboration check) switch, then GNAT behaves in a quite different
26197 manner. Dynamic checks are generated for all calls that could possibly result
26198 in raising an exception. With this switch, the compiler does not generate
26199 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
26200 exactly as specified in the @cite{Ada Reference Manual}.
26201 The binder will generate
26202 an executable program that may or may not raise @code{Program_Error}, and then
26203 it is the programmer's job to ensure that it does not raise an exception. Note
26204 that it is important to compile all units with the switch, it cannot be used
26205 selectively.
26206
26207 @item Suppress checks
26208 The drawback of dynamic checks is that they generate a
26209 significant overhead at run time, both in space and time. If you
26210 are absolutely sure that your program cannot raise any elaboration
26211 exceptions, and you still want to use the dynamic elaboration model,
26212 then you can use the configuration pragma
26213 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
26214 example this pragma could be placed in the @file{gnat.adc} file.
26215
26216 @item Suppress checks selectively
26217 When you know that certain calls or instantiations in elaboration code cannot
26218 possibly lead to an elaboration error, and the binder nevertheless complains
26219 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
26220 elaboration circularities, it is possible to remove those warnings locally and
26221 obtain a program that will bind. Clearly this can be unsafe, and it is the
26222 responsibility of the programmer to make sure that the resulting program has no
26223 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
26224 used with different granularity to suppress warnings and break elaboration
26225 circularities:
26226
26227 @itemize @bullet
26228 @item
26229 Place the pragma that names the called subprogram in the declarative part
26230 that contains the call.
26231
26232 @item
26233 Place the pragma in the declarative part, without naming an entity. This
26234 disables warnings on all calls in the corresponding declarative region.
26235
26236 @item
26237 Place the pragma in the package spec that declares the called subprogram,
26238 and name the subprogram. This disables warnings on all elaboration calls to
26239 that subprogram.
26240
26241 @item
26242 Place the pragma in the package spec that declares the called subprogram,
26243 without naming any entity. This disables warnings on all elaboration calls to
26244 all subprograms declared in this spec.
26245
26246 @item Use Pragma Elaborate
26247 As previously described in section @xref{Treatment of Pragma Elaborate},
26248 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
26249 that no elaboration checks are required on calls to the designated unit.
26250 There may be cases in which the caller knows that no transitive calls
26251 can occur, so that a @code{pragma Elaborate} will be sufficient in a
26252 case where @code{pragma Elaborate_All} would cause a circularity.
26253 @end itemize
26254
26255 @noindent
26256 These five cases are listed in order of decreasing safety, and therefore
26257 require increasing programmer care in their application. Consider the
26258 following program:
26259
26260 @smallexample @c adanocomment
26261 package Pack1 is
26262 function F1 return Integer;
26263 X1 : Integer;
26264 end Pack1;
26265
26266 package Pack2 is
26267 function F2 return Integer;
26268 function Pure (x : integer) return integer;
26269 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
26270 -- pragma Suppress (Elaboration_Check); -- (4)
26271 end Pack2;
26272
26273 with Pack2;
26274 package body Pack1 is
26275 function F1 return Integer is
26276 begin
26277 return 100;
26278 end F1;
26279 Val : integer := Pack2.Pure (11); -- Elab. call (1)
26280 begin
26281 declare
26282 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
26283 -- pragma Suppress(Elaboration_Check); -- (2)
26284 begin
26285 X1 := Pack2.F2 + 1; -- Elab. call (2)
26286 end;
26287 end Pack1;
26288
26289 with Pack1;
26290 package body Pack2 is
26291 function F2 return Integer is
26292 begin
26293 return Pack1.F1;
26294 end F2;
26295 function Pure (x : integer) return integer is
26296 begin
26297 return x ** 3 - 3 * x;
26298 end;
26299 end Pack2;
26300
26301 with Pack1, Ada.Text_IO;
26302 procedure Proc3 is
26303 begin
26304 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
26305 end Proc3;
26306 @end smallexample
26307 In the absence of any pragmas, an attempt to bind this program produces
26308 the following diagnostics:
26309 @smallexample
26310 @group
26311 @iftex
26312 @leftskip=.5cm
26313 @end iftex
26314 error: elaboration circularity detected
26315 info: "pack1 (body)" must be elaborated before "pack1 (body)"
26316 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
26317 info: recompile "pack1 (body)" with -gnatwl for full details
26318 info: "pack1 (body)"
26319 info: must be elaborated along with its spec:
26320 info: "pack1 (spec)"
26321 info: which is withed by:
26322 info: "pack2 (body)"
26323 info: which must be elaborated along with its spec:
26324 info: "pack2 (spec)"
26325 info: which is withed by:
26326 info: "pack1 (body)"
26327 @end group
26328 @end smallexample
26329 The sources of the circularity are the two calls to @code{Pack2.Pure} and
26330 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
26331 F2 is safe, even though F2 calls F1, because the call appears after the
26332 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
26333 remove the warning on the call. It is also possible to use pragma (2)
26334 because there are no other potentially unsafe calls in the block.
26335
26336 @noindent
26337 The call to @code{Pure} is safe because this function does not depend on the
26338 state of @code{Pack2}. Therefore any call to this function is safe, and it
26339 is correct to place pragma (3) in the corresponding package spec.
26340
26341 @noindent
26342 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
26343 warnings on all calls to functions declared therein. Note that this is not
26344 necessarily safe, and requires more detailed examination of the subprogram
26345 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
26346 be already elaborated.
26347 @end table
26348
26349 @noindent
26350 It is hard to generalize on which of these four approaches should be
26351 taken. Obviously if it is possible to fix the program so that the default
26352 treatment works, this is preferable, but this may not always be practical.
26353 It is certainly simple enough to use
26354 @option{-gnatE}
26355 but the danger in this case is that, even if the GNAT binder
26356 finds a correct elaboration order, it may not always do so,
26357 and certainly a binder from another Ada compiler might not. A
26358 combination of testing and analysis (for which the warnings generated
26359 with the
26360 @option{-gnatwl}
26361 switch can be useful) must be used to ensure that the program is free
26362 of errors. One switch that is useful in this testing is the
26363 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
26364 switch for
26365 @code{gnatbind}.
26366 Normally the binder tries to find an order that has the best chance
26367 of avoiding elaboration problems. However, if this switch is used, the binder
26368 plays a devil's advocate role, and tries to choose the order that
26369 has the best chance of failing. If your program works even with this
26370 switch, then it has a better chance of being error free, but this is still
26371 not a guarantee.
26372
26373 For an example of this approach in action, consider the C-tests (executable
26374 tests) from the ACVC suite. If these are compiled and run with the default
26375 treatment, then all but one of them succeed without generating any error
26376 diagnostics from the binder. However, there is one test that fails, and
26377 this is not surprising, because the whole point of this test is to ensure
26378 that the compiler can handle cases where it is impossible to determine
26379 a correct order statically, and it checks that an exception is indeed
26380 raised at run time.
26381
26382 This one test must be compiled and run using the
26383 @option{-gnatE}
26384 switch, and then it passes. Alternatively, the entire suite can
26385 be run using this switch. It is never wrong to run with the dynamic
26386 elaboration switch if your code is correct, and we assume that the
26387 C-tests are indeed correct (it is less efficient, but efficiency is
26388 not a factor in running the ACVC tests.)
26389
26390 @node Elaboration for Dispatching Calls
26391 @section Elaboration for Dispatching Calls
26392 @cindex Dispatching calls
26393
26394 @noindent
26395 In rare cases, the static elaboration model fails to prevent
26396 dispatching calls to not-yet-elaborated subprograms. In such cases, we
26397 fall back to run-time checks; premature calls to any primitive
26398 operation of a tagged type before the body of the operation has been
26399 elaborated will raise @code{Program_Error}.
26400
26401 Access-to-subprogram types, however, are handled conservatively, and
26402 do not require run-time checks. This was not true in earlier versions
26403 of the compiler; you can use the @option{-gnatd.U} debug switch to
26404 revert to the old behavior if the new conservative behavior causes
26405 elaboration cycles.
26406
26407 @node Summary of Procedures for Elaboration Control
26408 @section Summary of Procedures for Elaboration Control
26409 @cindex Elaboration control
26410
26411 @noindent
26412 First, compile your program with the default options, using none of
26413 the special elaboration control switches. If the binder successfully
26414 binds your program, then you can be confident that, apart from issues
26415 raised by the use of access-to-subprogram types and dynamic dispatching,
26416 the program is free of elaboration errors. If it is important that the
26417 program be portable, then use the
26418 @option{-gnatwl}
26419 switch to generate warnings about missing @code{Elaborate} or
26420 @code{Elaborate_All} pragmas, and supply the missing pragmas.
26421
26422 If the program fails to bind using the default static elaboration
26423 handling, then you can fix the program to eliminate the binder
26424 message, or recompile the entire program with the
26425 @option{-gnatE} switch to generate dynamic elaboration checks,
26426 and, if you are sure there really are no elaboration problems,
26427 use a global pragma @code{Suppress (Elaboration_Check)}.
26428
26429 @node Other Elaboration Order Considerations
26430 @section Other Elaboration Order Considerations
26431 @noindent
26432 This section has been entirely concerned with the issue of finding a valid
26433 elaboration order, as defined by the Ada Reference Manual. In a case
26434 where several elaboration orders are valid, the task is to find one
26435 of the possible valid elaboration orders (and the static model in GNAT
26436 will ensure that this is achieved).
26437
26438 The purpose of the elaboration rules in the Ada Reference Manual is to
26439 make sure that no entity is accessed before it has been elaborated. For
26440 a subprogram, this means that the spec and body must have been elaborated
26441 before the subprogram is called. For an object, this means that the object
26442 must have been elaborated before its value is read or written. A violation
26443 of either of these two requirements is an access before elaboration order,
26444 and this section has been all about avoiding such errors.
26445
26446 In the case where more than one order of elaboration is possible, in the
26447 sense that access before elaboration errors are avoided, then any one of
26448 the orders is ``correct'' in the sense that it meets the requirements of
26449 the Ada Reference Manual, and no such error occurs.
26450
26451 However, it may be the case for a given program, that there are
26452 constraints on the order of elaboration that come not from consideration
26453 of avoiding elaboration errors, but rather from extra-lingual logic
26454 requirements. Consider this example:
26455
26456 @smallexample @c ada
26457 with Init_Constants;
26458 package Constants is
26459 X : Integer := 0;
26460 Y : Integer := 0;
26461 end Constants;
26462
26463 package Init_Constants is
26464 procedure P; -- require a body
26465 end Init_Constants;
26466
26467 with Constants;
26468 package body Init_Constants is
26469 procedure P is begin null; end;
26470 begin
26471 Constants.X := 3;
26472 Constants.Y := 4;
26473 end Init_Constants;
26474
26475 with Constants;
26476 package Calc is
26477 Z : Integer := Constants.X + Constants.Y;
26478 end Calc;
26479
26480 with Calc;
26481 with Text_IO; use Text_IO;
26482 procedure Main is
26483 begin
26484 Put_Line (Calc.Z'Img);
26485 end Main;
26486 @end smallexample
26487
26488 @noindent
26489 In this example, there is more than one valid order of elaboration. For
26490 example both the following are correct orders:
26491
26492 @smallexample
26493 Init_Constants spec
26494 Constants spec
26495 Calc spec
26496 Init_Constants body
26497 Main body
26498
26499 and
26500
26501 Init_Constants spec
26502 Init_Constants body
26503 Constants spec
26504 Calc spec
26505 Main body
26506 @end smallexample
26507
26508 @noindent
26509 There is no language rule to prefer one or the other, both are correct
26510 from an order of elaboration point of view. But the programmatic effects
26511 of the two orders are very different. In the first, the elaboration routine
26512 of @code{Calc} initializes @code{Z} to zero, and then the main program
26513 runs with this value of zero. But in the second order, the elaboration
26514 routine of @code{Calc} runs after the body of Init_Constants has set
26515 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
26516 runs.
26517
26518 One could perhaps by applying pretty clever non-artificial intelligence
26519 to the situation guess that it is more likely that the second order of
26520 elaboration is the one desired, but there is no formal linguistic reason
26521 to prefer one over the other. In fact in this particular case, GNAT will
26522 prefer the second order, because of the rule that bodies are elaborated
26523 as soon as possible, but it's just luck that this is what was wanted
26524 (if indeed the second order was preferred).
26525
26526 If the program cares about the order of elaboration routines in a case like
26527 this, it is important to specify the order required. In this particular
26528 case, that could have been achieved by adding to the spec of Calc:
26529
26530 @smallexample @c ada
26531 pragma Elaborate_All (Constants);
26532 @end smallexample
26533
26534 @noindent
26535 which requires that the body (if any) and spec of @code{Constants},
26536 as well as the body and spec of any unit @code{with}'ed by
26537 @code{Constants} be elaborated before @code{Calc} is elaborated.
26538
26539 Clearly no automatic method can always guess which alternative you require,
26540 and if you are working with legacy code that had constraints of this kind
26541 which were not properly specified by adding @code{Elaborate} or
26542 @code{Elaborate_All} pragmas, then indeed it is possible that two different
26543 compilers can choose different orders.
26544
26545 However, GNAT does attempt to diagnose the common situation where there
26546 are uninitialized variables in the visible part of a package spec, and the
26547 corresponding package body has an elaboration block that directly or
26548 indirectly initialized one or more of these variables. This is the situation
26549 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
26550 a warning that suggests this addition if it detects this situation.
26551
26552 The @code{gnatbind}
26553 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
26554 out problems. This switch causes bodies to be elaborated as late as possible
26555 instead of as early as possible. In the example above, it would have forced
26556 the choice of the first elaboration order. If you get different results
26557 when using this switch, and particularly if one set of results is right,
26558 and one is wrong as far as you are concerned, it shows that you have some
26559 missing @code{Elaborate} pragmas. For the example above, we have the
26560 following output:
26561
26562 @smallexample
26563 gnatmake -f -q main
26564 main
26565 7
26566 gnatmake -f -q main -bargs -p
26567 main
26568 0
26569 @end smallexample
26570
26571 @noindent
26572 It is of course quite unlikely that both these results are correct, so
26573 it is up to you in a case like this to investigate the source of the
26574 difference, by looking at the two elaboration orders that are chosen,
26575 and figuring out which is correct, and then adding the necessary
26576 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
26577
26578
26579 @c **********************************
26580 @node Overflow Check Handling in GNAT
26581 @appendix Overflow Check Handling in GNAT
26582 @cindex Overflow checks
26583 @cindex Checks (overflow)
26584 @c **********************************
26585
26586 @menu
26587 * Background::
26588 * Overflow Checking Modes in GNAT::
26589 * Specifying the Desired Mode::
26590 * Default Settings::
26591 * Implementation Notes::
26592 @end menu
26593
26594
26595 @node Background
26596 @section Background
26597
26598 @noindent
26599 Overflow checks are checks that the compiler may make to ensure
26600 that intermediate results are not out of range. For example:
26601
26602 @smallexample @c ada
26603 A : Integer;
26604 ...
26605 A := A + 1;
26606 @end smallexample
26607
26608 @noindent
26609 if @code{A} has the value @code{Integer'Last}, then the addition may cause
26610 overflow since the result is out of range of the type @code{Integer}.
26611 In this case @code{Constraint_Error} will be raised if checks are
26612 enabled.
26613
26614 A trickier situation arises in examples like the following:
26615
26616 @smallexample @c ada
26617 A, C : Integer;
26618 ...
26619 A := (A + 1) + C;
26620 @end smallexample
26621
26622 @noindent
26623 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
26624 Now the final result of the expression on the right hand side is
26625 @code{Integer'Last} which is in range, but the question arises whether the
26626 intermediate addition of @code{(A + 1)} raises an overflow error.
26627
26628 The (perhaps surprising) answer is that the Ada language
26629 definition does not answer this question. Instead it leaves
26630 it up to the implementation to do one of two things if overflow
26631 checks are enabled.
26632
26633 @itemize @bullet
26634 @item
26635 raise an exception (@code{Constraint_Error}), or
26636
26637 @item
26638 yield the correct mathematical result which is then used in
26639 subsequent operations.
26640 @end itemize
26641
26642 @noindent
26643 If the compiler chooses the first approach, then the assignment of this
26644 example will indeed raise @code{Constraint_Error} if overflow checking is
26645 enabled, or result in erroneous execution if overflow checks are suppressed.
26646
26647 But if the compiler
26648 chooses the second approach, then it can perform both additions yielding
26649 the correct mathematical result, which is in range, so no exception
26650 will be raised, and the right result is obtained, regardless of whether
26651 overflow checks are suppressed.
26652
26653 Note that in the first example an
26654 exception will be raised in either case, since if the compiler
26655 gives the correct mathematical result for the addition, it will
26656 be out of range of the target type of the assignment, and thus
26657 fails the range check.
26658
26659 This lack of specified behavior in the handling of overflow for
26660 intermediate results is a source of non-portability, and can thus
26661 be problematic when programs are ported. Most typically this arises
26662 in a situation where the original compiler did not raise an exception,
26663 and then the application is moved to a compiler where the check is
26664 performed on the intermediate result and an unexpected exception is
26665 raised.
26666
26667 Furthermore, when using Ada 2012's preconditions and other
26668 assertion forms, another issue arises. Consider:
26669
26670 @smallexample @c ada
26671 procedure P (A, B : Integer) with
26672 Pre => A + B <= Integer'Last;
26673 @end smallexample
26674
26675 @noindent
26676 One often wants to regard arithmetic in a context like this from
26677 a mathematical point of view. So for example, if the two actual parameters
26678 for a call to @code{P} are both @code{Integer'Last}, then
26679 the precondition should be regarded as False. If we are executing
26680 in a mode with run-time checks enabled for preconditions, then we would
26681 like this precondition to fail, rather than raising an exception
26682 because of the intermediate overflow.
26683
26684 However, the language definition leaves the specification of
26685 whether the above condition fails (raising @code{Assert_Error}) or
26686 causes an intermediate overflow (raising @code{Constraint_Error})
26687 up to the implementation.
26688
26689 The situation is worse in a case such as the following:
26690
26691 @smallexample @c ada
26692 procedure Q (A, B, C : Integer) with
26693 Pre => A + B + C <= Integer'Last;
26694 @end smallexample
26695
26696 @noindent
26697 Consider the call
26698
26699 @smallexample @c ada
26700 Q (A => Integer'Last, B => 1, C => -1);
26701 @end smallexample
26702
26703 @noindent
26704 From a mathematical point of view the precondition
26705 is True, but at run time we may (but are not guaranteed to) get an
26706 exception raised because of the intermediate overflow (and we really
26707 would prefer this precondition to be considered True at run time).
26708
26709 @node Overflow Checking Modes in GNAT
26710 @section Overflow Checking Modes in GNAT
26711
26712 @noindent
26713 To deal with the portability issue, and with the problem of
26714 mathematical versus run-time interpretation of the expressions in
26715 assertions, GNAT provides comprehensive control over the handling
26716 of intermediate overflow. GNAT can operate in three modes, and
26717 furthemore, permits separate selection of operating modes for
26718 the expressions within assertions (here the term ``assertions''
26719 is used in the technical sense, which includes preconditions and so forth)
26720 and for expressions appearing outside assertions.
26721
26722 The three modes are:
26723
26724 @itemize @bullet
26725 @item @i{Use base type for intermediate operations} (@code{STRICT})
26726
26727 In this mode, all intermediate results for predefined arithmetic
26728 operators are computed using the base type, and the result must
26729 be in range of the base type. If this is not the
26730 case then either an exception is raised (if overflow checks are
26731 enabled) or the execution is erroneous (if overflow checks are suppressed).
26732 This is the normal default mode.
26733
26734 @item @i{Most intermediate overflows avoided} (@code{MINIMIZED})
26735
26736 In this mode, the compiler attempts to avoid intermediate overflows by
26737 using a larger integer type, typically @code{Long_Long_Integer},
26738 as the type in which arithmetic is
26739 performed for predefined arithmetic operators. This may be slightly more
26740 expensive at
26741 run time (compared to suppressing intermediate overflow checks), though
26742 the cost is negligible on modern 64-bit machines. For the examples given
26743 earlier, no intermediate overflows would have resulted in exceptions,
26744 since the intermediate results are all in the range of
26745 @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
26746 of GNAT). In addition, if checks are enabled, this reduces the number of
26747 checks that must be made, so this choice may actually result in an
26748 improvement in space and time behavior.
26749
26750 However, there are cases where @code{Long_Long_Integer} is not large
26751 enough, consider the following example:
26752
26753 @smallexample @c ada
26754 procedure R (A, B, C, D : Integer) with
26755 Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
26756 @end smallexample
26757
26758 where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
26759 Now the intermediate results are
26760 out of the range of @code{Long_Long_Integer} even though the final result
26761 is in range and the precondition is True (from a mathematical point
26762 of view). In such a case, operating in this mode, an overflow occurs
26763 for the intermediate computation (which is why this mode
26764 says @i{most} intermediate overflows are avoided). In this case,
26765 an exception is raised if overflow checks are enabled, and the
26766 execution is erroneous if overflow checks are suppressed.
26767
26768 @item @i{All intermediate overflows avoided} (@code{ELIMINATED})
26769
26770 In this mode, the compiler avoids all intermediate overflows
26771 by using arbitrary precision arithmetic as required. In this
26772 mode, the above example with @code{A**2 * B**2} would
26773 not cause intermediate overflow, because the intermediate result
26774 would be evaluated using sufficient precision, and the result
26775 of evaluating the precondition would be True.
26776
26777 This mode has the advantage of avoiding any intermediate
26778 overflows, but at the expense of significant run-time overhead,
26779 including the use of a library (included automatically in this
26780 mode) for multiple-precision arithmetic.
26781
26782 This mode provides cleaner semantics for assertions, since now
26783 the run-time behavior emulates true arithmetic behavior for the
26784 predefined arithmetic operators, meaning that there is never a
26785 conflict between the mathematical view of the assertion, and its
26786 run-time behavior.
26787
26788 Note that in this mode, the behavior is unaffected by whether or
26789 not overflow checks are suppressed, since overflow does not occur.
26790 It is possible for gigantic intermediate expressions to raise
26791 @code{Storage_Error} as a result of attempting to compute the
26792 results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
26793 but overflow is impossible.
26794
26795
26796 @end itemize
26797
26798 @noindent
26799 Note that these modes apply only to the evaluation of predefined
26800 arithmetic, membership, and comparison operators for signed integer
26801 aritmetic.
26802
26803 For fixed-point arithmetic, checks can be suppressed. But if checks
26804 are enabled
26805 then fixed-point values are always checked for overflow against the
26806 base type for intermediate expressions (that is such checks always
26807 operate in the equivalent of @code{STRICT} mode).
26808
26809 For floating-point, on nearly all architectures, @code{Machine_Overflows}
26810 is False, and IEEE infinities are generated, so overflow exceptions
26811 are never raised. If you want to avoid infinities, and check that
26812 final results of expressions are in range, then you can declare a
26813 constrained floating-point type, and range checks will be carried
26814 out in the normal manner (with infinite values always failing all
26815 range checks).
26816
26817
26818 @c -------------------------
26819 @node Specifying the Desired Mode
26820 @section Specifying the Desired Mode
26821
26822 @noindent
26823 The desired mode of for handling intermediate overflow can be specified using
26824 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
26825 The pragma has the form
26826 @cindex pragma @code{Overflow_Mode}
26827
26828 @smallexample @c ada
26829 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
26830 @end smallexample
26831
26832 @noindent
26833 where @code{MODE} is one of
26834
26835 @itemize @bullet
26836 @item @code{STRICT}: intermediate overflows checked (using base type)
26837 @item @code{MINIMIZED}: minimize intermediate overflows
26838 @item @code{ELIMINATED}: eliminate intermediate overflows
26839 @end itemize
26840
26841 @noindent
26842 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
26843 @code{minimized} all have the same effect.
26844
26845 If only the @code{General} parameter is present, then the given @code{MODE}
26846 applies
26847 to expressions both within and outside assertions. If both arguments
26848 are present, then @code{General} applies to expressions outside assertions,
26849 and @code{Assertions} applies to expressions within assertions. For example:
26850
26851 @smallexample @c ada
26852 pragma Overflow_Mode
26853 (General => Minimized, Assertions => Eliminated);
26854 @end smallexample
26855
26856 @noindent
26857 specifies that general expressions outside assertions be evaluated
26858 in ``minimize intermediate overflows'' mode, and expressions within
26859 assertions be evaluated in ``eliminate intermediate overflows'' mode.
26860 This is often a reasonable choice, avoiding excessive overhead
26861 outside assertions, but assuring a high degree of portability
26862 when importing code from another compiler, while incurring
26863 the extra overhead for assertion expressions to ensure that
26864 the behavior at run time matches the expected mathematical
26865 behavior.
26866
26867 The @code{Overflow_Mode} pragma has the same scoping and placement
26868 rules as pragma @code{Suppress}, so it can occur either as a
26869 configuration pragma, specifying a default for the whole
26870 program, or in a declarative scope, where it applies to the
26871 remaining declarations and statements in that scope.
26872
26873 Note that pragma @code{Overflow_Mode} does not affect whether
26874 overflow checks are enabled or suppressed. It only controls the
26875 method used to compute intermediate values. To control whether
26876 overflow checking is enabled or suppressed, use pragma @code{Suppress}
26877 or @code{Unsuppress} in the usual manner
26878
26879 Additionally, a compiler switch @option{-gnato?} or @option{-gnato??}
26880 can be used to control the checking mode default (which can be subsequently
26881 overridden using pragmas).
26882 @cindex @option{-gnato?} (gcc)
26883 @cindex @option{-gnato??} (gcc)
26884
26885 Here `@code{?}' is one of the digits `@code{1}' through `@code{3}':
26886
26887 @itemize @bullet
26888 @item @code{1}:
26889 use base type for intermediate operations (@code{STRICT})
26890 @item @code{2}:
26891 minimize intermediate overflows (@code{MINIMIZED})
26892 @item @code{3}:
26893 eliminate intermediate overflows (@code{ELIMINATED})
26894 @end itemize
26895
26896 @noindent
26897 As with the pragma, if only one digit appears then it applies to all
26898 cases; if two digits are given, then the first applies outside
26899 assertions, and the second within assertions. Thus the equivalent
26900 of the example pragma above would be
26901 @option{^-gnato23^/OVERFLOW_CHECKS=23^}.
26902
26903 If no digits follow the @option{-gnato}, then it is equivalent to
26904 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
26905 causing all intermediate operations to be computed using the base
26906 type (@code{STRICT} mode).
26907
26908 In addition to setting the mode used for computation of intermediate
26909 results, the @code{-gnato} switch also enables overflow checking (which
26910 is suppressed by default). It thus combines the effect of using
26911 a pragma @code{Overflow_Mode} and pragma @code{Unsuppress}.
26912
26913
26914 @c -------------------------
26915 @node Default Settings
26916 @section Default Settings
26917
26918 The default mode for overflow checks is
26919
26920 @smallexample
26921 General => Strict
26922 @end smallexample
26923
26924 @noindent
26925 which causes all computations both inside and outside assertions to use
26926 the base type. In addition overflow checks are suppressed.
26927
26928 This retains compatibility with previous versions of
26929 GNAT which suppressed overflow checks by default and always
26930 used the base type for computation of intermediate results.
26931
26932 The switch @option{-gnato} (with no digits following) is equivalent to
26933 @cindex @option{-gnato} (gcc)
26934
26935 @smallexample
26936 General => Strict
26937 @end smallexample
26938
26939 @noindent
26940 which causes overflow checking of all intermediate overflows
26941 both inside and outside assertions against the base type.
26942 This provides compatibility
26943 with this switch as implemented in previous versions of GNAT.
26944
26945 The pragma @code{Suppress (Overflow_Check)} disables overflow
26946 checking, but it has no effect on the method used for computing
26947 intermediate results.
26948
26949 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
26950 checking, but it has no effect on the method used for computing
26951 intermediate results.
26952
26953 @c -------------------------
26954 @node Implementation Notes
26955 @section Implementation Notes
26956
26957 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
26958 reasonably efficient, and can be generally used. It also helps
26959 to ensure compatibility with code imported from some other
26960 compiler to GNAT.
26961
26962 Setting all intermediate overflows checking (@code{CHECKED} mode)
26963 makes sense if you want to
26964 make sure that your code is compatible with any other possible
26965 Ada implementation. This may be useful in ensuring portability
26966 for code that is to be exported to some other compiler than GNAT.
26967
26968
26969 The Ada standard allows the reassociation of expressions at
26970 the same precedence level if no parentheses are present. For
26971 example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but
26972 the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly
26973 introducing or eliminating an overflow exception. The GNAT
26974 compiler never takes advantage of this freedom, and the
26975 expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}.
26976 If you need the other order, you can write the parentheses
26977 explicitly @w{@code{A+(B+C)}} and GNAT will respect this order.
26978
26979 The use of @code{ELIMINATED} mode will cause the compiler to
26980 automatically include an appropriate arbitrary precision
26981 integer arithmetic package. The compiler will make calls
26982 to this package, though only in cases where it cannot be
26983 sure that @code{Long_Long_Integer} is sufficient to guard against
26984 intermediate overflows. This package does not use dynamic
26985 alllocation, but it does use the secondary stack, so an
26986 appropriate secondary stack package must be present (this
26987 is always true for standard full Ada, but may require
26988 specific steps for restricted run times such as ZFP).
26989
26990 Although @code{ELIMINATED} mode causes expressions to use arbitrary
26991 precision arithmetic, avoiding overflow, the final result
26992 must be in an appropriate range. This is true even if the
26993 final result is of type @code{[Long_[Long_]]Integer'Base}, which
26994 still has the same bounds as its associated constrained
26995 type at run-time.
26996
26997 Currently, the @code{ELIMINATED} mode is only available on target
26998 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
26999 platforms).
27000
27001 @c *******************************
27002 @node Conditional Compilation
27003 @appendix Conditional Compilation
27004 @c *******************************
27005 @cindex Conditional compilation
27006
27007 @noindent
27008 It is often necessary to arrange for a single source program
27009 to serve multiple purposes, where it is compiled in different
27010 ways to achieve these different goals. Some examples of the
27011 need for this feature are
27012
27013 @itemize @bullet
27014 @item Adapting a program to a different hardware environment
27015 @item Adapting a program to a different target architecture
27016 @item Turning debugging features on and off
27017 @item Arranging for a program to compile with different compilers
27018 @end itemize
27019
27020 @noindent
27021 In C, or C++, the typical approach would be to use the preprocessor
27022 that is defined as part of the language. The Ada language does not
27023 contain such a feature. This is not an oversight, but rather a very
27024 deliberate design decision, based on the experience that overuse of
27025 the preprocessing features in C and C++ can result in programs that
27026 are extremely difficult to maintain. For example, if we have ten
27027 switches that can be on or off, this means that there are a thousand
27028 separate programs, any one of which might not even be syntactically
27029 correct, and even if syntactically correct, the resulting program
27030 might not work correctly. Testing all combinations can quickly become
27031 impossible.
27032
27033 Nevertheless, the need to tailor programs certainly exists, and in
27034 this Appendix we will discuss how this can
27035 be achieved using Ada in general, and GNAT in particular.
27036
27037 @menu
27038 * Use of Boolean Constants::
27039 * Debugging - A Special Case::
27040 * Conditionalizing Declarations::
27041 * Use of Alternative Implementations::
27042 * Preprocessing::
27043 @end menu
27044
27045 @node Use of Boolean Constants
27046 @section Use of Boolean Constants
27047
27048 @noindent
27049 In the case where the difference is simply which code
27050 sequence is executed, the cleanest solution is to use Boolean
27051 constants to control which code is executed.
27052
27053 @smallexample @c ada
27054 @group
27055 FP_Initialize_Required : constant Boolean := True;
27056 @dots{}
27057 if FP_Initialize_Required then
27058 @dots{}
27059 end if;
27060 @end group
27061 @end smallexample
27062
27063 @noindent
27064 Not only will the code inside the @code{if} statement not be executed if
27065 the constant Boolean is @code{False}, but it will also be completely
27066 deleted from the program.
27067 However, the code is only deleted after the @code{if} statement
27068 has been checked for syntactic and semantic correctness.
27069 (In contrast, with preprocessors the code is deleted before the
27070 compiler ever gets to see it, so it is not checked until the switch
27071 is turned on.)
27072 @cindex Preprocessors (contrasted with conditional compilation)
27073
27074 Typically the Boolean constants will be in a separate package,
27075 something like:
27076
27077 @smallexample @c ada
27078 @group
27079 package Config is
27080 FP_Initialize_Required : constant Boolean := True;
27081 Reset_Available : constant Boolean := False;
27082 @dots{}
27083 end Config;
27084 @end group
27085 @end smallexample
27086
27087 @noindent
27088 The @code{Config} package exists in multiple forms for the various targets,
27089 with an appropriate script selecting the version of @code{Config} needed.
27090 Then any other unit requiring conditional compilation can do a @code{with}
27091 of @code{Config} to make the constants visible.
27092
27093
27094 @node Debugging - A Special Case
27095 @section Debugging - A Special Case
27096
27097 @noindent
27098 A common use of conditional code is to execute statements (for example
27099 dynamic checks, or output of intermediate results) under control of a
27100 debug switch, so that the debugging behavior can be turned on and off.
27101 This can be done using a Boolean constant to control whether the code
27102 is active:
27103
27104 @smallexample @c ada
27105 @group
27106 if Debugging then
27107 Put_Line ("got to the first stage!");
27108 end if;
27109 @end group
27110 @end smallexample
27111
27112 @noindent
27113 or
27114
27115 @smallexample @c ada
27116 @group
27117 if Debugging and then Temperature > 999.0 then
27118 raise Temperature_Crazy;
27119 end if;
27120 @end group
27121 @end smallexample
27122
27123 @noindent
27124 Since this is a common case, there are special features to deal with
27125 this in a convenient manner. For the case of tests, Ada 2005 has added
27126 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
27127 @cindex pragma @code{Assert}
27128 on the @code{Assert} pragma that has always been available in GNAT, so this
27129 feature may be used with GNAT even if you are not using Ada 2005 features.
27130 The use of pragma @code{Assert} is described in
27131 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
27132 example, the last test could be written:
27133
27134 @smallexample @c ada
27135 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
27136 @end smallexample
27137
27138 @noindent
27139 or simply
27140
27141 @smallexample @c ada
27142 pragma Assert (Temperature <= 999.0);
27143 @end smallexample
27144
27145 @noindent
27146 In both cases, if assertions are active and the temperature is excessive,
27147 the exception @code{Assert_Failure} will be raised, with the given string in
27148 the first case or a string indicating the location of the pragma in the second
27149 case used as the exception message.
27150
27151 You can turn assertions on and off by using the @code{Assertion_Policy}
27152 pragma.
27153 @cindex pragma @code{Assertion_Policy}
27154 This is an Ada 2005 pragma which is implemented in all modes by
27155 GNAT, but only in the latest versions of GNAT which include Ada 2005
27156 capability. Alternatively, you can use the @option{-gnata} switch
27157 @cindex @option{-gnata} switch
27158 to enable assertions from the command line (this is recognized by all versions
27159 of GNAT).
27160
27161 For the example above with the @code{Put_Line}, the GNAT-specific pragma
27162 @code{Debug} can be used:
27163 @cindex pragma @code{Debug}
27164
27165 @smallexample @c ada
27166 pragma Debug (Put_Line ("got to the first stage!"));
27167 @end smallexample
27168
27169 @noindent
27170 If debug pragmas are enabled, the argument, which must be of the form of
27171 a procedure call, is executed (in this case, @code{Put_Line} will be called).
27172 Only one call can be present, but of course a special debugging procedure
27173 containing any code you like can be included in the program and then
27174 called in a pragma @code{Debug} argument as needed.
27175
27176 One advantage of pragma @code{Debug} over the @code{if Debugging then}
27177 construct is that pragma @code{Debug} can appear in declarative contexts,
27178 such as at the very beginning of a procedure, before local declarations have
27179 been elaborated.
27180
27181 Debug pragmas are enabled using either the @option{-gnata} switch that also
27182 controls assertions, or with a separate Debug_Policy pragma.
27183 @cindex pragma @code{Debug_Policy}
27184 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
27185 in Ada 95 and Ada 83 programs as well), and is analogous to
27186 pragma @code{Assertion_Policy} to control assertions.
27187
27188 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
27189 and thus they can appear in @file{gnat.adc} if you are not using a
27190 project file, or in the file designated to contain configuration pragmas
27191 in a project file.
27192 They then apply to all subsequent compilations. In practice the use of
27193 the @option{-gnata} switch is often the most convenient method of controlling
27194 the status of these pragmas.
27195
27196 Note that a pragma is not a statement, so in contexts where a statement
27197 sequence is required, you can't just write a pragma on its own. You have
27198 to add a @code{null} statement.
27199
27200 @smallexample @c ada
27201 @group
27202 if @dots{} then
27203 @dots{} -- some statements
27204 else
27205 pragma Assert (Num_Cases < 10);
27206 null;
27207 end if;
27208 @end group
27209 @end smallexample
27210
27211
27212 @node Conditionalizing Declarations
27213 @section Conditionalizing Declarations
27214
27215 @noindent
27216 In some cases, it may be necessary to conditionalize declarations to meet
27217 different requirements. For example we might want a bit string whose length
27218 is set to meet some hardware message requirement.
27219
27220 In some cases, it may be possible to do this using declare blocks controlled
27221 by conditional constants:
27222
27223 @smallexample @c ada
27224 @group
27225 if Small_Machine then
27226 declare
27227 X : Bit_String (1 .. 10);
27228 begin
27229 @dots{}
27230 end;
27231 else
27232 declare
27233 X : Large_Bit_String (1 .. 1000);
27234 begin
27235 @dots{}
27236 end;
27237 end if;
27238 @end group
27239 @end smallexample
27240
27241 @noindent
27242 Note that in this approach, both declarations are analyzed by the
27243 compiler so this can only be used where both declarations are legal,
27244 even though one of them will not be used.
27245
27246 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
27247 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
27248 that are parameterized by these constants. For example
27249
27250 @smallexample @c ada
27251 @group
27252 for Rec use
27253 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
27254 end record;
27255 @end group
27256 @end smallexample
27257
27258 @noindent
27259 If @code{Bits_Per_Word} is set to 32, this generates either
27260
27261 @smallexample @c ada
27262 @group
27263 for Rec use
27264 Field1 at 0 range 0 .. 32;
27265 end record;
27266 @end group
27267 @end smallexample
27268
27269 @noindent
27270 for the big endian case, or
27271
27272 @smallexample @c ada
27273 @group
27274 for Rec use record
27275 Field1 at 0 range 10 .. 32;
27276 end record;
27277 @end group
27278 @end smallexample
27279
27280 @noindent
27281 for the little endian case. Since a powerful subset of Ada expression
27282 notation is usable for creating static constants, clever use of this
27283 feature can often solve quite difficult problems in conditionalizing
27284 compilation (note incidentally that in Ada 95, the little endian
27285 constant was introduced as @code{System.Default_Bit_Order}, so you do not
27286 need to define this one yourself).
27287
27288
27289 @node Use of Alternative Implementations
27290 @section Use of Alternative Implementations
27291
27292 @noindent
27293 In some cases, none of the approaches described above are adequate. This
27294 can occur for example if the set of declarations required is radically
27295 different for two different configurations.
27296
27297 In this situation, the official Ada way of dealing with conditionalizing
27298 such code is to write separate units for the different cases. As long as
27299 this does not result in excessive duplication of code, this can be done
27300 without creating maintenance problems. The approach is to share common
27301 code as far as possible, and then isolate the code and declarations
27302 that are different. Subunits are often a convenient method for breaking
27303 out a piece of a unit that is to be conditionalized, with separate files
27304 for different versions of the subunit for different targets, where the
27305 build script selects the right one to give to the compiler.
27306 @cindex Subunits (and conditional compilation)
27307
27308 As an example, consider a situation where a new feature in Ada 2005
27309 allows something to be done in a really nice way. But your code must be able
27310 to compile with an Ada 95 compiler. Conceptually you want to say:
27311
27312 @smallexample @c ada
27313 @group
27314 if Ada_2005 then
27315 @dots{} neat Ada 2005 code
27316 else
27317 @dots{} not quite as neat Ada 95 code
27318 end if;
27319 @end group
27320 @end smallexample
27321
27322 @noindent
27323 where @code{Ada_2005} is a Boolean constant.
27324
27325 But this won't work when @code{Ada_2005} is set to @code{False},
27326 since the @code{then} clause will be illegal for an Ada 95 compiler.
27327 (Recall that although such unreachable code would eventually be deleted
27328 by the compiler, it still needs to be legal. If it uses features
27329 introduced in Ada 2005, it will be illegal in Ada 95.)
27330
27331 So instead we write
27332
27333 @smallexample @c ada
27334 procedure Insert is separate;
27335 @end smallexample
27336
27337 @noindent
27338 Then we have two files for the subunit @code{Insert}, with the two sets of
27339 code.
27340 If the package containing this is called @code{File_Queries}, then we might
27341 have two files
27342
27343 @itemize @bullet
27344 @item @file{file_queries-insert-2005.adb}
27345 @item @file{file_queries-insert-95.adb}
27346 @end itemize
27347
27348 @noindent
27349 and the build script renames the appropriate file to
27350
27351 @smallexample
27352 file_queries-insert.adb
27353 @end smallexample
27354
27355 @noindent
27356 and then carries out the compilation.
27357
27358 This can also be done with project files' naming schemes. For example:
27359
27360 @smallexample @c project
27361 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
27362 @end smallexample
27363
27364 @noindent
27365 Note also that with project files it is desirable to use a different extension
27366 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
27367 conflict may arise through another commonly used feature: to declare as part
27368 of the project a set of directories containing all the sources obeying the
27369 default naming scheme.
27370
27371 The use of alternative units is certainly feasible in all situations,
27372 and for example the Ada part of the GNAT run-time is conditionalized
27373 based on the target architecture using this approach. As a specific example,
27374 consider the implementation of the AST feature in VMS. There is one
27375 spec:
27376
27377 @smallexample
27378 s-asthan.ads
27379 @end smallexample
27380
27381 @noindent
27382 which is the same for all architectures, and three bodies:
27383
27384 @table @file
27385 @item s-asthan.adb
27386 used for all non-VMS operating systems
27387 @item s-asthan-vms-alpha.adb
27388 used for VMS on the Alpha
27389 @item s-asthan-vms-ia64.adb
27390 used for VMS on the ia64
27391 @end table
27392
27393 @noindent
27394 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
27395 this operating system feature is not available, and the two remaining
27396 versions interface with the corresponding versions of VMS to provide
27397 VMS-compatible AST handling. The GNAT build script knows the architecture
27398 and operating system, and automatically selects the right version,
27399 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
27400
27401 Another style for arranging alternative implementations is through Ada's
27402 access-to-subprogram facility.
27403 In case some functionality is to be conditionally included,
27404 you can declare an access-to-procedure variable @code{Ref} that is initialized
27405 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
27406 when appropriate.
27407 In some library package, set @code{Ref} to @code{Proc'Access} for some
27408 procedure @code{Proc} that performs the relevant processing.
27409 The initialization only occurs if the library package is included in the
27410 program.
27411 The same idea can also be implemented using tagged types and dispatching
27412 calls.
27413
27414
27415 @node Preprocessing
27416 @section Preprocessing
27417 @cindex Preprocessing
27418
27419 @noindent
27420 Although it is quite possible to conditionalize code without the use of
27421 C-style preprocessing, as described earlier in this section, it is
27422 nevertheless convenient in some cases to use the C approach. Moreover,
27423 older Ada compilers have often provided some preprocessing capability,
27424 so legacy code may depend on this approach, even though it is not
27425 standard.
27426
27427 To accommodate such use, GNAT provides a preprocessor (modeled to a large
27428 extent on the various preprocessors that have been used
27429 with legacy code on other compilers, to enable easier transition).
27430
27431 The preprocessor may be used in two separate modes. It can be used quite
27432 separately from the compiler, to generate a separate output source file
27433 that is then fed to the compiler as a separate step. This is the
27434 @code{gnatprep} utility, whose use is fully described in
27435 @ref{Preprocessing with gnatprep}.
27436 @cindex @code{gnatprep}
27437
27438 The preprocessing language allows such constructs as
27439
27440 @smallexample
27441 @group
27442 #if DEBUG or PRIORITY > 4 then
27443 bunch of declarations
27444 #else
27445 completely different bunch of declarations
27446 #end if;
27447 @end group
27448 @end smallexample
27449
27450 @noindent
27451 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
27452 defined either on the command line or in a separate file.
27453
27454 The other way of running the preprocessor is even closer to the C style and
27455 often more convenient. In this approach the preprocessing is integrated into
27456 the compilation process. The compiler is fed the preprocessor input which
27457 includes @code{#if} lines etc, and then the compiler carries out the
27458 preprocessing internally and processes the resulting output.
27459 For more details on this approach, see @ref{Integrated Preprocessing}.
27460
27461
27462 @c *******************************
27463 @node Inline Assembler
27464 @appendix Inline Assembler
27465 @c *******************************
27466
27467 @noindent
27468 If you need to write low-level software that interacts directly
27469 with the hardware, Ada provides two ways to incorporate assembly
27470 language code into your program. First, you can import and invoke
27471 external routines written in assembly language, an Ada feature fully
27472 supported by GNAT@. However, for small sections of code it may be simpler
27473 or more efficient to include assembly language statements directly
27474 in your Ada source program, using the facilities of the implementation-defined
27475 package @code{System.Machine_Code}, which incorporates the gcc
27476 Inline Assembler. The Inline Assembler approach offers a number of advantages,
27477 including the following:
27478
27479 @itemize @bullet
27480 @item No need to use non-Ada tools
27481 @item Consistent interface over different targets
27482 @item Automatic usage of the proper calling conventions
27483 @item Access to Ada constants and variables
27484 @item Definition of intrinsic routines
27485 @item Possibility of inlining a subprogram comprising assembler code
27486 @item Code optimizer can take Inline Assembler code into account
27487 @end itemize
27488
27489 This chapter presents a series of examples to show you how to use
27490 the Inline Assembler. Although it focuses on the Intel x86,
27491 the general approach applies also to other processors.
27492 It is assumed that you are familiar with Ada
27493 and with assembly language programming.
27494
27495 @menu
27496 * Basic Assembler Syntax::
27497 * A Simple Example of Inline Assembler::
27498 * Output Variables in Inline Assembler::
27499 * Input Variables in Inline Assembler::
27500 * Inlining Inline Assembler Code::
27501 * Other Asm Functionality::
27502 @end menu
27503
27504 @c ---------------------------------------------------------------------------
27505 @node Basic Assembler Syntax
27506 @section Basic Assembler Syntax
27507
27508 @noindent
27509 The assembler used by GNAT and gcc is based not on the Intel assembly
27510 language, but rather on a language that descends from the AT&T Unix
27511 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
27512 The following table summarizes the main features of @emph{as} syntax
27513 and points out the differences from the Intel conventions.
27514 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
27515 pre-processor) documentation for further information.
27516
27517 @table @asis
27518 @item Register names
27519 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
27520 @*
27521 Intel: No extra punctuation; for example @code{eax}
27522
27523 @item Immediate operand
27524 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
27525 @*
27526 Intel: No extra punctuation; for example @code{4}
27527
27528 @item Address
27529 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
27530 @*
27531 Intel: No extra punctuation; for example @code{loc}
27532
27533 @item Memory contents
27534 gcc / @emph{as}: No extra punctuation; for example @code{loc}
27535 @*
27536 Intel: Square brackets; for example @code{[loc]}
27537
27538 @item Register contents
27539 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
27540 @*
27541 Intel: Square brackets; for example @code{[eax]}
27542
27543 @item Hexadecimal numbers
27544 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
27545 @*
27546 Intel: Trailing ``h''; for example @code{A0h}
27547
27548 @item Operand size
27549 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
27550 a 16-bit word
27551 @*
27552 Intel: Implicit, deduced by assembler; for example @code{mov}
27553
27554 @item Instruction repetition
27555 gcc / @emph{as}: Split into two lines; for example
27556 @*
27557 @code{rep}
27558 @*
27559 @code{stosl}
27560 @*
27561 Intel: Keep on one line; for example @code{rep stosl}
27562
27563 @item Order of operands
27564 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
27565 @*
27566 Intel: Destination first; for example @code{mov eax, 4}
27567 @end table
27568
27569 @c ---------------------------------------------------------------------------
27570 @node A Simple Example of Inline Assembler
27571 @section A Simple Example of Inline Assembler
27572
27573 @noindent
27574 The following example will generate a single assembly language statement,
27575 @code{nop}, which does nothing. Despite its lack of run-time effect,
27576 the example will be useful in illustrating the basics of
27577 the Inline Assembler facility.
27578
27579 @smallexample @c ada
27580 @group
27581 with System.Machine_Code; use System.Machine_Code;
27582 procedure Nothing is
27583 begin
27584 Asm ("nop");
27585 end Nothing;
27586 @end group
27587 @end smallexample
27588
27589 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
27590 here it takes one parameter, a @emph{template string} that must be a static
27591 expression and that will form the generated instruction.
27592 @code{Asm} may be regarded as a compile-time procedure that parses
27593 the template string and additional parameters (none here),
27594 from which it generates a sequence of assembly language instructions.
27595
27596 The examples in this chapter will illustrate several of the forms
27597 for invoking @code{Asm}; a complete specification of the syntax
27598 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
27599 Manual}.
27600
27601 Under the standard GNAT conventions, the @code{Nothing} procedure
27602 should be in a file named @file{nothing.adb}.
27603 You can build the executable in the usual way:
27604 @smallexample
27605 gnatmake nothing
27606 @end smallexample
27607 However, the interesting aspect of this example is not its run-time behavior
27608 but rather the generated assembly code.
27609 To see this output, invoke the compiler as follows:
27610 @smallexample
27611 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
27612 @end smallexample
27613 where the options are:
27614
27615 @table @code
27616 @item -c
27617 compile only (no bind or link)
27618 @item -S
27619 generate assembler listing
27620 @item -fomit-frame-pointer
27621 do not set up separate stack frames
27622 @item -gnatp
27623 do not add runtime checks
27624 @end table
27625
27626 This gives a human-readable assembler version of the code. The resulting
27627 file will have the same name as the Ada source file, but with a @code{.s}
27628 extension. In our example, the file @file{nothing.s} has the following
27629 contents:
27630
27631 @smallexample
27632 @group
27633 .file "nothing.adb"
27634 gcc2_compiled.:
27635 ___gnu_compiled_ada:
27636 .text
27637 .align 4
27638 .globl __ada_nothing
27639 __ada_nothing:
27640 #APP
27641 nop
27642 #NO_APP
27643 jmp L1
27644 .align 2,0x90
27645 L1:
27646 ret
27647 @end group
27648 @end smallexample
27649
27650 The assembly code you included is clearly indicated by
27651 the compiler, between the @code{#APP} and @code{#NO_APP}
27652 delimiters. The character before the 'APP' and 'NOAPP'
27653 can differ on different targets. For example, GNU/Linux uses '#APP' while
27654 on NT you will see '/APP'.
27655
27656 If you make a mistake in your assembler code (such as using the
27657 wrong size modifier, or using a wrong operand for the instruction) GNAT
27658 will report this error in a temporary file, which will be deleted when
27659 the compilation is finished. Generating an assembler file will help
27660 in such cases, since you can assemble this file separately using the
27661 @emph{as} assembler that comes with gcc.
27662
27663 Assembling the file using the command
27664
27665 @smallexample
27666 as @file{nothing.s}
27667 @end smallexample
27668 @noindent
27669 will give you error messages whose lines correspond to the assembler
27670 input file, so you can easily find and correct any mistakes you made.
27671 If there are no errors, @emph{as} will generate an object file
27672 @file{nothing.out}.
27673
27674 @c ---------------------------------------------------------------------------
27675 @node Output Variables in Inline Assembler
27676 @section Output Variables in Inline Assembler
27677
27678 @noindent
27679 The examples in this section, showing how to access the processor flags,
27680 illustrate how to specify the destination operands for assembly language
27681 statements.
27682
27683 @smallexample @c ada
27684 @group
27685 with Interfaces; use Interfaces;
27686 with Ada.Text_IO; use Ada.Text_IO;
27687 with System.Machine_Code; use System.Machine_Code;
27688 procedure Get_Flags is
27689 Flags : Unsigned_32;
27690 use ASCII;
27691 begin
27692 Asm ("pushfl" & LF & HT & -- push flags on stack
27693 "popl %%eax" & LF & HT & -- load eax with flags
27694 "movl %%eax, %0", -- store flags in variable
27695 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27696 Put_Line ("Flags register:" & Flags'Img);
27697 end Get_Flags;
27698 @end group
27699 @end smallexample
27700
27701 In order to have a nicely aligned assembly listing, we have separated
27702 multiple assembler statements in the Asm template string with linefeed
27703 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
27704 The resulting section of the assembly output file is:
27705
27706 @smallexample
27707 @group
27708 #APP
27709 pushfl
27710 popl %eax
27711 movl %eax, -40(%ebp)
27712 #NO_APP
27713 @end group
27714 @end smallexample
27715
27716 It would have been legal to write the Asm invocation as:
27717
27718 @smallexample
27719 Asm ("pushfl popl %%eax movl %%eax, %0")
27720 @end smallexample
27721
27722 but in the generated assembler file, this would come out as:
27723
27724 @smallexample
27725 #APP
27726 pushfl popl %eax movl %eax, -40(%ebp)
27727 #NO_APP
27728 @end smallexample
27729
27730 which is not so convenient for the human reader.
27731
27732 We use Ada comments
27733 at the end of each line to explain what the assembler instructions
27734 actually do. This is a useful convention.
27735
27736 When writing Inline Assembler instructions, you need to precede each register
27737 and variable name with a percent sign. Since the assembler already requires
27738 a percent sign at the beginning of a register name, you need two consecutive
27739 percent signs for such names in the Asm template string, thus @code{%%eax}.
27740 In the generated assembly code, one of the percent signs will be stripped off.
27741
27742 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
27743 variables: operands you later define using @code{Input} or @code{Output}
27744 parameters to @code{Asm}.
27745 An output variable is illustrated in
27746 the third statement in the Asm template string:
27747 @smallexample
27748 movl %%eax, %0
27749 @end smallexample
27750 The intent is to store the contents of the eax register in a variable that can
27751 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
27752 necessarily work, since the compiler might optimize by using a register
27753 to hold Flags, and the expansion of the @code{movl} instruction would not be
27754 aware of this optimization. The solution is not to store the result directly
27755 but rather to advise the compiler to choose the correct operand form;
27756 that is the purpose of the @code{%0} output variable.
27757
27758 Information about the output variable is supplied in the @code{Outputs}
27759 parameter to @code{Asm}:
27760 @smallexample
27761 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27762 @end smallexample
27763
27764 The output is defined by the @code{Asm_Output} attribute of the target type;
27765 the general format is
27766 @smallexample
27767 Type'Asm_Output (constraint_string, variable_name)
27768 @end smallexample
27769
27770 The constraint string directs the compiler how
27771 to store/access the associated variable. In the example
27772 @smallexample
27773 Unsigned_32'Asm_Output ("=m", Flags);
27774 @end smallexample
27775 the @code{"m"} (memory) constraint tells the compiler that the variable
27776 @code{Flags} should be stored in a memory variable, thus preventing
27777 the optimizer from keeping it in a register. In contrast,
27778 @smallexample
27779 Unsigned_32'Asm_Output ("=r", Flags);
27780 @end smallexample
27781 uses the @code{"r"} (register) constraint, telling the compiler to
27782 store the variable in a register.
27783
27784 If the constraint is preceded by the equal character (@strong{=}), it tells
27785 the compiler that the variable will be used to store data into it.
27786
27787 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
27788 allowing the optimizer to choose whatever it deems best.
27789
27790 There are a fairly large number of constraints, but the ones that are
27791 most useful (for the Intel x86 processor) are the following:
27792
27793 @table @code
27794 @item =
27795 output constraint
27796 @item g
27797 global (i.e.@: can be stored anywhere)
27798 @item m
27799 in memory
27800 @item I
27801 a constant
27802 @item a
27803 use eax
27804 @item b
27805 use ebx
27806 @item c
27807 use ecx
27808 @item d
27809 use edx
27810 @item S
27811 use esi
27812 @item D
27813 use edi
27814 @item r
27815 use one of eax, ebx, ecx or edx
27816 @item q
27817 use one of eax, ebx, ecx, edx, esi or edi
27818 @end table
27819
27820 The full set of constraints is described in the gcc and @emph{as}
27821 documentation; note that it is possible to combine certain constraints
27822 in one constraint string.
27823
27824 You specify the association of an output variable with an assembler operand
27825 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
27826 integer. Thus in
27827 @smallexample @c ada
27828 @group
27829 Asm ("pushfl" & LF & HT & -- push flags on stack
27830 "popl %%eax" & LF & HT & -- load eax with flags
27831 "movl %%eax, %0", -- store flags in variable
27832 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27833 @end group
27834 @end smallexample
27835 @noindent
27836 @code{%0} will be replaced in the expanded code by the appropriate operand,
27837 whatever
27838 the compiler decided for the @code{Flags} variable.
27839
27840 In general, you may have any number of output variables:
27841 @itemize @bullet
27842 @item
27843 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
27844 @item
27845 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
27846 of @code{Asm_Output} attributes
27847 @end itemize
27848
27849 For example:
27850 @smallexample @c ada
27851 @group
27852 Asm ("movl %%eax, %0" & LF & HT &
27853 "movl %%ebx, %1" & LF & HT &
27854 "movl %%ecx, %2",
27855 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
27856 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
27857 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
27858 @end group
27859 @end smallexample
27860 @noindent
27861 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
27862 in the Ada program.
27863
27864 As a variation on the @code{Get_Flags} example, we can use the constraints
27865 string to direct the compiler to store the eax register into the @code{Flags}
27866 variable, instead of including the store instruction explicitly in the
27867 @code{Asm} template string:
27868
27869 @smallexample @c ada
27870 @group
27871 with Interfaces; use Interfaces;
27872 with Ada.Text_IO; use Ada.Text_IO;
27873 with System.Machine_Code; use System.Machine_Code;
27874 procedure Get_Flags_2 is
27875 Flags : Unsigned_32;
27876 use ASCII;
27877 begin
27878 Asm ("pushfl" & LF & HT & -- push flags on stack
27879 "popl %%eax", -- save flags in eax
27880 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
27881 Put_Line ("Flags register:" & Flags'Img);
27882 end Get_Flags_2;
27883 @end group
27884 @end smallexample
27885
27886 @noindent
27887 The @code{"a"} constraint tells the compiler that the @code{Flags}
27888 variable will come from the eax register. Here is the resulting code:
27889
27890 @smallexample
27891 @group
27892 #APP
27893 pushfl
27894 popl %eax
27895 #NO_APP
27896 movl %eax,-40(%ebp)
27897 @end group
27898 @end smallexample
27899
27900 @noindent
27901 The compiler generated the store of eax into Flags after
27902 expanding the assembler code.
27903
27904 Actually, there was no need to pop the flags into the eax register;
27905 more simply, we could just pop the flags directly into the program variable:
27906
27907 @smallexample @c ada
27908 @group
27909 with Interfaces; use Interfaces;
27910 with Ada.Text_IO; use Ada.Text_IO;
27911 with System.Machine_Code; use System.Machine_Code;
27912 procedure Get_Flags_3 is
27913 Flags : Unsigned_32;
27914 use ASCII;
27915 begin
27916 Asm ("pushfl" & LF & HT & -- push flags on stack
27917 "pop %0", -- save flags in Flags
27918 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
27919 Put_Line ("Flags register:" & Flags'Img);
27920 end Get_Flags_3;
27921 @end group
27922 @end smallexample
27923
27924 @c ---------------------------------------------------------------------------
27925 @node Input Variables in Inline Assembler
27926 @section Input Variables in Inline Assembler
27927
27928 @noindent
27929 The example in this section illustrates how to specify the source operands
27930 for assembly language statements.
27931 The program simply increments its input value by 1:
27932
27933 @smallexample @c ada
27934 @group
27935 with Interfaces; use Interfaces;
27936 with Ada.Text_IO; use Ada.Text_IO;
27937 with System.Machine_Code; use System.Machine_Code;
27938 procedure Increment is
27939
27940 function Incr (Value : Unsigned_32) return Unsigned_32 is
27941 Result : Unsigned_32;
27942 begin
27943 Asm ("incl %0",
27944 Outputs => Unsigned_32'Asm_Output ("=a", Result),
27945 Inputs => Unsigned_32'Asm_Input ("a", Value));
27946 return Result;
27947 end Incr;
27948
27949 Value : Unsigned_32;
27950
27951 begin
27952 Value := 5;
27953 Put_Line ("Value before is" & Value'Img);
27954 Value := Incr (Value);
27955 Put_Line ("Value after is" & Value'Img);
27956 end Increment;
27957 @end group
27958 @end smallexample
27959
27960 The @code{Outputs} parameter to @code{Asm} specifies
27961 that the result will be in the eax register and that it is to be stored
27962 in the @code{Result} variable.
27963
27964 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
27965 but with an @code{Asm_Input} attribute.
27966 The @code{"="} constraint, indicating an output value, is not present.
27967
27968 You can have multiple input variables, in the same way that you can have more
27969 than one output variable.
27970
27971 The parameter count (%0, %1) etc, still starts at the first output statement,
27972 and continues with the input statements.
27973
27974 Just as the @code{Outputs} parameter causes the register to be stored into the
27975 target variable after execution of the assembler statements, so does the
27976 @code{Inputs} parameter cause its variable to be loaded into the register
27977 before execution of the assembler statements.
27978
27979 Thus the effect of the @code{Asm} invocation is:
27980 @enumerate
27981 @item load the 32-bit value of @code{Value} into eax
27982 @item execute the @code{incl %eax} instruction
27983 @item store the contents of eax into the @code{Result} variable
27984 @end enumerate
27985
27986 The resulting assembler file (with @option{-O2} optimization) contains:
27987 @smallexample
27988 @group
27989 _increment__incr.1:
27990 subl $4,%esp
27991 movl 8(%esp),%eax
27992 #APP
27993 incl %eax
27994 #NO_APP
27995 movl %eax,%edx
27996 movl %ecx,(%esp)
27997 addl $4,%esp
27998 ret
27999 @end group
28000 @end smallexample
28001
28002 @c ---------------------------------------------------------------------------
28003 @node Inlining Inline Assembler Code
28004 @section Inlining Inline Assembler Code
28005
28006 @noindent
28007 For a short subprogram such as the @code{Incr} function in the previous
28008 section, the overhead of the call and return (creating / deleting the stack
28009 frame) can be significant, compared to the amount of code in the subprogram
28010 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
28011 which directs the compiler to expand invocations of the subprogram at the
28012 point(s) of call, instead of setting up a stack frame for out-of-line calls.
28013 Here is the resulting program:
28014
28015 @smallexample @c ada
28016 @group
28017 with Interfaces; use Interfaces;
28018 with Ada.Text_IO; use Ada.Text_IO;
28019 with System.Machine_Code; use System.Machine_Code;
28020 procedure Increment_2 is
28021
28022 function Incr (Value : Unsigned_32) return Unsigned_32 is
28023 Result : Unsigned_32;
28024 begin
28025 Asm ("incl %0",
28026 Outputs => Unsigned_32'Asm_Output ("=a", Result),
28027 Inputs => Unsigned_32'Asm_Input ("a", Value));
28028 return Result;
28029 end Incr;
28030 pragma Inline (Increment);
28031
28032 Value : Unsigned_32;
28033
28034 begin
28035 Value := 5;
28036 Put_Line ("Value before is" & Value'Img);
28037 Value := Increment (Value);
28038 Put_Line ("Value after is" & Value'Img);
28039 end Increment_2;
28040 @end group
28041 @end smallexample
28042
28043 Compile the program with both optimization (@option{-O2}) and inlining
28044 (@option{-gnatn}) enabled.
28045
28046 The @code{Incr} function is still compiled as usual, but at the
28047 point in @code{Increment} where our function used to be called:
28048
28049 @smallexample
28050 @group
28051 pushl %edi
28052 call _increment__incr.1
28053 @end group
28054 @end smallexample
28055
28056 @noindent
28057 the code for the function body directly appears:
28058
28059 @smallexample
28060 @group
28061 movl %esi,%eax
28062 #APP
28063 incl %eax
28064 #NO_APP
28065 movl %eax,%edx
28066 @end group
28067 @end smallexample
28068
28069 @noindent
28070 thus saving the overhead of stack frame setup and an out-of-line call.
28071
28072 @c ---------------------------------------------------------------------------
28073 @node Other Asm Functionality
28074 @section Other @code{Asm} Functionality
28075
28076 @noindent
28077 This section describes two important parameters to the @code{Asm}
28078 procedure: @code{Clobber}, which identifies register usage;
28079 and @code{Volatile}, which inhibits unwanted optimizations.
28080
28081 @menu
28082 * The Clobber Parameter::
28083 * The Volatile Parameter::
28084 @end menu
28085
28086 @c ---------------------------------------------------------------------------
28087 @node The Clobber Parameter
28088 @subsection The @code{Clobber} Parameter
28089
28090 @noindent
28091 One of the dangers of intermixing assembly language and a compiled language
28092 such as Ada is that the compiler needs to be aware of which registers are
28093 being used by the assembly code. In some cases, such as the earlier examples,
28094 the constraint string is sufficient to indicate register usage (e.g.,
28095 @code{"a"} for
28096 the eax register). But more generally, the compiler needs an explicit
28097 identification of the registers that are used by the Inline Assembly
28098 statements.
28099
28100 Using a register that the compiler doesn't know about
28101 could be a side effect of an instruction (like @code{mull}
28102 storing its result in both eax and edx).
28103 It can also arise from explicit register usage in your
28104 assembly code; for example:
28105 @smallexample
28106 @group
28107 Asm ("movl %0, %%ebx" & LF & HT &
28108 "movl %%ebx, %1",
28109 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28110 Inputs => Unsigned_32'Asm_Input ("g", Var_In));
28111 @end group
28112 @end smallexample
28113 @noindent
28114 where the compiler (since it does not analyze the @code{Asm} template string)
28115 does not know you are using the ebx register.
28116
28117 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
28118 to identify the registers that will be used by your assembly code:
28119
28120 @smallexample
28121 @group
28122 Asm ("movl %0, %%ebx" & LF & HT &
28123 "movl %%ebx, %1",
28124 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28125 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28126 Clobber => "ebx");
28127 @end group
28128 @end smallexample
28129
28130 The Clobber parameter is a static string expression specifying the
28131 register(s) you are using. Note that register names are @emph{not} prefixed
28132 by a percent sign. Also, if more than one register is used then their names
28133 are separated by commas; e.g., @code{"eax, ebx"}
28134
28135 The @code{Clobber} parameter has several additional uses:
28136 @enumerate
28137 @item Use ``register'' name @code{cc} to indicate that flags might have changed
28138 @item Use ``register'' name @code{memory} if you changed a memory location
28139 @end enumerate
28140
28141 @c ---------------------------------------------------------------------------
28142 @node The Volatile Parameter
28143 @subsection The @code{Volatile} Parameter
28144 @cindex Volatile parameter
28145
28146 @noindent
28147 Compiler optimizations in the presence of Inline Assembler may sometimes have
28148 unwanted effects. For example, when an @code{Asm} invocation with an input
28149 variable is inside a loop, the compiler might move the loading of the input
28150 variable outside the loop, regarding it as a one-time initialization.
28151
28152 If this effect is not desired, you can disable such optimizations by setting
28153 the @code{Volatile} parameter to @code{True}; for example:
28154
28155 @smallexample @c ada
28156 @group
28157 Asm ("movl %0, %%ebx" & LF & HT &
28158 "movl %%ebx, %1",
28159 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28160 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28161 Clobber => "ebx",
28162 Volatile => True);
28163 @end group
28164 @end smallexample
28165
28166 By default, @code{Volatile} is set to @code{False} unless there is no
28167 @code{Outputs} parameter.
28168
28169 Although setting @code{Volatile} to @code{True} prevents unwanted
28170 optimizations, it will also disable other optimizations that might be
28171 important for efficiency. In general, you should set @code{Volatile}
28172 to @code{True} only if the compiler's optimizations have created
28173 problems.
28174 @c END OF INLINE ASSEMBLER CHAPTER
28175 @c ===============================
28176
28177 @c ***********************************
28178 @c * Compatibility and Porting Guide *
28179 @c ***********************************
28180 @node Compatibility and Porting Guide
28181 @appendix Compatibility and Porting Guide
28182
28183 @noindent
28184 This chapter describes the compatibility issues that may arise between
28185 GNAT and other Ada compilation systems (including those for Ada 83),
28186 and shows how GNAT can expedite porting
28187 applications developed in other Ada environments.
28188
28189 @menu
28190 * Compatibility with Ada 83::
28191 * Compatibility between Ada 95 and Ada 2005::
28192 * Implementation-dependent characteristics::
28193 * Compatibility with Other Ada Systems::
28194 * Representation Clauses::
28195 @ifclear vms
28196 @c Brief section is only in non-VMS version
28197 @c Full chapter is in VMS version
28198 * Compatibility with HP Ada 83::
28199 @end ifclear
28200 @ifset vms
28201 * Transitioning to 64-Bit GNAT for OpenVMS::
28202 @end ifset
28203 @end menu
28204
28205 @node Compatibility with Ada 83
28206 @section Compatibility with Ada 83
28207 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
28208
28209 @noindent
28210 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
28211 particular, the design intention was that the difficulties associated
28212 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
28213 that occur when moving from one Ada 83 system to another.
28214
28215 However, there are a number of points at which there are minor
28216 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
28217 full details of these issues,
28218 and should be consulted for a complete treatment.
28219 In practice the
28220 following subsections treat the most likely issues to be encountered.
28221
28222 @menu
28223 * Legal Ada 83 programs that are illegal in Ada 95::
28224 * More deterministic semantics::
28225 * Changed semantics::
28226 * Other language compatibility issues::
28227 @end menu
28228
28229 @node Legal Ada 83 programs that are illegal in Ada 95
28230 @subsection Legal Ada 83 programs that are illegal in Ada 95
28231
28232 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
28233 Ada 95 and thus also in Ada 2005:
28234
28235 @table @emph
28236 @item Character literals
28237 Some uses of character literals are ambiguous. Since Ada 95 has introduced
28238 @code{Wide_Character} as a new predefined character type, some uses of
28239 character literals that were legal in Ada 83 are illegal in Ada 95.
28240 For example:
28241 @smallexample @c ada
28242 for Char in 'A' .. 'Z' loop @dots{} end loop;
28243 @end smallexample
28244
28245 @noindent
28246 The problem is that @code{'A'} and @code{'Z'} could be from either
28247 @code{Character} or @code{Wide_Character}. The simplest correction
28248 is to make the type explicit; e.g.:
28249 @smallexample @c ada
28250 for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
28251 @end smallexample
28252
28253 @item New reserved words
28254 The identifiers @code{abstract}, @code{aliased}, @code{protected},
28255 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
28256 Existing Ada 83 code using any of these identifiers must be edited to
28257 use some alternative name.
28258
28259 @item Freezing rules
28260 The rules in Ada 95 are slightly different with regard to the point at
28261 which entities are frozen, and representation pragmas and clauses are
28262 not permitted past the freeze point. This shows up most typically in
28263 the form of an error message complaining that a representation item
28264 appears too late, and the appropriate corrective action is to move
28265 the item nearer to the declaration of the entity to which it refers.
28266
28267 A particular case is that representation pragmas
28268 @ifset vms
28269 (including the
28270 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
28271 @end ifset
28272 cannot be applied to a subprogram body. If necessary, a separate subprogram
28273 declaration must be introduced to which the pragma can be applied.
28274
28275 @item Optional bodies for library packages
28276 In Ada 83, a package that did not require a package body was nevertheless
28277 allowed to have one. This lead to certain surprises in compiling large
28278 systems (situations in which the body could be unexpectedly ignored by the
28279 binder). In Ada 95, if a package does not require a body then it is not
28280 permitted to have a body. To fix this problem, simply remove a redundant
28281 body if it is empty, or, if it is non-empty, introduce a dummy declaration
28282 into the spec that makes the body required. One approach is to add a private
28283 part to the package declaration (if necessary), and define a parameterless
28284 procedure called @code{Requires_Body}, which must then be given a dummy
28285 procedure body in the package body, which then becomes required.
28286 Another approach (assuming that this does not introduce elaboration
28287 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
28288 since one effect of this pragma is to require the presence of a package body.
28289
28290 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
28291 In Ada 95, the exception @code{Numeric_Error} is a renaming of
28292 @code{Constraint_Error}.
28293 This means that it is illegal to have separate exception handlers for
28294 the two exceptions. The fix is simply to remove the handler for the
28295 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
28296 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
28297
28298 @item Indefinite subtypes in generics
28299 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
28300 as the actual for a generic formal private type, but then the instantiation
28301 would be illegal if there were any instances of declarations of variables
28302 of this type in the generic body. In Ada 95, to avoid this clear violation
28303 of the methodological principle known as the ``contract model'',
28304 the generic declaration explicitly indicates whether
28305 or not such instantiations are permitted. If a generic formal parameter
28306 has explicit unknown discriminants, indicated by using @code{(<>)} after the
28307 subtype name, then it can be instantiated with indefinite types, but no
28308 stand-alone variables can be declared of this type. Any attempt to declare
28309 such a variable will result in an illegality at the time the generic is
28310 declared. If the @code{(<>)} notation is not used, then it is illegal
28311 to instantiate the generic with an indefinite type.
28312 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
28313 It will show up as a compile time error, and
28314 the fix is usually simply to add the @code{(<>)} to the generic declaration.
28315 @end table
28316
28317 @node More deterministic semantics
28318 @subsection More deterministic semantics
28319
28320 @table @emph
28321 @item Conversions
28322 Conversions from real types to integer types round away from 0. In Ada 83
28323 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
28324 implementation freedom was intended to support unbiased rounding in
28325 statistical applications, but in practice it interfered with portability.
28326 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
28327 is required. Numeric code may be affected by this change in semantics.
28328 Note, though, that this issue is no worse than already existed in Ada 83
28329 when porting code from one vendor to another.
28330
28331 @item Tasking
28332 The Real-Time Annex introduces a set of policies that define the behavior of
28333 features that were implementation dependent in Ada 83, such as the order in
28334 which open select branches are executed.
28335 @end table
28336
28337 @node Changed semantics
28338 @subsection Changed semantics
28339
28340 @noindent
28341 The worst kind of incompatibility is one where a program that is legal in
28342 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
28343 possible in Ada 83. Fortunately this is extremely rare, but the one
28344 situation that you should be alert to is the change in the predefined type
28345 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
28346
28347 @table @emph
28348 @item Range of type @code{Character}
28349 The range of @code{Standard.Character} is now the full 256 characters
28350 of Latin-1, whereas in most Ada 83 implementations it was restricted
28351 to 128 characters. Although some of the effects of
28352 this change will be manifest in compile-time rejection of legal
28353 Ada 83 programs it is possible for a working Ada 83 program to have
28354 a different effect in Ada 95, one that was not permitted in Ada 83.
28355 As an example, the expression
28356 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
28357 delivers @code{255} as its value.
28358 In general, you should look at the logic of any
28359 character-processing Ada 83 program and see whether it needs to be adapted
28360 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
28361 character handling package that may be relevant if code needs to be adapted
28362 to account for the additional Latin-1 elements.
28363 The desirable fix is to
28364 modify the program to accommodate the full character set, but in some cases
28365 it may be convenient to define a subtype or derived type of Character that
28366 covers only the restricted range.
28367 @cindex Latin-1
28368 @end table
28369
28370 @node Other language compatibility issues
28371 @subsection Other language compatibility issues
28372
28373 @table @emph
28374 @item @option{-gnat83} switch
28375 All implementations of GNAT provide a switch that causes GNAT to operate
28376 in Ada 83 mode. In this mode, some but not all compatibility problems
28377 of the type described above are handled automatically. For example, the
28378 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
28379 as identifiers as in Ada 83.
28380 However,
28381 in practice, it is usually advisable to make the necessary modifications
28382 to the program to remove the need for using this switch.
28383 See @ref{Compiling Different Versions of Ada}.
28384
28385 @item Support for removed Ada 83 pragmas and attributes
28386 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
28387 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
28388 compilers are allowed, but not required, to implement these missing
28389 elements. In contrast with some other compilers, GNAT implements all
28390 such pragmas and attributes, eliminating this compatibility concern. These
28391 include @code{pragma Interface} and the floating point type attributes
28392 (@code{Emax}, @code{Mantissa}, etc.), among other items.
28393 @end table
28394
28395
28396 @node Compatibility between Ada 95 and Ada 2005
28397 @section Compatibility between Ada 95 and Ada 2005
28398 @cindex Compatibility between Ada 95 and Ada 2005
28399
28400 @noindent
28401 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
28402 a number of incompatibilities. Several are enumerated below;
28403 for a complete description please see the
28404 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
28405 @cite{Rationale for Ada 2005}.
28406
28407 @table @emph
28408 @item New reserved words.
28409 The words @code{interface}, @code{overriding} and @code{synchronized} are
28410 reserved in Ada 2005.
28411 A pre-Ada 2005 program that uses any of these as an identifier will be
28412 illegal.
28413
28414 @item New declarations in predefined packages.
28415 A number of packages in the predefined environment contain new declarations:
28416 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
28417 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
28418 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
28419 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
28420 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
28421 If an Ada 95 program does a @code{with} and @code{use} of any of these
28422 packages, the new declarations may cause name clashes.
28423
28424 @item Access parameters.
28425 A nondispatching subprogram with an access parameter cannot be renamed
28426 as a dispatching operation. This was permitted in Ada 95.
28427
28428 @item Access types, discriminants, and constraints.
28429 Rule changes in this area have led to some incompatibilities; for example,
28430 constrained subtypes of some access types are not permitted in Ada 2005.
28431
28432 @item Aggregates for limited types.
28433 The allowance of aggregates for limited types in Ada 2005 raises the
28434 possibility of ambiguities in legal Ada 95 programs, since additional types
28435 now need to be considered in expression resolution.
28436
28437 @item Fixed-point multiplication and division.
28438 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
28439 were legal in Ada 95 and invoked the predefined versions of these operations,
28440 are now ambiguous.
28441 The ambiguity may be resolved either by applying a type conversion to the
28442 expression, or by explicitly invoking the operation from package
28443 @code{Standard}.
28444
28445 @item Return-by-reference types.
28446 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
28447 can declare a function returning a value from an anonymous access type.
28448 @end table
28449
28450
28451 @node Implementation-dependent characteristics
28452 @section Implementation-dependent characteristics
28453 @noindent
28454 Although the Ada language defines the semantics of each construct as
28455 precisely as practical, in some situations (for example for reasons of
28456 efficiency, or where the effect is heavily dependent on the host or target
28457 platform) the implementation is allowed some freedom. In porting Ada 83
28458 code to GNAT, you need to be aware of whether / how the existing code
28459 exercised such implementation dependencies. Such characteristics fall into
28460 several categories, and GNAT offers specific support in assisting the
28461 transition from certain Ada 83 compilers.
28462
28463 @menu
28464 * Implementation-defined pragmas::
28465 * Implementation-defined attributes::
28466 * Libraries::
28467 * Elaboration order::
28468 * Target-specific aspects::
28469 @end menu
28470
28471 @node Implementation-defined pragmas
28472 @subsection Implementation-defined pragmas
28473
28474 @noindent
28475 Ada compilers are allowed to supplement the language-defined pragmas, and
28476 these are a potential source of non-portability. All GNAT-defined pragmas
28477 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
28478 Reference Manual}, and these include several that are specifically
28479 intended to correspond to other vendors' Ada 83 pragmas.
28480 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
28481 For compatibility with HP Ada 83, GNAT supplies the pragmas
28482 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
28483 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
28484 and @code{Volatile}.
28485 Other relevant pragmas include @code{External} and @code{Link_With}.
28486 Some vendor-specific
28487 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
28488 recognized, thus
28489 avoiding compiler rejection of units that contain such pragmas; they are not
28490 relevant in a GNAT context and hence are not otherwise implemented.
28491
28492 @node Implementation-defined attributes
28493 @subsection Implementation-defined attributes
28494
28495 Analogous to pragmas, the set of attributes may be extended by an
28496 implementation. All GNAT-defined attributes are described in
28497 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
28498 Manual}, and these include several that are specifically intended
28499 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
28500 the attribute @code{VADS_Size} may be useful. For compatibility with HP
28501 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
28502 @code{Type_Class}.
28503
28504 @node Libraries
28505 @subsection Libraries
28506 @noindent
28507 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
28508 code uses vendor-specific libraries then there are several ways to manage
28509 this in Ada 95 or Ada 2005:
28510 @enumerate
28511 @item
28512 If the source code for the libraries (specs and bodies) are
28513 available, then the libraries can be migrated in the same way as the
28514 application.
28515 @item
28516 If the source code for the specs but not the bodies are
28517 available, then you can reimplement the bodies.
28518 @item
28519 Some features introduced by Ada 95 obviate the need for library support. For
28520 example most Ada 83 vendors supplied a package for unsigned integers. The
28521 Ada 95 modular type feature is the preferred way to handle this need, so
28522 instead of migrating or reimplementing the unsigned integer package it may
28523 be preferable to retrofit the application using modular types.
28524 @end enumerate
28525
28526 @node Elaboration order
28527 @subsection Elaboration order
28528 @noindent
28529 The implementation can choose any elaboration order consistent with the unit
28530 dependency relationship. This freedom means that some orders can result in
28531 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
28532 to invoke a subprogram its body has been elaborated, or to instantiate a
28533 generic before the generic body has been elaborated. By default GNAT
28534 attempts to choose a safe order (one that will not encounter access before
28535 elaboration problems) by implicitly inserting @code{Elaborate} or
28536 @code{Elaborate_All} pragmas where
28537 needed. However, this can lead to the creation of elaboration circularities
28538 and a resulting rejection of the program by gnatbind. This issue is
28539 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
28540 In brief, there are several
28541 ways to deal with this situation:
28542
28543 @itemize @bullet
28544 @item
28545 Modify the program to eliminate the circularities, e.g.@: by moving
28546 elaboration-time code into explicitly-invoked procedures
28547 @item
28548 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
28549 @code{Elaborate} pragmas, and then inhibit the generation of implicit
28550 @code{Elaborate_All}
28551 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
28552 (by selectively suppressing elaboration checks via pragma
28553 @code{Suppress(Elaboration_Check)} when it is safe to do so).
28554 @end itemize
28555
28556 @node Target-specific aspects
28557 @subsection Target-specific aspects
28558 @noindent
28559 Low-level applications need to deal with machine addresses, data
28560 representations, interfacing with assembler code, and similar issues. If
28561 such an Ada 83 application is being ported to different target hardware (for
28562 example where the byte endianness has changed) then you will need to
28563 carefully examine the program logic; the porting effort will heavily depend
28564 on the robustness of the original design. Moreover, Ada 95 (and thus
28565 Ada 2005) are sometimes
28566 incompatible with typical Ada 83 compiler practices regarding implicit
28567 packing, the meaning of the Size attribute, and the size of access values.
28568 GNAT's approach to these issues is described in @ref{Representation Clauses}.
28569
28570 @node Compatibility with Other Ada Systems
28571 @section Compatibility with Other Ada Systems
28572
28573 @noindent
28574 If programs avoid the use of implementation dependent and
28575 implementation defined features, as documented in the @cite{Ada
28576 Reference Manual}, there should be a high degree of portability between
28577 GNAT and other Ada systems. The following are specific items which
28578 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
28579 compilers, but do not affect porting code to GNAT@.
28580 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
28581 the following issues may or may not arise for Ada 2005 programs
28582 when other compilers appear.)
28583
28584 @table @emph
28585 @item Ada 83 Pragmas and Attributes
28586 Ada 95 compilers are allowed, but not required, to implement the missing
28587 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
28588 GNAT implements all such pragmas and attributes, eliminating this as
28589 a compatibility concern, but some other Ada 95 compilers reject these
28590 pragmas and attributes.
28591
28592 @item Specialized Needs Annexes
28593 GNAT implements the full set of special needs annexes. At the
28594 current time, it is the only Ada 95 compiler to do so. This means that
28595 programs making use of these features may not be portable to other Ada
28596 95 compilation systems.
28597
28598 @item Representation Clauses
28599 Some other Ada 95 compilers implement only the minimal set of
28600 representation clauses required by the Ada 95 reference manual. GNAT goes
28601 far beyond this minimal set, as described in the next section.
28602 @end table
28603
28604 @node Representation Clauses
28605 @section Representation Clauses
28606
28607 @noindent
28608 The Ada 83 reference manual was quite vague in describing both the minimal
28609 required implementation of representation clauses, and also their precise
28610 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
28611 minimal set of capabilities required is still quite limited.
28612
28613 GNAT implements the full required set of capabilities in
28614 Ada 95 and Ada 2005, but also goes much further, and in particular
28615 an effort has been made to be compatible with existing Ada 83 usage to the
28616 greatest extent possible.
28617
28618 A few cases exist in which Ada 83 compiler behavior is incompatible with
28619 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
28620 intentional or accidental dependence on specific implementation dependent
28621 characteristics of these Ada 83 compilers. The following is a list of
28622 the cases most likely to arise in existing Ada 83 code.
28623
28624 @table @emph
28625 @item Implicit Packing
28626 Some Ada 83 compilers allowed a Size specification to cause implicit
28627 packing of an array or record. This could cause expensive implicit
28628 conversions for change of representation in the presence of derived
28629 types, and the Ada design intends to avoid this possibility.
28630 Subsequent AI's were issued to make it clear that such implicit
28631 change of representation in response to a Size clause is inadvisable,
28632 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
28633 Reference Manuals as implementation advice that is followed by GNAT@.
28634 The problem will show up as an error
28635 message rejecting the size clause. The fix is simply to provide
28636 the explicit pragma @code{Pack}, or for more fine tuned control, provide
28637 a Component_Size clause.
28638
28639 @item Meaning of Size Attribute
28640 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
28641 the minimal number of bits required to hold values of the type. For example,
28642 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
28643 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
28644 some 32 in this situation. This problem will usually show up as a compile
28645 time error, but not always. It is a good idea to check all uses of the
28646 'Size attribute when porting Ada 83 code. The GNAT specific attribute
28647 Object_Size can provide a useful way of duplicating the behavior of
28648 some Ada 83 compiler systems.
28649
28650 @item Size of Access Types
28651 A common assumption in Ada 83 code is that an access type is in fact a pointer,
28652 and that therefore it will be the same size as a System.Address value. This
28653 assumption is true for GNAT in most cases with one exception. For the case of
28654 a pointer to an unconstrained array type (where the bounds may vary from one
28655 value of the access type to another), the default is to use a ``fat pointer'',
28656 which is represented as two separate pointers, one to the bounds, and one to
28657 the array. This representation has a number of advantages, including improved
28658 efficiency. However, it may cause some difficulties in porting existing Ada 83
28659 code which makes the assumption that, for example, pointers fit in 32 bits on
28660 a machine with 32-bit addressing.
28661
28662 To get around this problem, GNAT also permits the use of ``thin pointers'' for
28663 access types in this case (where the designated type is an unconstrained array
28664 type). These thin pointers are indeed the same size as a System.Address value.
28665 To specify a thin pointer, use a size clause for the type, for example:
28666
28667 @smallexample @c ada
28668 type X is access all String;
28669 for X'Size use Standard'Address_Size;
28670 @end smallexample
28671
28672 @noindent
28673 which will cause the type X to be represented using a single pointer.
28674 When using this representation, the bounds are right behind the array.
28675 This representation is slightly less efficient, and does not allow quite
28676 such flexibility in the use of foreign pointers or in using the
28677 Unrestricted_Access attribute to create pointers to non-aliased objects.
28678 But for any standard portable use of the access type it will work in
28679 a functionally correct manner and allow porting of existing code.
28680 Note that another way of forcing a thin pointer representation
28681 is to use a component size clause for the element size in an array,
28682 or a record representation clause for an access field in a record.
28683 @end table
28684
28685 @ifclear vms
28686 @c This brief section is only in the non-VMS version
28687 @c The complete chapter on HP Ada is in the VMS version
28688 @node Compatibility with HP Ada 83
28689 @section Compatibility with HP Ada 83
28690
28691 @noindent
28692 The VMS version of GNAT fully implements all the pragmas and attributes
28693 provided by HP Ada 83, as well as providing the standard HP Ada 83
28694 libraries, including Starlet. In addition, data layouts and parameter
28695 passing conventions are highly compatible. This means that porting
28696 existing HP Ada 83 code to GNAT in VMS systems should be easier than
28697 most other porting efforts. The following are some of the most
28698 significant differences between GNAT and HP Ada 83.
28699
28700 @table @emph
28701 @item Default floating-point representation
28702 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
28703 it is VMS format. GNAT does implement the necessary pragmas
28704 (Long_Float, Float_Representation) for changing this default.
28705
28706 @item System
28707 The package System in GNAT exactly corresponds to the definition in the
28708 Ada 95 reference manual, which means that it excludes many of the
28709 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
28710 that contains the additional definitions, and a special pragma,
28711 Extend_System allows this package to be treated transparently as an
28712 extension of package System.
28713
28714 @item To_Address
28715 The definitions provided by Aux_DEC are exactly compatible with those
28716 in the HP Ada 83 version of System, with one exception.
28717 HP Ada provides the following declarations:
28718
28719 @smallexample @c ada
28720 TO_ADDRESS (INTEGER)
28721 TO_ADDRESS (UNSIGNED_LONGWORD)
28722 TO_ADDRESS (@i{universal_integer})
28723 @end smallexample
28724
28725 @noindent
28726 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
28727 an extension to Ada 83 not strictly compatible with the reference manual.
28728 In GNAT, we are constrained to be exactly compatible with the standard,
28729 and this means we cannot provide this capability. In HP Ada 83, the
28730 point of this definition is to deal with a call like:
28731
28732 @smallexample @c ada
28733 TO_ADDRESS (16#12777#);
28734 @end smallexample
28735
28736 @noindent
28737 Normally, according to the Ada 83 standard, one would expect this to be
28738 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
28739 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
28740 definition using @i{universal_integer} takes precedence.
28741
28742 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
28743 is not possible to be 100% compatible. Since there are many programs using
28744 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
28745 to change the name of the function in the UNSIGNED_LONGWORD case, so the
28746 declarations provided in the GNAT version of AUX_Dec are:
28747
28748 @smallexample @c ada
28749 function To_Address (X : Integer) return Address;
28750 pragma Pure_Function (To_Address);
28751
28752 function To_Address_Long (X : Unsigned_Longword)
28753 return Address;
28754 pragma Pure_Function (To_Address_Long);
28755 @end smallexample
28756
28757 @noindent
28758 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
28759 change the name to TO_ADDRESS_LONG@.
28760
28761 @item Task_Id values
28762 The Task_Id values assigned will be different in the two systems, and GNAT
28763 does not provide a specified value for the Task_Id of the environment task,
28764 which in GNAT is treated like any other declared task.
28765 @end table
28766
28767 @noindent
28768 For full details on these and other less significant compatibility issues,
28769 see appendix E of the HP publication entitled @cite{HP Ada, Technical
28770 Overview and Comparison on HP Platforms}.
28771
28772 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
28773 attributes are recognized, although only a subset of them can sensibly
28774 be implemented. The description of pragmas in @ref{Implementation
28775 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
28776 indicates whether or not they are applicable to non-VMS systems.
28777 @end ifclear
28778
28779 @ifset vms
28780 @node Transitioning to 64-Bit GNAT for OpenVMS
28781 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
28782
28783 @noindent
28784 This section is meant to assist users of pre-2006 @value{EDITION}
28785 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
28786 the version of the GNAT technology supplied in 2006 and later for
28787 OpenVMS on both Alpha and I64.
28788
28789 @menu
28790 * Introduction to transitioning::
28791 * Migration of 32 bit code::
28792 * Taking advantage of 64 bit addressing::
28793 * Technical details::
28794 @end menu
28795
28796 @node Introduction to transitioning
28797 @subsection Introduction
28798
28799 @noindent
28800 64-bit @value{EDITION} for Open VMS has been designed to meet
28801 three main goals:
28802
28803 @enumerate
28804 @item
28805 Providing a full conforming implementation of Ada 95 and Ada 2005
28806
28807 @item
28808 Allowing maximum backward compatibility, thus easing migration of existing
28809 Ada source code
28810
28811 @item
28812 Supplying a path for exploiting the full 64-bit address range
28813 @end enumerate
28814
28815 @noindent
28816 Ada's strong typing semantics has made it
28817 impractical to have different 32-bit and 64-bit modes. As soon as
28818 one object could possibly be outside the 32-bit address space, this
28819 would make it necessary for the @code{System.Address} type to be 64 bits.
28820 In particular, this would cause inconsistencies if 32-bit code is
28821 called from 64-bit code that raises an exception.
28822
28823 This issue has been resolved by always using 64-bit addressing
28824 at the system level, but allowing for automatic conversions between
28825 32-bit and 64-bit addresses where required. Thus users who
28826 do not currently require 64-bit addressing capabilities, can
28827 recompile their code with only minimal changes (and indeed
28828 if the code is written in portable Ada, with no assumptions about
28829 the size of the @code{Address} type, then no changes at all are necessary).
28830 At the same time,
28831 this approach provides a simple, gradual upgrade path to future
28832 use of larger memories than available for 32-bit systems.
28833 Also, newly written applications or libraries will by default
28834 be fully compatible with future systems exploiting 64-bit
28835 addressing capabilities.
28836
28837 @ref{Migration of 32 bit code}, will focus on porting applications
28838 that do not require more than 2 GB of
28839 addressable memory. This code will be referred to as
28840 @emph{32-bit code}.
28841 For applications intending to exploit the full 64-bit address space,
28842 @ref{Taking advantage of 64 bit addressing},
28843 will consider further changes that may be required.
28844 Such code will be referred to below as @emph{64-bit code}.
28845
28846 @node Migration of 32 bit code
28847 @subsection Migration of 32-bit code
28848
28849 @menu
28850 * Address types::
28851 * Access types and 32/64-bit allocation::
28852 * Unchecked conversions::
28853 * Predefined constants::
28854 * Interfacing with C::
28855 * 32/64-bit descriptors::
28856 * Experience with source compatibility::
28857 @end menu
28858
28859 @node Address types
28860 @subsubsection Address types
28861
28862 @noindent
28863 To solve the problem of mixing 64-bit and 32-bit addressing,
28864 while maintaining maximum backward compatibility, the following
28865 approach has been taken:
28866
28867 @itemize @bullet
28868 @item
28869 @code{System.Address} always has a size of 64 bits
28870 @cindex @code{System.Address} size
28871 @cindex @code{Address} size
28872
28873 @item
28874 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
28875 @cindex @code{System.Short_Address} size
28876 @cindex @code{Short_Address} size
28877 @end itemize
28878
28879 @noindent
28880 Since @code{System.Short_Address} is a subtype of @code{System.Address},
28881 a @code{Short_Address}
28882 may be used where an @code{Address} is required, and vice versa, without
28883 needing explicit type conversions.
28884 By virtue of the Open VMS parameter passing conventions,
28885 even imported
28886 and exported subprograms that have 32-bit address parameters are
28887 compatible with those that have 64-bit address parameters.
28888 (See @ref{Making code 64 bit clean} for details.)
28889
28890 The areas that may need attention are those where record types have
28891 been defined that contain components of the type @code{System.Address}, and
28892 where objects of this type are passed to code expecting a record layout with
28893 32-bit addresses.
28894
28895 Different compilers on different platforms cannot be
28896 expected to represent the same type in the same way,
28897 since alignment constraints
28898 and other system-dependent properties affect the compiler's decision.
28899 For that reason, Ada code
28900 generally uses representation clauses to specify the expected
28901 layout where required.
28902
28903 If such a representation clause uses 32 bits for a component having
28904 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
28905 will detect that error and produce a specific diagnostic message.
28906 The developer should then determine whether the representation
28907 should be 64 bits or not and make either of two changes:
28908 change the size to 64 bits and leave the type as @code{System.Address}, or
28909 leave the size as 32 bits and change the type to @code{System.Short_Address}.
28910 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
28911 required in any code setting or accessing the field; the compiler will
28912 automatically perform any needed conversions between address
28913 formats.
28914
28915 @node Access types and 32/64-bit allocation
28916 @subsubsection Access types and 32/64-bit allocation
28917 @cindex 32-bit allocation
28918 @cindex 64-bit allocation
28919
28920 @noindent
28921 By default, objects designated by access values are always allocated in
28922 the 64-bit address space, and access values themselves are represented
28923 in 64 bits. If these defaults are not appropriate, and 32-bit allocation
28924 is required (for example if the address of an allocated object is assigned
28925 to a @code{Short_Address} variable), then several alternatives are available:
28926
28927 @itemize @bullet
28928 @item
28929 A pool-specific access type (ie, an @w{Ada 83} access type, whose
28930 definition is @code{access T} versus @code{access all T} or
28931 @code{access constant T}), may be declared with a @code{'Size} representation
28932 clause that establishes the size as 32 bits.
28933 In such circumstances allocations for that type will
28934 be from the 32-bit heap. Such a clause is not permitted
28935 for a general access type (declared with @code{access all} or
28936 @code{access constant}) as values of such types must be able to refer
28937 to any object of the designated type, including objects residing outside
28938 the 32-bit address range. Existing @w{Ada 83} code will not contain such
28939 type definitions, however, since general access types were introduced
28940 in @w{Ada 95}.
28941
28942 @item
28943 Switches for @command{GNAT BIND} control whether the internal GNAT
28944 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
28945 @cindex @code{__gnat_malloc}
28946 The switches are respectively @option{-H64} (the default) and
28947 @option{-H32}.
28948 @cindex @option{-H32} (@command{gnatbind})
28949 @cindex @option{-H64} (@command{gnatbind})
28950
28951 @item
28952 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
28953 @cindex @code{GNAT$NO_MALLOC_64} environment variable
28954 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
28955 If this variable is left
28956 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
28957 then the default (64-bit) allocation is used.
28958 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
28959 then 32-bit allocation is used. The gnatbind qualifiers described above
28960 override this logical name.
28961
28962 @item
28963 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
28964 @cindex @option{-mno-malloc64} (^gcc^gcc^)
28965 at a low level to convert explicit calls to @code{malloc} and related
28966 functions from the C run-time library so that they perform allocations
28967 in the 32-bit heap.
28968 Since all internal allocations from GNAT use @code{__gnat_malloc},
28969 this switch is not required unless the program makes explicit calls on
28970 @code{malloc} (or related functions) from interfaced C code.
28971 @end itemize
28972
28973
28974 @node Unchecked conversions
28975 @subsubsection Unchecked conversions
28976
28977 @noindent
28978 In the case of an @code{Unchecked_Conversion} where the source type is a
28979 64-bit access type or the type @code{System.Address}, and the target
28980 type is a 32-bit type, the compiler will generate a warning.
28981 Even though the generated code will still perform the required
28982 conversions, it is highly recommended in these cases to use
28983 respectively a 32-bit access type or @code{System.Short_Address}
28984 as the source type.
28985
28986 @node Predefined constants
28987 @subsubsection Predefined constants
28988
28989 @noindent
28990 The following table shows the correspondence between pre-2006 versions of
28991 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
28992 (``New''):
28993
28994 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
28995 @item @b{Constant} @tab @b{Old} @tab @b{New}
28996 @item @code{System.Word_Size} @tab 32 @tab 64
28997 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
28998 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
28999 @item @code{System.Address_Size} @tab 32 @tab 64
29000 @end multitable
29001
29002 @noindent
29003 If you need to refer to the specific
29004 memory size of a 32-bit implementation, instead of the
29005 actual memory size, use @code{System.Short_Memory_Size}
29006 rather than @code{System.Memory_Size}.
29007 Similarly, references to @code{System.Address_Size} may need
29008 to be replaced by @code{System.Short_Address'Size}.
29009 The program @command{gnatfind} may be useful for locating
29010 references to the above constants, so that you can verify that they
29011 are still correct.
29012
29013 @node Interfacing with C
29014 @subsubsection Interfacing with C
29015
29016 @noindent
29017 In order to minimize the impact of the transition to 64-bit addresses on
29018 legacy programs, some fundamental types in the @code{Interfaces.C}
29019 package hierarchy continue to be represented in 32 bits.
29020 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
29021 This eases integration with the default HP C layout choices, for example
29022 as found in the system routines in @code{DECC$SHR.EXE}.
29023 Because of this implementation choice, the type fully compatible with
29024 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
29025 Depending on the context the compiler will issue a
29026 warning or an error when type @code{Address} is used, alerting the user to a
29027 potential problem. Otherwise 32-bit programs that use
29028 @code{Interfaces.C} should normally not require code modifications
29029
29030 The other issue arising with C interfacing concerns pragma @code{Convention}.
29031 For VMS 64-bit systems, there is an issue of the appropriate default size
29032 of C convention pointers in the absence of an explicit size clause. The HP
29033 C compiler can choose either 32 or 64 bits depending on compiler options.
29034 GNAT chooses 32-bits rather than 64-bits in the default case where no size
29035 clause is given. This proves a better choice for porting 32-bit legacy
29036 applications. In order to have a 64-bit representation, it is necessary to
29037 specify a size representation clause. For example:
29038
29039 @smallexample @c ada
29040 type int_star is access Interfaces.C.int;
29041 pragma Convention(C, int_star);
29042 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
29043 @end smallexample
29044
29045 @node 32/64-bit descriptors
29046 @subsubsection 32/64-bit descriptors
29047
29048 @noindent
29049 By default, GNAT uses a 64-bit descriptor mechanism. For an imported
29050 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
29051 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
29052 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
29053 @cindex @code{Short_Descriptor} mechanism for imported subprograms
29054
29055 If the configuration pragma @code{Short_Descriptors} is supplied, then
29056 all descriptors will be 32 bits.
29057 @cindex pragma @code{Short_Descriptors}
29058
29059 @node Experience with source compatibility
29060 @subsubsection Experience with source compatibility
29061
29062 @noindent
29063 The Security Server and STARLET on I64 provide an interesting ``test case''
29064 for source compatibility issues, since it is in such system code
29065 where assumptions about @code{Address} size might be expected to occur.
29066 Indeed, there were a small number of occasions in the Security Server
29067 file @file{jibdef.ads}
29068 where a representation clause for a record type specified
29069 32 bits for a component of type @code{Address}.
29070 All of these errors were detected by the compiler.
29071 The repair was obvious and immediate; to simply replace @code{Address} by
29072 @code{Short_Address}.
29073
29074 In the case of STARLET, there were several record types that should
29075 have had representation clauses but did not. In these record types
29076 there was an implicit assumption that an @code{Address} value occupied
29077 32 bits.
29078 These compiled without error, but their usage resulted in run-time error
29079 returns from STARLET system calls.
29080 Future GNAT technology enhancements may include a tool that detects and flags
29081 these sorts of potential source code porting problems.
29082
29083 @c ****************************************
29084 @node Taking advantage of 64 bit addressing
29085 @subsection Taking advantage of 64-bit addressing
29086
29087 @menu
29088 * Making code 64 bit clean::
29089 * Allocating memory from the 64 bit storage pool::
29090 * Restrictions on use of 64 bit objects::
29091 * STARLET and other predefined libraries::
29092 @end menu
29093
29094 @node Making code 64 bit clean
29095 @subsubsection Making code 64-bit clean
29096
29097 @noindent
29098 In order to prevent problems that may occur when (parts of) a
29099 system start using memory outside the 32-bit address range,
29100 we recommend some additional guidelines:
29101
29102 @itemize @bullet
29103 @item
29104 For imported subprograms that take parameters of the
29105 type @code{System.Address}, ensure that these subprograms can
29106 indeed handle 64-bit addresses. If not, or when in doubt,
29107 change the subprogram declaration to specify
29108 @code{System.Short_Address} instead.
29109
29110 @item
29111 Resolve all warnings related to size mismatches in
29112 unchecked conversions. Failing to do so causes
29113 erroneous execution if the source object is outside
29114 the 32-bit address space.
29115
29116 @item
29117 (optional) Explicitly use the 32-bit storage pool
29118 for access types used in a 32-bit context, or use
29119 generic access types where possible
29120 (@pxref{Restrictions on use of 64 bit objects}).
29121 @end itemize
29122
29123 @noindent
29124 If these rules are followed, the compiler will automatically insert
29125 any necessary checks to ensure that no addresses or access values
29126 passed to 32-bit code ever refer to objects outside the 32-bit
29127 address range.
29128 Any attempt to do this will raise @code{Constraint_Error}.
29129
29130 @node Allocating memory from the 64 bit storage pool
29131 @subsubsection Allocating memory from the 64-bit storage pool
29132
29133 @noindent
29134 By default, all allocations -- for both pool-specific and general
29135 access types -- use the 64-bit storage pool. To override
29136 this default, for an individual access type or globally, see
29137 @ref{Access types and 32/64-bit allocation}.
29138
29139 @node Restrictions on use of 64 bit objects
29140 @subsubsection Restrictions on use of 64-bit objects
29141
29142 @noindent
29143 Taking the address of an object allocated from a 64-bit storage pool,
29144 and then passing this address to a subprogram expecting
29145 @code{System.Short_Address},
29146 or assigning it to a variable of type @code{Short_Address}, will cause
29147 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
29148 (@pxref{Making code 64 bit clean}), or checks are suppressed,
29149 no exception is raised and execution
29150 will become erroneous.
29151
29152 @node STARLET and other predefined libraries
29153 @subsubsection STARLET and other predefined libraries
29154
29155 @noindent
29156 All code that comes as part of GNAT is 64-bit clean, but the
29157 restrictions given in @ref{Restrictions on use of 64 bit objects},
29158 still apply. Look at the package
29159 specs to see in which contexts objects allocated
29160 in 64-bit address space are acceptable.
29161
29162 @node Technical details
29163 @subsection Technical details
29164
29165 @noindent
29166 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
29167 Ada standard with respect to the type of @code{System.Address}. Previous
29168 versions of @value{EDITION} have defined this type as private and implemented it as a
29169 modular type.
29170
29171 In order to allow defining @code{System.Short_Address} as a proper subtype,
29172 and to match the implicit sign extension in parameter passing,
29173 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
29174 visible (i.e., non-private) integer type.
29175 Standard operations on the type, such as the binary operators ``+'', ``-'',
29176 etc., that take @code{Address} operands and return an @code{Address} result,
29177 have been hidden by declaring these
29178 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
29179 ambiguities that would otherwise result from overloading.
29180 (Note that, although @code{Address} is a visible integer type,
29181 good programming practice dictates against exploiting the type's
29182 integer properties such as literals, since this will compromise
29183 code portability.)
29184
29185 Defining @code{Address} as a visible integer type helps achieve
29186 maximum compatibility for existing Ada code,
29187 without sacrificing the capabilities of the 64-bit architecture.
29188 @end ifset
29189
29190 @c ************************************************
29191 @node Microsoft Windows Topics
29192 @appendix Microsoft Windows Topics
29193 @cindex Windows NT
29194 @cindex Windows 95
29195 @cindex Windows 98
29196
29197 @noindent
29198 This chapter describes topics that are specific to the Microsoft Windows
29199 platforms (NT, 2000, and XP Professional).
29200
29201 @menu
29202 @ifclear FSFEDITION
29203 * Installing from the Command Line::
29204 @end ifclear
29205 * Using GNAT on Windows::
29206 * Using a network installation of GNAT::
29207 * CONSOLE and WINDOWS subsystems::
29208 * Temporary Files::
29209 * Mixed-Language Programming on Windows::
29210 * Windows Calling Conventions::
29211 * Introduction to Dynamic Link Libraries (DLLs)::
29212 * Using DLLs with GNAT::
29213 * Building DLLs with GNAT Project files::
29214 * Building DLLs with GNAT::
29215 * Building DLLs with gnatdll::
29216 * GNAT and Windows Resources::
29217 * Debugging a DLL::
29218 * Setting Stack Size from gnatlink::
29219 * Setting Heap Size from gnatlink::
29220 @end menu
29221
29222 @ifclear FSFEDITION
29223 @node Installing from the Command Line
29224 @section Installing from the Command Line
29225 @cindex Batch installation
29226 @cindex Silent installation
29227 @cindex Unassisted installation
29228
29229 @noindent
29230 By default the @value{EDITION} installers display a GUI that prompts the user
29231 to enter installation path and similar information, and guide him through the
29232 installation process. It is also possible to perform silent installations
29233 using the command-line interface.
29234
29235 In order to install one of the @value{EDITION} installers from the command
29236 line you should pass parameter @code{/S} (and, optionally,
29237 @code{/D=<directory>}) as command-line arguments.
29238
29239 @ifset PROEDITION
29240 For example, for an unattended installation of
29241 @value{EDITION} 7.0.2 into the default directory
29242 @code{C:\GNATPRO\7.0.2} you would run:
29243
29244 @smallexample
29245 gnatpro-7.0.2-i686-pc-mingw32-bin.exe /S
29246 @end smallexample
29247
29248 To install into a custom directory, say, @code{C:\TOOLS\GNATPRO\7.0.2}:
29249
29250 @smallexample
29251 gnatpro-7.0.2-i686-pc-mingw32-bin /S /D=C:\TOOLS\GNATPRO\7.0.2
29252 @end smallexample
29253 @end ifset
29254
29255 @ifset GPLEDITION
29256 For example, for an unattended installation of
29257 @value{EDITION} 2012 into @code{C:\GNAT\2012}:
29258
29259 @smallexample
29260 gnat-gpl-2012-i686-pc-mingw32-bin /S /D=C:\GNAT\2012
29261 @end smallexample
29262 @end ifset
29263
29264 You can use the same syntax for all installers.
29265
29266 Note that unattended installations don't modify system path, nor create file
29267 associations, so such activities need to be done by hand.
29268 @end ifclear
29269
29270 @node Using GNAT on Windows
29271 @section Using GNAT on Windows
29272
29273 @noindent
29274 One of the strengths of the GNAT technology is that its tool set
29275 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
29276 @code{gdb} debugger, etc.) is used in the same way regardless of the
29277 platform.
29278
29279 On Windows this tool set is complemented by a number of Microsoft-specific
29280 tools that have been provided to facilitate interoperability with Windows
29281 when this is required. With these tools:
29282
29283 @itemize @bullet
29284
29285 @item
29286 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
29287 subsystems.
29288
29289 @item
29290 You can use any Dynamically Linked Library (DLL) in your Ada code (both
29291 relocatable and non-relocatable DLLs are supported).
29292
29293 @item
29294 You can build Ada DLLs for use in other applications. These applications
29295 can be written in a language other than Ada (e.g., C, C++, etc). Again both
29296 relocatable and non-relocatable Ada DLLs are supported.
29297
29298 @item
29299 You can include Windows resources in your Ada application.
29300
29301 @item
29302 You can use or create COM/DCOM objects.
29303 @end itemize
29304
29305 @noindent
29306 Immediately below are listed all known general GNAT-for-Windows restrictions.
29307 Other restrictions about specific features like Windows Resources and DLLs
29308 are listed in separate sections below.
29309
29310 @itemize @bullet
29311
29312 @item
29313 It is not possible to use @code{GetLastError} and @code{SetLastError}
29314 when tasking, protected records, or exceptions are used. In these
29315 cases, in order to implement Ada semantics, the GNAT run-time system
29316 calls certain Win32 routines that set the last error variable to 0 upon
29317 success. It should be possible to use @code{GetLastError} and
29318 @code{SetLastError} when tasking, protected record, and exception
29319 features are not used, but it is not guaranteed to work.
29320
29321 @item
29322 It is not possible to link against Microsoft C++ libraries except for
29323 import libraries. Interfacing must be done by the mean of DLLs.
29324
29325 @item
29326 It is possible to link against Microsoft C libraries. Yet the preferred
29327 solution is to use C/C++ compiler that comes with @value{EDITION}, since it
29328 doesn't require having two different development environments and makes the
29329 inter-language debugging experience smoother.
29330
29331 @item
29332 When the compilation environment is located on FAT32 drives, users may
29333 experience recompilations of the source files that have not changed if
29334 Daylight Saving Time (DST) state has changed since the last time files
29335 were compiled. NTFS drives do not have this problem.
29336
29337 @item
29338 No components of the GNAT toolset use any entries in the Windows
29339 registry. The only entries that can be created are file associations and
29340 PATH settings, provided the user has chosen to create them at installation
29341 time, as well as some minimal book-keeping information needed to correctly
29342 uninstall or integrate different GNAT products.
29343 @end itemize
29344
29345 @node Using a network installation of GNAT
29346 @section Using a network installation of GNAT
29347
29348 @noindent
29349 Make sure the system on which GNAT is installed is accessible from the
29350 current machine, i.e., the install location is shared over the network.
29351 Shared resources are accessed on Windows by means of UNC paths, which
29352 have the format @code{\\server\sharename\path}
29353
29354 In order to use such a network installation, simply add the UNC path of the
29355 @file{bin} directory of your GNAT installation in front of your PATH. For
29356 example, if GNAT is installed in @file{\GNAT} directory of a share location
29357 called @file{c-drive} on a machine @file{LOKI}, the following command will
29358 make it available:
29359
29360 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
29361
29362 Be aware that every compilation using the network installation results in the
29363 transfer of large amounts of data across the network and will likely cause
29364 serious performance penalty.
29365
29366 @node CONSOLE and WINDOWS subsystems
29367 @section CONSOLE and WINDOWS subsystems
29368 @cindex CONSOLE Subsystem
29369 @cindex WINDOWS Subsystem
29370 @cindex -mwindows
29371
29372 @noindent
29373 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
29374 (which is the default subsystem) will always create a console when
29375 launching the application. This is not something desirable when the
29376 application has a Windows GUI. To get rid of this console the
29377 application must be using the @code{WINDOWS} subsystem. To do so
29378 the @option{-mwindows} linker option must be specified.
29379
29380 @smallexample
29381 $ gnatmake winprog -largs -mwindows
29382 @end smallexample
29383
29384 @node Temporary Files
29385 @section Temporary Files
29386 @cindex Temporary files
29387
29388 @noindent
29389 It is possible to control where temporary files gets created by setting
29390 the @env{TMP} environment variable. The file will be created:
29391
29392 @itemize
29393 @item Under the directory pointed to by the @env{TMP} environment variable if
29394 this directory exists.
29395
29396 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
29397 set (or not pointing to a directory) and if this directory exists.
29398
29399 @item Under the current working directory otherwise.
29400 @end itemize
29401
29402 @noindent
29403 This allows you to determine exactly where the temporary
29404 file will be created. This is particularly useful in networked
29405 environments where you may not have write access to some
29406 directories.
29407
29408 @node Mixed-Language Programming on Windows
29409 @section Mixed-Language Programming on Windows
29410
29411 @noindent
29412 Developing pure Ada applications on Windows is no different than on
29413 other GNAT-supported platforms. However, when developing or porting an
29414 application that contains a mix of Ada and C/C++, the choice of your
29415 Windows C/C++ development environment conditions your overall
29416 interoperability strategy.
29417
29418 If you use @command{gcc} or Microsoft C to compile the non-Ada part of
29419 your application, there are no Windows-specific restrictions that
29420 affect the overall interoperability with your Ada code. If you do want
29421 to use the Microsoft tools for your C++ code, you have two choices:
29422
29423 @enumerate
29424 @item
29425 Encapsulate your C++ code in a DLL to be linked with your Ada
29426 application. In this case, use the Microsoft or whatever environment to
29427 build the DLL and use GNAT to build your executable
29428 (@pxref{Using DLLs with GNAT}).
29429
29430 @item
29431 Or you can encapsulate your Ada code in a DLL to be linked with the
29432 other part of your application. In this case, use GNAT to build the DLL
29433 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
29434 or whatever environment to build your executable.
29435 @end enumerate
29436
29437 In addition to the description about C main in
29438 @pxref{Mixed Language Programming} section, if the C main uses a
29439 stand-alone library it is required on x86-windows to
29440 setup the SEH context. For this the C main must looks like this:
29441
29442 @smallexample
29443 /* main.c */
29444 extern void adainit (void);
29445 extern void adafinal (void);
29446 extern void __gnat_initialize(void*);
29447 extern void call_to_ada (void);
29448
29449 int main (int argc, char *argv[])
29450 @{
29451 int SEH [2];
29452
29453 /* Initialize the SEH context */
29454 __gnat_initialize (&SEH);
29455
29456 adainit();
29457
29458 /* Then call Ada services in the stand-alone library */
29459
29460 call_to_ada();
29461
29462 adafinal();
29463 @}
29464 @end smallexample
29465
29466 Note that this is not needed on x86_64-windows where the Windows
29467 native SEH support is used.
29468
29469 @node Windows Calling Conventions
29470 @section Windows Calling Conventions
29471 @findex Stdcall
29472 @findex APIENTRY
29473
29474 This section pertain only to Win32. On Win64 there is a single native
29475 calling convention. All convention specifiers are ignored on this
29476 platform.
29477
29478 @menu
29479 * C Calling Convention::
29480 * Stdcall Calling Convention::
29481 * Win32 Calling Convention::
29482 * DLL Calling Convention::
29483 @end menu
29484
29485 @noindent
29486 When a subprogram @code{F} (caller) calls a subprogram @code{G}
29487 (callee), there are several ways to push @code{G}'s parameters on the
29488 stack and there are several possible scenarios to clean up the stack
29489 upon @code{G}'s return. A calling convention is an agreed upon software
29490 protocol whereby the responsibilities between the caller (@code{F}) and
29491 the callee (@code{G}) are clearly defined. Several calling conventions
29492 are available for Windows:
29493
29494 @itemize @bullet
29495 @item
29496 @code{C} (Microsoft defined)
29497
29498 @item
29499 @code{Stdcall} (Microsoft defined)
29500
29501 @item
29502 @code{Win32} (GNAT specific)
29503
29504 @item
29505 @code{DLL} (GNAT specific)
29506 @end itemize
29507
29508 @node C Calling Convention
29509 @subsection @code{C} Calling Convention
29510
29511 @noindent
29512 This is the default calling convention used when interfacing to C/C++
29513 routines compiled with either @command{gcc} or Microsoft Visual C++.
29514
29515 In the @code{C} calling convention subprogram parameters are pushed on the
29516 stack by the caller from right to left. The caller itself is in charge of
29517 cleaning up the stack after the call. In addition, the name of a routine
29518 with @code{C} calling convention is mangled by adding a leading underscore.
29519
29520 The name to use on the Ada side when importing (or exporting) a routine
29521 with @code{C} calling convention is the name of the routine. For
29522 instance the C function:
29523
29524 @smallexample
29525 int get_val (long);
29526 @end smallexample
29527
29528 @noindent
29529 should be imported from Ada as follows:
29530
29531 @smallexample @c ada
29532 @group
29533 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29534 pragma Import (C, Get_Val, External_Name => "get_val");
29535 @end group
29536 @end smallexample
29537
29538 @noindent
29539 Note that in this particular case the @code{External_Name} parameter could
29540 have been omitted since, when missing, this parameter is taken to be the
29541 name of the Ada entity in lower case. When the @code{Link_Name} parameter
29542 is missing, as in the above example, this parameter is set to be the
29543 @code{External_Name} with a leading underscore.
29544
29545 When importing a variable defined in C, you should always use the @code{C}
29546 calling convention unless the object containing the variable is part of a
29547 DLL (in which case you should use the @code{Stdcall} calling
29548 convention, @pxref{Stdcall Calling Convention}).
29549
29550 @node Stdcall Calling Convention
29551 @subsection @code{Stdcall} Calling Convention
29552
29553 @noindent
29554 This convention, which was the calling convention used for Pascal
29555 programs, is used by Microsoft for all the routines in the Win32 API for
29556 efficiency reasons. It must be used to import any routine for which this
29557 convention was specified.
29558
29559 In the @code{Stdcall} calling convention subprogram parameters are pushed
29560 on the stack by the caller from right to left. The callee (and not the
29561 caller) is in charge of cleaning the stack on routine exit. In addition,
29562 the name of a routine with @code{Stdcall} calling convention is mangled by
29563 adding a leading underscore (as for the @code{C} calling convention) and a
29564 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
29565 bytes) of the parameters passed to the routine.
29566
29567 The name to use on the Ada side when importing a C routine with a
29568 @code{Stdcall} calling convention is the name of the C routine. The leading
29569 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
29570 the compiler. For instance the Win32 function:
29571
29572 @smallexample
29573 @b{APIENTRY} int get_val (long);
29574 @end smallexample
29575
29576 @noindent
29577 should be imported from Ada as follows:
29578
29579 @smallexample @c ada
29580 @group
29581 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29582 pragma Import (Stdcall, Get_Val);
29583 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
29584 @end group
29585 @end smallexample
29586
29587 @noindent
29588 As for the @code{C} calling convention, when the @code{External_Name}
29589 parameter is missing, it is taken to be the name of the Ada entity in lower
29590 case. If instead of writing the above import pragma you write:
29591
29592 @smallexample @c ada
29593 @group
29594 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29595 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
29596 @end group
29597 @end smallexample
29598
29599 @noindent
29600 then the imported routine is @code{_retrieve_val@@4}. However, if instead
29601 of specifying the @code{External_Name} parameter you specify the
29602 @code{Link_Name} as in the following example:
29603
29604 @smallexample @c ada
29605 @group
29606 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
29607 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
29608 @end group
29609 @end smallexample
29610
29611 @noindent
29612 then the imported routine is @code{retrieve_val}, that is, there is no
29613 decoration at all. No leading underscore and no Stdcall suffix
29614 @code{@@}@code{@var{nn}}.
29615
29616 @noindent
29617 This is especially important as in some special cases a DLL's entry
29618 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
29619 name generated for a call has it.
29620
29621 @noindent
29622 It is also possible to import variables defined in a DLL by using an
29623 import pragma for a variable. As an example, if a DLL contains a
29624 variable defined as:
29625
29626 @smallexample
29627 int my_var;
29628 @end smallexample
29629
29630 @noindent
29631 then, to access this variable from Ada you should write:
29632
29633 @smallexample @c ada
29634 @group
29635 My_Var : Interfaces.C.int;
29636 pragma Import (Stdcall, My_Var);
29637 @end group
29638 @end smallexample
29639
29640 @noindent
29641 Note that to ease building cross-platform bindings this convention
29642 will be handled as a @code{C} calling convention on non-Windows platforms.
29643
29644 @node Win32 Calling Convention
29645 @subsection @code{Win32} Calling Convention
29646
29647 @noindent
29648 This convention, which is GNAT-specific is fully equivalent to the
29649 @code{Stdcall} calling convention described above.
29650
29651 @node DLL Calling Convention
29652 @subsection @code{DLL} Calling Convention
29653
29654 @noindent
29655 This convention, which is GNAT-specific is fully equivalent to the
29656 @code{Stdcall} calling convention described above.
29657
29658 @node Introduction to Dynamic Link Libraries (DLLs)
29659 @section Introduction to Dynamic Link Libraries (DLLs)
29660 @findex DLL
29661
29662 @noindent
29663 A Dynamically Linked Library (DLL) is a library that can be shared by
29664 several applications running under Windows. A DLL can contain any number of
29665 routines and variables.
29666
29667 One advantage of DLLs is that you can change and enhance them without
29668 forcing all the applications that depend on them to be relinked or
29669 recompiled. However, you should be aware than all calls to DLL routines are
29670 slower since, as you will understand below, such calls are indirect.
29671
29672 To illustrate the remainder of this section, suppose that an application
29673 wants to use the services of a DLL @file{API.dll}. To use the services
29674 provided by @file{API.dll} you must statically link against the DLL or
29675 an import library which contains a jump table with an entry for each
29676 routine and variable exported by the DLL. In the Microsoft world this
29677 import library is called @file{API.lib}. When using GNAT this import
29678 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
29679 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
29680
29681 After you have linked your application with the DLL or the import library
29682 and you run your application, here is what happens:
29683
29684 @enumerate
29685 @item
29686 Your application is loaded into memory.
29687
29688 @item
29689 The DLL @file{API.dll} is mapped into the address space of your
29690 application. This means that:
29691
29692 @itemize @bullet
29693 @item
29694 The DLL will use the stack of the calling thread.
29695
29696 @item
29697 The DLL will use the virtual address space of the calling process.
29698
29699 @item
29700 The DLL will allocate memory from the virtual address space of the calling
29701 process.
29702
29703 @item
29704 Handles (pointers) can be safely exchanged between routines in the DLL
29705 routines and routines in the application using the DLL.
29706 @end itemize
29707
29708 @item
29709 The entries in the jump table (from the import library @file{libAPI.dll.a}
29710 or @file{API.lib} or automatically created when linking against a DLL)
29711 which is part of your application are initialized with the addresses
29712 of the routines and variables in @file{API.dll}.
29713
29714 @item
29715 If present in @file{API.dll}, routines @code{DllMain} or
29716 @code{DllMainCRTStartup} are invoked. These routines typically contain
29717 the initialization code needed for the well-being of the routines and
29718 variables exported by the DLL.
29719 @end enumerate
29720
29721 @noindent
29722 There is an additional point which is worth mentioning. In the Windows
29723 world there are two kind of DLLs: relocatable and non-relocatable
29724 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
29725 in the target application address space. If the addresses of two
29726 non-relocatable DLLs overlap and these happen to be used by the same
29727 application, a conflict will occur and the application will run
29728 incorrectly. Hence, when possible, it is always preferable to use and
29729 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
29730 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
29731 User's Guide) removes the debugging symbols from the DLL but the DLL can
29732 still be relocated.
29733
29734 As a side note, an interesting difference between Microsoft DLLs and
29735 Unix shared libraries, is the fact that on most Unix systems all public
29736 routines are exported by default in a Unix shared library, while under
29737 Windows it is possible (but not required) to list exported routines in
29738 a definition file (@pxref{The Definition File}).
29739
29740 @node Using DLLs with GNAT
29741 @section Using DLLs with GNAT
29742
29743 @menu
29744 * Creating an Ada Spec for the DLL Services::
29745 * Creating an Import Library::
29746 @end menu
29747
29748 @noindent
29749 To use the services of a DLL, say @file{API.dll}, in your Ada application
29750 you must have:
29751
29752 @enumerate
29753 @item
29754 The Ada spec for the routines and/or variables you want to access in
29755 @file{API.dll}. If not available this Ada spec must be built from the C/C++
29756 header files provided with the DLL.
29757
29758 @item
29759 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
29760 mentioned an import library is a statically linked library containing the
29761 import table which will be filled at load time to point to the actual
29762 @file{API.dll} routines. Sometimes you don't have an import library for the
29763 DLL you want to use. The following sections will explain how to build
29764 one. Note that this is optional.
29765
29766 @item
29767 The actual DLL, @file{API.dll}.
29768 @end enumerate
29769
29770 @noindent
29771 Once you have all the above, to compile an Ada application that uses the
29772 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
29773 you simply issue the command
29774
29775 @smallexample
29776 $ gnatmake my_ada_app -largs -lAPI
29777 @end smallexample
29778
29779 @noindent
29780 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
29781 tells the GNAT linker to look for an import library. The linker will
29782 look for a library name in this specific order:
29783
29784 @enumerate
29785 @item @file{libAPI.dll.a}
29786 @item @file{API.dll.a}
29787 @item @file{libAPI.a}
29788 @item @file{API.lib}
29789 @item @file{libAPI.dll}
29790 @item @file{API.dll}
29791 @end enumerate
29792
29793 The first three are the GNU style import libraries. The third is the
29794 Microsoft style import libraries. The last two are the actual DLL names.
29795
29796 Note that if the Ada package spec for @file{API.dll} contains the
29797 following pragma
29798
29799 @smallexample @c ada
29800 pragma Linker_Options ("-lAPI");
29801 @end smallexample
29802
29803 @noindent
29804 you do not have to add @option{-largs -lAPI} at the end of the
29805 @command{gnatmake} command.
29806
29807 If any one of the items above is missing you will have to create it
29808 yourself. The following sections explain how to do so using as an
29809 example a fictitious DLL called @file{API.dll}.
29810
29811 @node Creating an Ada Spec for the DLL Services
29812 @subsection Creating an Ada Spec for the DLL Services
29813
29814 @noindent
29815 A DLL typically comes with a C/C++ header file which provides the
29816 definitions of the routines and variables exported by the DLL. The Ada
29817 equivalent of this header file is a package spec that contains definitions
29818 for the imported entities. If the DLL you intend to use does not come with
29819 an Ada spec you have to generate one such spec yourself. For example if
29820 the header file of @file{API.dll} is a file @file{api.h} containing the
29821 following two definitions:
29822
29823 @smallexample
29824 @group
29825 @cartouche
29826 int some_var;
29827 int get (char *);
29828 @end cartouche
29829 @end group
29830 @end smallexample
29831
29832 @noindent
29833 then the equivalent Ada spec could be:
29834
29835 @smallexample @c ada
29836 @group
29837 @cartouche
29838 with Interfaces.C.Strings;
29839 package API is
29840 use Interfaces;
29841
29842 Some_Var : C.int;
29843 function Get (Str : C.Strings.Chars_Ptr) return C.int;
29844
29845 private
29846 pragma Import (C, Get);
29847 pragma Import (DLL, Some_Var);
29848 end API;
29849 @end cartouche
29850 @end group
29851 @end smallexample
29852
29853 @node Creating an Import Library
29854 @subsection Creating an Import Library
29855 @cindex Import library
29856
29857 @menu
29858 * The Definition File::
29859 * GNAT-Style Import Library::
29860 * Microsoft-Style Import Library::
29861 @end menu
29862
29863 @noindent
29864 If a Microsoft-style import library @file{API.lib} or a GNAT-style
29865 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
29866 with @file{API.dll} you can skip this section. You can also skip this
29867 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
29868 as in this case it is possible to link directly against the
29869 DLL. Otherwise read on.
29870
29871 @node The Definition File
29872 @subsubsection The Definition File
29873 @cindex Definition file
29874 @findex .def
29875
29876 @noindent
29877 As previously mentioned, and unlike Unix systems, the list of symbols
29878 that are exported from a DLL must be provided explicitly in Windows.
29879 The main goal of a definition file is precisely that: list the symbols
29880 exported by a DLL. A definition file (usually a file with a @code{.def}
29881 suffix) has the following structure:
29882
29883 @smallexample
29884 @group
29885 @cartouche
29886 @r{[}LIBRARY @var{name}@r{]}
29887 @r{[}DESCRIPTION @var{string}@r{]}
29888 EXPORTS
29889 @var{symbol1}
29890 @var{symbol2}
29891 @dots{}
29892 @end cartouche
29893 @end group
29894 @end smallexample
29895
29896 @table @code
29897 @item LIBRARY @var{name}
29898 This section, which is optional, gives the name of the DLL.
29899
29900 @item DESCRIPTION @var{string}
29901 This section, which is optional, gives a description string that will be
29902 embedded in the import library.
29903
29904 @item EXPORTS
29905 This section gives the list of exported symbols (procedures, functions or
29906 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
29907 section of @file{API.def} looks like:
29908
29909 @smallexample
29910 @group
29911 @cartouche
29912 EXPORTS
29913 some_var
29914 get
29915 @end cartouche
29916 @end group
29917 @end smallexample
29918 @end table
29919
29920 @noindent
29921 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
29922 (@pxref{Windows Calling Conventions}) for a Stdcall
29923 calling convention function in the exported symbols list.
29924
29925 @noindent
29926 There can actually be other sections in a definition file, but these
29927 sections are not relevant to the discussion at hand.
29928
29929 @node GNAT-Style Import Library
29930 @subsubsection GNAT-Style Import Library
29931
29932 @noindent
29933 To create a static import library from @file{API.dll} with the GNAT tools
29934 you should proceed as follows:
29935
29936 @enumerate
29937 @item
29938 Create the definition file @file{API.def} (@pxref{The Definition File}).
29939 For that use the @code{dll2def} tool as follows:
29940
29941 @smallexample
29942 $ dll2def API.dll > API.def
29943 @end smallexample
29944
29945 @noindent
29946 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
29947 to standard output the list of entry points in the DLL. Note that if
29948 some routines in the DLL have the @code{Stdcall} convention
29949 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
29950 suffix then you'll have to edit @file{api.def} to add it, and specify
29951 @option{-k} to @command{gnatdll} when creating the import library.
29952
29953 @noindent
29954 Here are some hints to find the right @code{@@}@var{nn} suffix.
29955
29956 @enumerate
29957 @item
29958 If you have the Microsoft import library (.lib), it is possible to get
29959 the right symbols by using Microsoft @code{dumpbin} tool (see the
29960 corresponding Microsoft documentation for further details).
29961
29962 @smallexample
29963 $ dumpbin /exports api.lib
29964 @end smallexample
29965
29966 @item
29967 If you have a message about a missing symbol at link time the compiler
29968 tells you what symbol is expected. You just have to go back to the
29969 definition file and add the right suffix.
29970 @end enumerate
29971
29972 @item
29973 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
29974 (@pxref{Using gnatdll}) as follows:
29975
29976 @smallexample
29977 $ gnatdll -e API.def -d API.dll
29978 @end smallexample
29979
29980 @noindent
29981 @code{gnatdll} takes as input a definition file @file{API.def} and the
29982 name of the DLL containing the services listed in the definition file
29983 @file{API.dll}. The name of the static import library generated is
29984 computed from the name of the definition file as follows: if the
29985 definition file name is @var{xyz}@code{.def}, the import library name will
29986 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
29987 @option{-e} could have been removed because the name of the definition
29988 file (before the ``@code{.def}'' suffix) is the same as the name of the
29989 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
29990 @end enumerate
29991
29992 @node Microsoft-Style Import Library
29993 @subsubsection Microsoft-Style Import Library
29994
29995 @noindent
29996 With GNAT you can either use a GNAT-style or Microsoft-style import
29997 library. A Microsoft import library is needed only if you plan to make an
29998 Ada DLL available to applications developed with Microsoft
29999 tools (@pxref{Mixed-Language Programming on Windows}).
30000
30001 To create a Microsoft-style import library for @file{API.dll} you
30002 should proceed as follows:
30003
30004 @enumerate
30005 @item
30006 Create the definition file @file{API.def} from the DLL. For this use either
30007 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
30008 tool (see the corresponding Microsoft documentation for further details).
30009
30010 @item
30011 Build the actual import library using Microsoft's @code{lib} utility:
30012
30013 @smallexample
30014 $ lib -machine:IX86 -def:API.def -out:API.lib
30015 @end smallexample
30016
30017 @noindent
30018 If you use the above command the definition file @file{API.def} must
30019 contain a line giving the name of the DLL:
30020
30021 @smallexample
30022 LIBRARY "API"
30023 @end smallexample
30024
30025 @noindent
30026 See the Microsoft documentation for further details about the usage of
30027 @code{lib}.
30028 @end enumerate
30029
30030 @node Building DLLs with GNAT Project files
30031 @section Building DLLs with GNAT Project files
30032 @cindex DLLs, building
30033
30034 @noindent
30035 There is nothing specific to Windows in the build process.
30036 @pxref{Library Projects}.
30037
30038 @noindent
30039 Due to a system limitation, it is not possible under Windows to create threads
30040 when inside the @code{DllMain} routine which is used for auto-initialization
30041 of shared libraries, so it is not possible to have library level tasks in SALs.
30042
30043 @node Building DLLs with GNAT
30044 @section Building DLLs with GNAT
30045 @cindex DLLs, building
30046
30047 @noindent
30048 This section explain how to build DLLs using the GNAT built-in DLL
30049 support. With the following procedure it is straight forward to build
30050 and use DLLs with GNAT.
30051
30052 @enumerate
30053
30054 @item building object files
30055
30056 The first step is to build all objects files that are to be included
30057 into the DLL. This is done by using the standard @command{gnatmake} tool.
30058
30059 @item building the DLL
30060
30061 To build the DLL you must use @command{gcc}'s @option{-shared} and
30062 @option{-shared-libgcc} options. It is quite simple to use this method:
30063
30064 @smallexample
30065 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
30066 @end smallexample
30067
30068 It is important to note that in this case all symbols found in the
30069 object files are automatically exported. It is possible to restrict
30070 the set of symbols to export by passing to @command{gcc} a definition
30071 file, @pxref{The Definition File}. For example:
30072
30073 @smallexample
30074 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
30075 @end smallexample
30076
30077 If you use a definition file you must export the elaboration procedures
30078 for every package that required one. Elaboration procedures are named
30079 using the package name followed by "_E".
30080
30081 @item preparing DLL to be used
30082
30083 For the DLL to be used by client programs the bodies must be hidden
30084 from it and the .ali set with read-only attribute. This is very important
30085 otherwise GNAT will recompile all packages and will not actually use
30086 the code in the DLL. For example:
30087
30088 @smallexample
30089 $ mkdir apilib
30090 $ copy *.ads *.ali api.dll apilib
30091 $ attrib +R apilib\*.ali
30092 @end smallexample
30093
30094 @end enumerate
30095
30096 At this point it is possible to use the DLL by directly linking
30097 against it. Note that you must use the GNAT shared runtime when using
30098 GNAT shared libraries. This is achieved by using @option{-shared} binder's
30099 option.
30100
30101 @smallexample
30102 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
30103 @end smallexample
30104
30105 @node Building DLLs with gnatdll
30106 @section Building DLLs with gnatdll
30107 @cindex DLLs, building
30108
30109 @menu
30110 * Limitations When Using Ada DLLs from Ada::
30111 * Exporting Ada Entities::
30112 * Ada DLLs and Elaboration::
30113 * Ada DLLs and Finalization::
30114 * Creating a Spec for Ada DLLs::
30115 * Creating the Definition File::
30116 * Using gnatdll::
30117 @end menu
30118
30119 @noindent
30120 Note that it is preferred to use GNAT Project files
30121 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
30122 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
30123
30124 This section explains how to build DLLs containing Ada code using
30125 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
30126 remainder of this section.
30127
30128 The steps required to build an Ada DLL that is to be used by Ada as well as
30129 non-Ada applications are as follows:
30130
30131 @enumerate
30132 @item
30133 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
30134 @code{Stdcall} calling convention to avoid any Ada name mangling for the
30135 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
30136 skip this step if you plan to use the Ada DLL only from Ada applications.
30137
30138 @item
30139 Your Ada code must export an initialization routine which calls the routine
30140 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
30141 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
30142 routine exported by the Ada DLL must be invoked by the clients of the DLL
30143 to initialize the DLL.
30144
30145 @item
30146 When useful, the DLL should also export a finalization routine which calls
30147 routine @code{adafinal} generated by @command{gnatbind} to perform the
30148 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
30149 The finalization routine exported by the Ada DLL must be invoked by the
30150 clients of the DLL when the DLL services are no further needed.
30151
30152 @item
30153 You must provide a spec for the services exported by the Ada DLL in each
30154 of the programming languages to which you plan to make the DLL available.
30155
30156 @item
30157 You must provide a definition file listing the exported entities
30158 (@pxref{The Definition File}).
30159
30160 @item
30161 Finally you must use @code{gnatdll} to produce the DLL and the import
30162 library (@pxref{Using gnatdll}).
30163 @end enumerate
30164
30165 @noindent
30166 Note that a relocatable DLL stripped using the @code{strip}
30167 binutils tool will not be relocatable anymore. To build a DLL without
30168 debug information pass @code{-largs -s} to @code{gnatdll}. This
30169 restriction does not apply to a DLL built using a Library Project.
30170 @pxref{Library Projects}.
30171
30172 @node Limitations When Using Ada DLLs from Ada
30173 @subsection Limitations When Using Ada DLLs from Ada
30174
30175 @noindent
30176 When using Ada DLLs from Ada applications there is a limitation users
30177 should be aware of. Because on Windows the GNAT run time is not in a DLL of
30178 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
30179 each Ada DLL includes the services of the GNAT run time that are necessary
30180 to the Ada code inside the DLL. As a result, when an Ada program uses an
30181 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
30182 one in the main program.
30183
30184 It is therefore not possible to exchange GNAT run-time objects between the
30185 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
30186 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
30187 types, etc.
30188
30189 It is completely safe to exchange plain elementary, array or record types,
30190 Windows object handles, etc.
30191
30192 @node Exporting Ada Entities
30193 @subsection Exporting Ada Entities
30194 @cindex Export table
30195
30196 @noindent
30197 Building a DLL is a way to encapsulate a set of services usable from any
30198 application. As a result, the Ada entities exported by a DLL should be
30199 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
30200 any Ada name mangling. As an example here is an Ada package
30201 @code{API}, spec and body, exporting two procedures, a function, and a
30202 variable:
30203
30204 @smallexample @c ada
30205 @group
30206 @cartouche
30207 with Interfaces.C; use Interfaces;
30208 package API is
30209 Count : C.int := 0;
30210 function Factorial (Val : C.int) return C.int;
30211
30212 procedure Initialize_API;
30213 procedure Finalize_API;
30214 -- Initialization & Finalization routines. More in the next section.
30215 private
30216 pragma Export (C, Initialize_API);
30217 pragma Export (C, Finalize_API);
30218 pragma Export (C, Count);
30219 pragma Export (C, Factorial);
30220 end API;
30221 @end cartouche
30222 @end group
30223 @end smallexample
30224
30225 @smallexample @c ada
30226 @group
30227 @cartouche
30228 package body API is
30229 function Factorial (Val : C.int) return C.int is
30230 Fact : C.int := 1;
30231 begin
30232 Count := Count + 1;
30233 for K in 1 .. Val loop
30234 Fact := Fact * K;
30235 end loop;
30236 return Fact;
30237 end Factorial;
30238
30239 procedure Initialize_API is
30240 procedure Adainit;
30241 pragma Import (C, Adainit);
30242 begin
30243 Adainit;
30244 end Initialize_API;
30245
30246 procedure Finalize_API is
30247 procedure Adafinal;
30248 pragma Import (C, Adafinal);
30249 begin
30250 Adafinal;
30251 end Finalize_API;
30252 end API;
30253 @end cartouche
30254 @end group
30255 @end smallexample
30256
30257 @noindent
30258 If the Ada DLL you are building will only be used by Ada applications
30259 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
30260 convention. As an example, the previous package could be written as
30261 follows:
30262
30263 @smallexample @c ada
30264 @group
30265 @cartouche
30266 package API is
30267 Count : Integer := 0;
30268 function Factorial (Val : Integer) return Integer;
30269
30270 procedure Initialize_API;
30271 procedure Finalize_API;
30272 -- Initialization and Finalization routines.
30273 end API;
30274 @end cartouche
30275 @end group
30276 @end smallexample
30277
30278 @smallexample @c ada
30279 @group
30280 @cartouche
30281 package body API is
30282 function Factorial (Val : Integer) return Integer is
30283 Fact : Integer := 1;
30284 begin
30285 Count := Count + 1;
30286 for K in 1 .. Val loop
30287 Fact := Fact * K;
30288 end loop;
30289 return Fact;
30290 end Factorial;
30291
30292 @dots{}
30293 -- The remainder of this package body is unchanged.
30294 end API;
30295 @end cartouche
30296 @end group
30297 @end smallexample
30298
30299 @noindent
30300 Note that if you do not export the Ada entities with a @code{C} or
30301 @code{Stdcall} convention you will have to provide the mangled Ada names
30302 in the definition file of the Ada DLL
30303 (@pxref{Creating the Definition File}).
30304
30305 @node Ada DLLs and Elaboration
30306 @subsection Ada DLLs and Elaboration
30307 @cindex DLLs and elaboration
30308
30309 @noindent
30310 The DLL that you are building contains your Ada code as well as all the
30311 routines in the Ada library that are needed by it. The first thing a
30312 user of your DLL must do is elaborate the Ada code
30313 (@pxref{Elaboration Order Handling in GNAT}).
30314
30315 To achieve this you must export an initialization routine
30316 (@code{Initialize_API} in the previous example), which must be invoked
30317 before using any of the DLL services. This elaboration routine must call
30318 the Ada elaboration routine @code{adainit} generated by the GNAT binder
30319 (@pxref{Binding with Non-Ada Main Programs}). See the body of
30320 @code{Initialize_Api} for an example. Note that the GNAT binder is
30321 automatically invoked during the DLL build process by the @code{gnatdll}
30322 tool (@pxref{Using gnatdll}).
30323
30324 When a DLL is loaded, Windows systematically invokes a routine called
30325 @code{DllMain}. It would therefore be possible to call @code{adainit}
30326 directly from @code{DllMain} without having to provide an explicit
30327 initialization routine. Unfortunately, it is not possible to call
30328 @code{adainit} from the @code{DllMain} if your program has library level
30329 tasks because access to the @code{DllMain} entry point is serialized by
30330 the system (that is, only a single thread can execute ``through'' it at a
30331 time), which means that the GNAT run time will deadlock waiting for the
30332 newly created task to complete its initialization.
30333
30334 @node Ada DLLs and Finalization
30335 @subsection Ada DLLs and Finalization
30336 @cindex DLLs and finalization
30337
30338 @noindent
30339 When the services of an Ada DLL are no longer needed, the client code should
30340 invoke the DLL finalization routine, if available. The DLL finalization
30341 routine is in charge of releasing all resources acquired by the DLL. In the
30342 case of the Ada code contained in the DLL, this is achieved by calling
30343 routine @code{adafinal} generated by the GNAT binder
30344 (@pxref{Binding with Non-Ada Main Programs}).
30345 See the body of @code{Finalize_Api} for an
30346 example. As already pointed out the GNAT binder is automatically invoked
30347 during the DLL build process by the @code{gnatdll} tool
30348 (@pxref{Using gnatdll}).
30349
30350 @node Creating a Spec for Ada DLLs
30351 @subsection Creating a Spec for Ada DLLs
30352
30353 @noindent
30354 To use the services exported by the Ada DLL from another programming
30355 language (e.g.@: C), you have to translate the specs of the exported Ada
30356 entities in that language. For instance in the case of @code{API.dll},
30357 the corresponding C header file could look like:
30358
30359 @smallexample
30360 @group
30361 @cartouche
30362 extern int *_imp__count;
30363 #define count (*_imp__count)
30364 int factorial (int);
30365 @end cartouche
30366 @end group
30367 @end smallexample
30368
30369 @noindent
30370 It is important to understand that when building an Ada DLL to be used by
30371 other Ada applications, you need two different specs for the packages
30372 contained in the DLL: one for building the DLL and the other for using
30373 the DLL. This is because the @code{DLL} calling convention is needed to
30374 use a variable defined in a DLL, but when building the DLL, the variable
30375 must have either the @code{Ada} or @code{C} calling convention. As an
30376 example consider a DLL comprising the following package @code{API}:
30377
30378 @smallexample @c ada
30379 @group
30380 @cartouche
30381 package API is
30382 Count : Integer := 0;
30383 @dots{}
30384 -- Remainder of the package omitted.
30385 end API;
30386 @end cartouche
30387 @end group
30388 @end smallexample
30389
30390 @noindent
30391 After producing a DLL containing package @code{API}, the spec that
30392 must be used to import @code{API.Count} from Ada code outside of the
30393 DLL is:
30394
30395 @smallexample @c ada
30396 @group
30397 @cartouche
30398 package API is
30399 Count : Integer;
30400 pragma Import (DLL, Count);
30401 end API;
30402 @end cartouche
30403 @end group
30404 @end smallexample
30405
30406 @node Creating the Definition File
30407 @subsection Creating the Definition File
30408
30409 @noindent
30410 The definition file is the last file needed to build the DLL. It lists
30411 the exported symbols. As an example, the definition file for a DLL
30412 containing only package @code{API} (where all the entities are exported
30413 with a @code{C} calling convention) is:
30414
30415 @smallexample
30416 @group
30417 @cartouche
30418 EXPORTS
30419 count
30420 factorial
30421 finalize_api
30422 initialize_api
30423 @end cartouche
30424 @end group
30425 @end smallexample
30426
30427 @noindent
30428 If the @code{C} calling convention is missing from package @code{API},
30429 then the definition file contains the mangled Ada names of the above
30430 entities, which in this case are:
30431
30432 @smallexample
30433 @group
30434 @cartouche
30435 EXPORTS
30436 api__count
30437 api__factorial
30438 api__finalize_api
30439 api__initialize_api
30440 @end cartouche
30441 @end group
30442 @end smallexample
30443
30444 @node Using gnatdll
30445 @subsection Using @code{gnatdll}
30446 @findex gnatdll
30447
30448 @menu
30449 * gnatdll Example::
30450 * gnatdll behind the Scenes::
30451 * Using dlltool::
30452 @end menu
30453
30454 @noindent
30455 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
30456 and non-Ada sources that make up your DLL have been compiled.
30457 @code{gnatdll} is actually in charge of two distinct tasks: build the
30458 static import library for the DLL and the actual DLL. The form of the
30459 @code{gnatdll} command is
30460
30461 @smallexample
30462 @cartouche
30463 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
30464 @c Expanding @ovar macro inline (explanation in macro def comments)
30465 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
30466 @end cartouche
30467 @end smallexample
30468
30469 @noindent
30470 where @var{list-of-files} is a list of ALI and object files. The object
30471 file list must be the exact list of objects corresponding to the non-Ada
30472 sources whose services are to be included in the DLL. The ALI file list
30473 must be the exact list of ALI files for the corresponding Ada sources
30474 whose services are to be included in the DLL. If @var{list-of-files} is
30475 missing, only the static import library is generated.
30476
30477 @noindent
30478 You may specify any of the following switches to @code{gnatdll}:
30479
30480 @table @code
30481 @c @item -a@ovar{address}
30482 @c Expanding @ovar macro inline (explanation in macro def comments)
30483 @item -a@r{[}@var{address}@r{]}
30484 @cindex @option{-a} (@code{gnatdll})
30485 Build a non-relocatable DLL at @var{address}. If @var{address} is not
30486 specified the default address @var{0x11000000} will be used. By default,
30487 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
30488 advise the reader to build relocatable DLL.
30489
30490 @item -b @var{address}
30491 @cindex @option{-b} (@code{gnatdll})
30492 Set the relocatable DLL base address. By default the address is
30493 @code{0x11000000}.
30494
30495 @item -bargs @var{opts}
30496 @cindex @option{-bargs} (@code{gnatdll})
30497 Binder options. Pass @var{opts} to the binder.
30498
30499 @item -d @var{dllfile}
30500 @cindex @option{-d} (@code{gnatdll})
30501 @var{dllfile} is the name of the DLL. This switch must be present for
30502 @code{gnatdll} to do anything. The name of the generated import library is
30503 obtained algorithmically from @var{dllfile} as shown in the following
30504 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
30505 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
30506 by option @option{-e}) is obtained algorithmically from @var{dllfile}
30507 as shown in the following example:
30508 if @var{dllfile} is @code{xyz.dll}, the definition
30509 file used is @code{xyz.def}.
30510
30511 @item -e @var{deffile}
30512 @cindex @option{-e} (@code{gnatdll})
30513 @var{deffile} is the name of the definition file.
30514
30515 @item -g
30516 @cindex @option{-g} (@code{gnatdll})
30517 Generate debugging information. This information is stored in the object
30518 file and copied from there to the final DLL file by the linker,
30519 where it can be read by the debugger. You must use the
30520 @option{-g} switch if you plan on using the debugger or the symbolic
30521 stack traceback.
30522
30523 @item -h
30524 @cindex @option{-h} (@code{gnatdll})
30525 Help mode. Displays @code{gnatdll} switch usage information.
30526
30527 @item -Idir
30528 @cindex @option{-I} (@code{gnatdll})
30529 Direct @code{gnatdll} to search the @var{dir} directory for source and
30530 object files needed to build the DLL.
30531 (@pxref{Search Paths and the Run-Time Library (RTL)}).
30532
30533 @item -k
30534 @cindex @option{-k} (@code{gnatdll})
30535 Removes the @code{@@}@var{nn} suffix from the import library's exported
30536 names, but keeps them for the link names. You must specify this
30537 option if you want to use a @code{Stdcall} function in a DLL for which
30538 the @code{@@}@var{nn} suffix has been removed. This is the case for most
30539 of the Windows NT DLL for example. This option has no effect when
30540 @option{-n} option is specified.
30541
30542 @item -l @var{file}
30543 @cindex @option{-l} (@code{gnatdll})
30544 The list of ALI and object files used to build the DLL are listed in
30545 @var{file}, instead of being given in the command line. Each line in
30546 @var{file} contains the name of an ALI or object file.
30547
30548 @item -n
30549 @cindex @option{-n} (@code{gnatdll})
30550 No Import. Do not create the import library.
30551
30552 @item -q
30553 @cindex @option{-q} (@code{gnatdll})
30554 Quiet mode. Do not display unnecessary messages.
30555
30556 @item -v
30557 @cindex @option{-v} (@code{gnatdll})
30558 Verbose mode. Display extra information.
30559
30560 @item -largs @var{opts}
30561 @cindex @option{-largs} (@code{gnatdll})
30562 Linker options. Pass @var{opts} to the linker.
30563 @end table
30564
30565 @node gnatdll Example
30566 @subsubsection @code{gnatdll} Example
30567
30568 @noindent
30569 As an example the command to build a relocatable DLL from @file{api.adb}
30570 once @file{api.adb} has been compiled and @file{api.def} created is
30571
30572 @smallexample
30573 $ gnatdll -d api.dll api.ali
30574 @end smallexample
30575
30576 @noindent
30577 The above command creates two files: @file{libapi.dll.a} (the import
30578 library) and @file{api.dll} (the actual DLL). If you want to create
30579 only the DLL, just type:
30580
30581 @smallexample
30582 $ gnatdll -d api.dll -n api.ali
30583 @end smallexample
30584
30585 @noindent
30586 Alternatively if you want to create just the import library, type:
30587
30588 @smallexample
30589 $ gnatdll -d api.dll
30590 @end smallexample
30591
30592 @node gnatdll behind the Scenes
30593 @subsubsection @code{gnatdll} behind the Scenes
30594
30595 @noindent
30596 This section details the steps involved in creating a DLL. @code{gnatdll}
30597 does these steps for you. Unless you are interested in understanding what
30598 goes on behind the scenes, you should skip this section.
30599
30600 We use the previous example of a DLL containing the Ada package @code{API},
30601 to illustrate the steps necessary to build a DLL. The starting point is a
30602 set of objects that will make up the DLL and the corresponding ALI
30603 files. In the case of this example this means that @file{api.o} and
30604 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
30605 the following:
30606
30607 @enumerate
30608 @item
30609 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
30610 the information necessary to generate relocation information for the
30611 DLL.
30612
30613 @smallexample
30614 @group
30615 $ gnatbind -n api
30616 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
30617 @end group
30618 @end smallexample
30619
30620 @noindent
30621 In addition to the base file, the @command{gnatlink} command generates an
30622 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
30623 asks @command{gnatlink} to generate the routines @code{DllMain} and
30624 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
30625 is loaded into memory.
30626
30627 @item
30628 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
30629 export table (@file{api.exp}). The export table contains the relocation
30630 information in a form which can be used during the final link to ensure
30631 that the Windows loader is able to place the DLL anywhere in memory.
30632
30633 @smallexample
30634 @group
30635 $ dlltool --dllname api.dll --def api.def --base-file api.base \
30636 --output-exp api.exp
30637 @end group
30638 @end smallexample
30639
30640 @item
30641 @code{gnatdll} builds the base file using the new export table. Note that
30642 @command{gnatbind} must be called once again since the binder generated file
30643 has been deleted during the previous call to @command{gnatlink}.
30644
30645 @smallexample
30646 @group
30647 $ gnatbind -n api
30648 $ gnatlink api -o api.jnk api.exp -mdll
30649 -Wl,--base-file,api.base
30650 @end group
30651 @end smallexample
30652
30653 @item
30654 @code{gnatdll} builds the new export table using the new base file and
30655 generates the DLL import library @file{libAPI.dll.a}.
30656
30657 @smallexample
30658 @group
30659 $ dlltool --dllname api.dll --def api.def --base-file api.base \
30660 --output-exp api.exp --output-lib libAPI.a
30661 @end group
30662 @end smallexample
30663
30664 @item
30665 Finally @code{gnatdll} builds the relocatable DLL using the final export
30666 table.
30667
30668 @smallexample
30669 @group
30670 $ gnatbind -n api
30671 $ gnatlink api api.exp -o api.dll -mdll
30672 @end group
30673 @end smallexample
30674 @end enumerate
30675
30676 @node Using dlltool
30677 @subsubsection Using @code{dlltool}
30678
30679 @noindent
30680 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
30681 DLLs and static import libraries. This section summarizes the most
30682 common @code{dlltool} switches. The form of the @code{dlltool} command
30683 is
30684
30685 @smallexample
30686 @c $ dlltool @ovar{switches}
30687 @c Expanding @ovar macro inline (explanation in macro def comments)
30688 $ dlltool @r{[}@var{switches}@r{]}
30689 @end smallexample
30690
30691 @noindent
30692 @code{dlltool} switches include:
30693
30694 @table @option
30695 @item --base-file @var{basefile}
30696 @cindex @option{--base-file} (@command{dlltool})
30697 Read the base file @var{basefile} generated by the linker. This switch
30698 is used to create a relocatable DLL.
30699
30700 @item --def @var{deffile}
30701 @cindex @option{--def} (@command{dlltool})
30702 Read the definition file.
30703
30704 @item --dllname @var{name}
30705 @cindex @option{--dllname} (@command{dlltool})
30706 Gives the name of the DLL. This switch is used to embed the name of the
30707 DLL in the static import library generated by @code{dlltool} with switch
30708 @option{--output-lib}.
30709
30710 @item -k
30711 @cindex @option{-k} (@command{dlltool})
30712 Kill @code{@@}@var{nn} from exported names
30713 (@pxref{Windows Calling Conventions}
30714 for a discussion about @code{Stdcall}-style symbols.
30715
30716 @item --help
30717 @cindex @option{--help} (@command{dlltool})
30718 Prints the @code{dlltool} switches with a concise description.
30719
30720 @item --output-exp @var{exportfile}
30721 @cindex @option{--output-exp} (@command{dlltool})
30722 Generate an export file @var{exportfile}. The export file contains the
30723 export table (list of symbols in the DLL) and is used to create the DLL.
30724
30725 @item --output-lib @var{libfile}
30726 @cindex @option{--output-lib} (@command{dlltool})
30727 Generate a static import library @var{libfile}.
30728
30729 @item -v
30730 @cindex @option{-v} (@command{dlltool})
30731 Verbose mode.
30732
30733 @item --as @var{assembler-name}
30734 @cindex @option{--as} (@command{dlltool})
30735 Use @var{assembler-name} as the assembler. The default is @code{as}.
30736 @end table
30737
30738 @node GNAT and Windows Resources
30739 @section GNAT and Windows Resources
30740 @cindex Resources, windows
30741
30742 @menu
30743 * Building Resources::
30744 * Compiling Resources::
30745 * Using Resources::
30746 @end menu
30747
30748 @noindent
30749 Resources are an easy way to add Windows specific objects to your
30750 application. The objects that can be added as resources include:
30751
30752 @itemize @bullet
30753 @item menus
30754
30755 @item accelerators
30756
30757 @item dialog boxes
30758
30759 @item string tables
30760
30761 @item bitmaps
30762
30763 @item cursors
30764
30765 @item icons
30766
30767 @item fonts
30768
30769 @item version information
30770 @end itemize
30771
30772 For example, a version information resource can be defined as follow and
30773 embedded into an executable or DLL:
30774
30775 A version information resource can be used to embed information into an
30776 executable or a DLL. These information can be viewed using the file properties
30777 from the Windows Explorer. Here is an example of a version information
30778 resource:
30779
30780 @smallexample
30781 @group
30782 1 VERSIONINFO
30783 FILEVERSION 1,0,0,0
30784 PRODUCTVERSION 1,0,0,0
30785 BEGIN
30786 BLOCK "StringFileInfo"
30787 BEGIN
30788 BLOCK "080904E4"
30789 BEGIN
30790 VALUE "CompanyName", "My Company Name"
30791 VALUE "FileDescription", "My application"
30792 VALUE "FileVersion", "1.0"
30793 VALUE "InternalName", "my_app"
30794 VALUE "LegalCopyright", "My Name"
30795 VALUE "OriginalFilename", "my_app.exe"
30796 VALUE "ProductName", "My App"
30797 VALUE "ProductVersion", "1.0"
30798 END
30799 END
30800
30801 BLOCK "VarFileInfo"
30802 BEGIN
30803 VALUE "Translation", 0x809, 1252
30804 END
30805 END
30806 @end group
30807 @end smallexample
30808
30809 The value @code{0809} (langID) is for the U.K English language and
30810 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
30811 multilingual.
30812
30813 @noindent
30814 This section explains how to build, compile and use resources. Note that this
30815 section does not cover all resource objects, for a complete description see
30816 the corresponding Microsoft documentation.
30817
30818 @node Building Resources
30819 @subsection Building Resources
30820 @cindex Resources, building
30821
30822 @noindent
30823 A resource file is an ASCII file. By convention resource files have an
30824 @file{.rc} extension.
30825 The easiest way to build a resource file is to use Microsoft tools
30826 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
30827 @code{dlgedit.exe} to build dialogs.
30828 It is always possible to build an @file{.rc} file yourself by writing a
30829 resource script.
30830
30831 It is not our objective to explain how to write a resource file. A
30832 complete description of the resource script language can be found in the
30833 Microsoft documentation.
30834
30835 @node Compiling Resources
30836 @subsection Compiling Resources
30837 @findex rc
30838 @findex windres
30839 @cindex Resources, compiling
30840
30841 @noindent
30842 This section describes how to build a GNAT-compatible (COFF) object file
30843 containing the resources. This is done using the Resource Compiler
30844 @code{windres} as follows:
30845
30846 @smallexample
30847 $ windres -i myres.rc -o myres.o
30848 @end smallexample
30849
30850 @noindent
30851 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
30852 file. You can specify an alternate preprocessor (usually named
30853 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
30854 parameter. A list of all possible options may be obtained by entering
30855 the command @code{windres} @option{--help}.
30856
30857 It is also possible to use the Microsoft resource compiler @code{rc.exe}
30858 to produce a @file{.res} file (binary resource file). See the
30859 corresponding Microsoft documentation for further details. In this case
30860 you need to use @code{windres} to translate the @file{.res} file to a
30861 GNAT-compatible object file as follows:
30862
30863 @smallexample
30864 $ windres -i myres.res -o myres.o
30865 @end smallexample
30866
30867 @node Using Resources
30868 @subsection Using Resources
30869 @cindex Resources, using
30870
30871 @noindent
30872 To include the resource file in your program just add the
30873 GNAT-compatible object file for the resource(s) to the linker
30874 arguments. With @command{gnatmake} this is done by using the @option{-largs}
30875 option:
30876
30877 @smallexample
30878 $ gnatmake myprog -largs myres.o
30879 @end smallexample
30880
30881 @node Debugging a DLL
30882 @section Debugging a DLL
30883 @cindex DLL debugging
30884
30885 @menu
30886 * Program and DLL Both Built with GCC/GNAT::
30887 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
30888 @end menu
30889
30890 @noindent
30891 Debugging a DLL is similar to debugging a standard program. But
30892 we have to deal with two different executable parts: the DLL and the
30893 program that uses it. We have the following four possibilities:
30894
30895 @enumerate 1
30896 @item
30897 The program and the DLL are built with @code{GCC/GNAT}.
30898 @item
30899 The program is built with foreign tools and the DLL is built with
30900 @code{GCC/GNAT}.
30901 @item
30902 The program is built with @code{GCC/GNAT} and the DLL is built with
30903 foreign tools.
30904 @end enumerate
30905
30906 @noindent
30907 In this section we address only cases one and two above.
30908 There is no point in trying to debug
30909 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
30910 information in it. To do so you must use a debugger compatible with the
30911 tools suite used to build the DLL.
30912
30913 @node Program and DLL Both Built with GCC/GNAT
30914 @subsection Program and DLL Both Built with GCC/GNAT
30915
30916 @noindent
30917 This is the simplest case. Both the DLL and the program have @code{GDB}
30918 compatible debugging information. It is then possible to break anywhere in
30919 the process. Let's suppose here that the main procedure is named
30920 @code{ada_main} and that in the DLL there is an entry point named
30921 @code{ada_dll}.
30922
30923 @noindent
30924 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
30925 program must have been built with the debugging information (see GNAT -g
30926 switch). Here are the step-by-step instructions for debugging it:
30927
30928 @enumerate 1
30929 @item Launch @code{GDB} on the main program.
30930
30931 @smallexample
30932 $ gdb -nw ada_main
30933 @end smallexample
30934
30935 @item Start the program and stop at the beginning of the main procedure
30936
30937 @smallexample
30938 (gdb) start
30939 @end smallexample
30940
30941 @noindent
30942 This step is required to be able to set a breakpoint inside the DLL. As long
30943 as the program is not run, the DLL is not loaded. This has the
30944 consequence that the DLL debugging information is also not loaded, so it is not
30945 possible to set a breakpoint in the DLL.
30946
30947 @item Set a breakpoint inside the DLL
30948
30949 @smallexample
30950 (gdb) break ada_dll
30951 (gdb) cont
30952 @end smallexample
30953
30954 @end enumerate
30955
30956 @noindent
30957 At this stage a breakpoint is set inside the DLL. From there on
30958 you can use the standard approach to debug the whole program
30959 (@pxref{Running and Debugging Ada Programs}).
30960
30961 @ignore
30962 @c This used to work, probably because the DLLs were non-relocatable
30963 @c keep this section around until the problem is sorted out.
30964
30965 To break on the @code{DllMain} routine it is not possible to follow
30966 the procedure above. At the time the program stop on @code{ada_main}
30967 the @code{DllMain} routine as already been called. Either you can use
30968 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
30969
30970 @enumerate 1
30971 @item Launch @code{GDB} on the main program.
30972
30973 @smallexample
30974 $ gdb ada_main
30975 @end smallexample
30976
30977 @item Load DLL symbols
30978
30979 @smallexample
30980 (gdb) add-sym api.dll
30981 @end smallexample
30982
30983 @item Set a breakpoint inside the DLL
30984
30985 @smallexample
30986 (gdb) break ada_dll.adb:45
30987 @end smallexample
30988
30989 Note that at this point it is not possible to break using the routine symbol
30990 directly as the program is not yet running. The solution is to break
30991 on the proper line (break in @file{ada_dll.adb} line 45).
30992
30993 @item Start the program
30994
30995 @smallexample
30996 (gdb) run
30997 @end smallexample
30998
30999 @end enumerate
31000 @end ignore
31001
31002 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
31003 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
31004
31005 @menu
31006 * Debugging the DLL Directly::
31007 * Attaching to a Running Process::
31008 @end menu
31009
31010 @noindent
31011 In this case things are slightly more complex because it is not possible to
31012 start the main program and then break at the beginning to load the DLL and the
31013 associated DLL debugging information. It is not possible to break at the
31014 beginning of the program because there is no @code{GDB} debugging information,
31015 and therefore there is no direct way of getting initial control. This
31016 section addresses this issue by describing some methods that can be used
31017 to break somewhere in the DLL to debug it.
31018
31019 @noindent
31020 First suppose that the main procedure is named @code{main} (this is for
31021 example some C code built with Microsoft Visual C) and that there is a
31022 DLL named @code{test.dll} containing an Ada entry point named
31023 @code{ada_dll}.
31024
31025 @noindent
31026 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
31027 been built with debugging information (see GNAT -g option).
31028
31029 @node Debugging the DLL Directly
31030 @subsubsection Debugging the DLL Directly
31031
31032 @enumerate 1
31033 @item
31034 Find out the executable starting address
31035
31036 @smallexample
31037 $ objdump --file-header main.exe
31038 @end smallexample
31039
31040 The starting address is reported on the last line. For example:
31041
31042 @smallexample
31043 main.exe: file format pei-i386
31044 architecture: i386, flags 0x0000010a:
31045 EXEC_P, HAS_DEBUG, D_PAGED
31046 start address 0x00401010
31047 @end smallexample
31048
31049 @item
31050 Launch the debugger on the executable.
31051
31052 @smallexample
31053 $ gdb main.exe
31054 @end smallexample
31055
31056 @item
31057 Set a breakpoint at the starting address, and launch the program.
31058
31059 @smallexample
31060 $ (gdb) break *0x00401010
31061 $ (gdb) run
31062 @end smallexample
31063
31064 The program will stop at the given address.
31065
31066 @item
31067 Set a breakpoint on a DLL subroutine.
31068
31069 @smallexample
31070 (gdb) break ada_dll.adb:45
31071 @end smallexample
31072
31073 Or if you want to break using a symbol on the DLL, you need first to
31074 select the Ada language (language used by the DLL).
31075
31076 @smallexample
31077 (gdb) set language ada
31078 (gdb) break ada_dll
31079 @end smallexample
31080
31081 @item
31082 Continue the program.
31083
31084 @smallexample
31085 (gdb) cont
31086 @end smallexample
31087
31088 @noindent
31089 This will run the program until it reaches the breakpoint that has been
31090 set. From that point you can use the standard way to debug a program
31091 as described in (@pxref{Running and Debugging Ada Programs}).
31092
31093 @end enumerate
31094
31095 @noindent
31096 It is also possible to debug the DLL by attaching to a running process.
31097
31098 @node Attaching to a Running Process
31099 @subsubsection Attaching to a Running Process
31100 @cindex DLL debugging, attach to process
31101
31102 @noindent
31103 With @code{GDB} it is always possible to debug a running process by
31104 attaching to it. It is possible to debug a DLL this way. The limitation
31105 of this approach is that the DLL must run long enough to perform the
31106 attach operation. It may be useful for instance to insert a time wasting
31107 loop in the code of the DLL to meet this criterion.
31108
31109 @enumerate 1
31110
31111 @item Launch the main program @file{main.exe}.
31112
31113 @smallexample
31114 $ main
31115 @end smallexample
31116
31117 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
31118 that the process PID for @file{main.exe} is 208.
31119
31120 @item Launch gdb.
31121
31122 @smallexample
31123 $ gdb
31124 @end smallexample
31125
31126 @item Attach to the running process to be debugged.
31127
31128 @smallexample
31129 (gdb) attach 208
31130 @end smallexample
31131
31132 @item Load the process debugging information.
31133
31134 @smallexample
31135 (gdb) symbol-file main.exe
31136 @end smallexample
31137
31138 @item Break somewhere in the DLL.
31139
31140 @smallexample
31141 (gdb) break ada_dll
31142 @end smallexample
31143
31144 @item Continue process execution.
31145
31146 @smallexample
31147 (gdb) cont
31148 @end smallexample
31149
31150 @end enumerate
31151
31152 @noindent
31153 This last step will resume the process execution, and stop at
31154 the breakpoint we have set. From there you can use the standard
31155 approach to debug a program as described in
31156 (@pxref{Running and Debugging Ada Programs}).
31157
31158 @node Setting Stack Size from gnatlink
31159 @section Setting Stack Size from @command{gnatlink}
31160
31161 @noindent
31162 It is possible to specify the program stack size at link time. On modern
31163 versions of Windows, starting with XP, this is mostly useful to set the size of
31164 the main stack (environment task). The other task stacks are set with pragma
31165 Storage_Size or with the @command{gnatbind -d} command.
31166
31167 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
31168 reserve size of individual tasks, the link-time stack size applies to all
31169 tasks, and pragma Storage_Size has no effect.
31170 In particular, Stack Overflow checks are made against this
31171 link-time specified size.
31172
31173 This setting can be done with
31174 @command{gnatlink} using either:
31175
31176 @itemize @bullet
31177
31178 @item using @option{-Xlinker} linker option
31179
31180 @smallexample
31181 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
31182 @end smallexample
31183
31184 This sets the stack reserve size to 0x10000 bytes and the stack commit
31185 size to 0x1000 bytes.
31186
31187 @item using @option{-Wl} linker option
31188
31189 @smallexample
31190 $ gnatlink hello -Wl,--stack=0x1000000
31191 @end smallexample
31192
31193 This sets the stack reserve size to 0x1000000 bytes. Note that with
31194 @option{-Wl} option it is not possible to set the stack commit size
31195 because the coma is a separator for this option.
31196
31197 @end itemize
31198
31199 @node Setting Heap Size from gnatlink
31200 @section Setting Heap Size from @command{gnatlink}
31201
31202 @noindent
31203 Under Windows systems, it is possible to specify the program heap size from
31204 @command{gnatlink} using either:
31205
31206 @itemize @bullet
31207
31208 @item using @option{-Xlinker} linker option
31209
31210 @smallexample
31211 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
31212 @end smallexample
31213
31214 This sets the heap reserve size to 0x10000 bytes and the heap commit
31215 size to 0x1000 bytes.
31216
31217 @item using @option{-Wl} linker option
31218
31219 @smallexample
31220 $ gnatlink hello -Wl,--heap=0x1000000
31221 @end smallexample
31222
31223 This sets the heap reserve size to 0x1000000 bytes. Note that with
31224 @option{-Wl} option it is not possible to set the heap commit size
31225 because the coma is a separator for this option.
31226
31227 @end itemize
31228
31229 @node Mac OS Topics
31230 @appendix Mac OS Topics
31231 @cindex OS X
31232
31233 @noindent
31234 This chapter describes topics that are specific to Apple's OS X
31235 platform.
31236
31237 @menu
31238 * Codesigning the Debugger::
31239 @end menu
31240
31241 @node Codesigning the Debugger
31242 @section Codesigning the Debugger
31243
31244 @noindent
31245 The Darwin Kernel requires the debugger to have special permissions
31246 before it is allowed to control other processes. These permissions
31247 are granted by codesigning the GDB executable. Without these
31248 permissions, the debugger will report error messages such as:
31249
31250 @smallexample
31251 Starting program: /x/y/foo
31252 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
31253 (please check gdb is codesigned - see taskgated(8))
31254 @end smallexample
31255
31256 Codesigning requires a certificate. The following procedure explains
31257 how to create one:
31258
31259 @itemize @bullet
31260 @item Start the Keychain Access application (in
31261 /Applications/Utilities/Keychain Access.app)
31262
31263 @item Select the Keychain Access -> Certificate Assistant ->
31264 Create a Certificate... menu
31265
31266 @item Then:
31267
31268 @itemize @bullet
31269 @item Choose a name for the new certificate (this procedure will use
31270 "gdb-cert" as an example)
31271
31272 @item Set "Identity Type" to "Self Signed Root"
31273
31274 @item Set "Certificate Type" to "Code Signing"
31275
31276 @item Activate the "Let me override defaults" option
31277
31278 @end itemize
31279
31280 @item Click several times on "Continue" until the "Specify a Location
31281 For The Certificate" screen appears, then set "Keychain" to "System"
31282
31283 @item Click on "Continue" until the certificate is created
31284
31285 @item Finally, in the view, double-click on the new certificate,
31286 and set "When using this certificate" to "Always Trust"
31287
31288 @item Exit the Keychain Access application and restart the computer
31289 (this is unfortunately required)
31290
31291 @end itemize
31292
31293 Once a certificate has been created, the debugger can be codesigned
31294 as follow. In a Terminal, run the following command...
31295
31296 @smallexample
31297 codesign -f -s "gdb-cert" <gnat_install_prefix>/bin/gdb
31298 @end smallexample
31299
31300 ... where "gdb-cert" should be replaced by the actual certificate
31301 name chosen above, and <gnat_install_prefix> should be replaced by
31302 the location where you installed GNAT.
31303
31304 @c **********************************
31305 @c * GNU Free Documentation License *
31306 @c **********************************
31307 @include fdl.texi
31308 @c GNU Free Documentation License
31309
31310 @node Index
31311 @unnumbered Index
31312
31313 @printindex cp
31314
31315 @contents
31316 @c Put table of contents at end, otherwise it precedes the "title page" in
31317 @c the .txt version
31318 @c Edit the pdf file to move the contents to the beginning, after the title
31319 @c page
31320
31321 @bye