[multiple changes]
[gcc.git] / gcc / ada / gnat_ugn.texi
1 \input texinfo @c -*-texinfo-*-
2 @c %**start of header
3
4 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
5 @c o
6 @c GNAT DOCUMENTATION o
7 @c o
8 @c G N A T _ U G N o
9 @c o
10 @c Copyright (C) 1992-2014, Free Software Foundation, Inc. o
11 @c o
12 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
13
14 @setfilename gnat_ugn.info
15
16 @copying
17 Copyright @copyright{} 1995-2014 Free Software Foundation,
18 Inc.
19
20 Permission is granted to copy, distribute and/or modify this document
21 under the terms of the GNU Free Documentation License, Version 1.3 or
22 any later version published by the Free Software Foundation; with no
23 Invariant Sections, with no Front-Cover Texts and with no Back-Cover
24 Texts. A copy of the license is included in the section entitled
25 ``GNU Free Documentation License''.
26 @end copying
27
28 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
29 @c
30 @c GNAT_UGN Style Guide
31 @c
32 @c 1. Always put a @noindent on the line before the first paragraph
33 @c after any of these commands:
34 @c
35 @c @chapter
36 @c @section
37 @c @subsection
38 @c @subsubsection
39 @c @subsubsubsection
40 @c
41 @c @end smallexample
42 @c @end itemize
43 @c @end enumerate
44 @c
45 @c 2. DO NOT use @example. Use @smallexample instead.
46 @c a) DO NOT use highlighting commands (@b{}, @i{}) inside an @smallexample
47 @c context. These can interfere with the readability of the texi
48 @c source file. Instead, use one of the following annotated
49 @c @smallexample commands, and preprocess the texi file with the
50 @c ada2texi tool (which generates appropriate highlighting):
51 @c @smallexample @c ada
52 @c @smallexample @c adanocomment
53 @c @smallexample @c projectfile
54 @c b) The "@c ada" markup will result in boldface for reserved words
55 @c and italics for comments
56 @c c) The "@c adanocomment" markup will result only in boldface for
57 @c reserved words (comments are left alone)
58 @c d) The "@c projectfile" markup is like "@c ada" except that the set
59 @c of reserved words include the new reserved words for project files
60 @c
61 @c 3. Each @chapter, @section, @subsection, @subsubsection, etc.
62 @c command must be preceded by two empty lines
63 @c
64 @c 4. The @item command should be on a line of its own if it is in an
65 @c @itemize or @enumerate command.
66 @c
67 @c 5. When talking about ALI files use "ALI" (all uppercase), not "Ali"
68 @c or "ali".
69 @c
70 @c 6. DO NOT put trailing spaces at the end of a line. Such spaces will
71 @c cause the document build to fail.
72 @c
73 @c 7. DO NOT use @cartouche for examples that are longer than around 10 lines.
74 @c This command inhibits page breaks, so long examples in a @cartouche can
75 @c lead to large, ugly patches of empty space on a page.
76 @c
77 @c NOTE: This file should be submitted to xgnatugn with either the vms flag
78 @c or the unw flag set. The unw flag covers topics for both Unix and
79 @c Windows.
80 @c
81 @c oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo
82
83 @set NOW January 2007
84 @c This flag is used where the text refers to conditions that exist when the
85 @c text was entered into the document but which may change over time.
86 @c Update the setting for the flag, and (if necessary) the text surrounding,
87 @c the references to the flag, on future doc revisions:
88 @c search for @value{NOW}.
89
90 @set FSFEDITION
91 @set EDITION GNAT
92
93 @ifset unw
94 @set PLATFORM
95 @set TITLESUFFIX
96 @end ifset
97
98 @ifset vms
99 @set PLATFORM OpenVMS
100 @set TITLESUFFIX for OpenVMS
101 @end ifset
102
103 @c @ovar(ARG)
104 @c ----------
105 @c The ARG is an optional argument. To be used for macro arguments in
106 @c their documentation (@defmac).
107 @macro ovar{varname}
108 @r{[}@var{\varname\}@r{]}@c
109 @end macro
110 @c Status as of November 2009:
111 @c Unfortunately texi2pdf and texi2html treat the trailing "@c"
112 @c differently, and faulty output is produced by one or the other
113 @c depending on whether the "@c" is present or absent.
114 @c As a result, the @ovar macro is not used, and all invocations
115 @c of the @ovar macro have been expanded inline.
116
117
118 @settitle @value{EDITION} User's Guide @value{TITLESUFFIX}
119 @dircategory GNU Ada tools
120 @direntry
121 * @value{EDITION} User's Guide: (gnat_ugn). @value{PLATFORM}
122 @end direntry
123
124 @include gcc-common.texi
125
126 @setchapternewpage odd
127 @syncodeindex fn cp
128 @c %**end of header
129
130 @titlepage
131 @title @value{EDITION} User's Guide
132 @ifset vms
133 @sp 1
134 @flushright
135 @titlefont{@i{@value{PLATFORM}}}
136 @end flushright
137 @end ifset
138
139 @sp 2
140
141 @subtitle GNAT, The GNU Ada Development Environment
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 Development Environment@*
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 @ifclear FSFEDITION
182 * The GNAT Pretty-Printer gnatpp::
183 @ifclear vms
184 * The Ada-to-XML converter gnat2xml::
185 @end ifclear
186 * The GNAT Metrics Tool gnatmetric::
187 @end ifclear
188 * File Name Krunching with gnatkr::
189 * Preprocessing with gnatprep::
190 * The GNAT Library Browser gnatls::
191 * Cleaning Up with gnatclean::
192 @ifclear vms
193 * GNAT and Libraries::
194 * Using the GNU make Utility::
195 @end ifclear
196 * Memory Management Issues::
197 * Stack Related Facilities::
198 @ifclear FSFEDITION
199 * Verifying Properties with gnatcheck::
200 * Creating Sample Bodies with gnatstub::
201 * Creating Unit Tests with gnattest::
202 @end ifclear
203 * Performing Dimensionality Analysis in GNAT::
204 * Generating Ada Bindings for C and C++ headers::
205 * Other Utility Programs::
206 @ifclear vms
207 * Code Coverage and Profiling::
208 @end ifclear
209 * Running and Debugging Ada Programs::
210 @ifset vms
211 * Compatibility with HP Ada::
212 @end ifset
213 * Platform-Specific Information for the Run-Time Libraries::
214 * Example of Binder Output File::
215 * Elaboration Order Handling in GNAT::
216 * Overflow Check Handling in GNAT::
217 * Conditional Compilation::
218 * Inline Assembler::
219 * Compatibility and Porting Guide::
220 * Microsoft Windows Topics::
221 * Mac OS Topics::
222 * GNU Free Documentation License::
223 * Index::
224 @end menu
225 @end ifnottex
226
227 @node About This Guide
228 @unnumbered About This Guide
229
230 @noindent
231 @ifset vms
232 This guide describes the use of @value{EDITION},
233 a compiler and software development toolset for the full Ada
234 programming language, implemented on OpenVMS for HP's Alpha and
235 Integrity server (I64) platforms.
236 @end ifset
237 @ifclear vms
238 This guide describes the use of @value{EDITION},
239 a compiler and software development
240 toolset for the full Ada programming language.
241 @end ifclear
242 It documents the features of the compiler and tools, and explains
243 how to use them to build Ada applications.
244
245 @value{EDITION} implements Ada 95, Ada 2005 and Ada 2012, and it may also be
246 invoked in Ada 83 compatibility mode.
247 By default, @value{EDITION} assumes Ada 2012, but you can override with a
248 compiler switch (@pxref{Compiling Different Versions of Ada})
249 to explicitly specify the language version.
250 Throughout this manual, references to ``Ada'' without a year suffix
251 apply to all Ada 95/2005/2012 versions of the language.
252
253 @ifclear FSFEDITION
254 For ease of exposition, ``@value{EDITION}'' will be referred to simply as
255 ``GNAT'' in the remainder of this document.
256 @end ifclear
257
258
259 @menu
260 * What This Guide Contains::
261 * What You Should Know before Reading This Guide::
262 * Related Information::
263 * Conventions::
264 @end menu
265
266 @node What This Guide Contains
267 @unnumberedsec What This Guide Contains
268
269 @noindent
270 This guide contains the following chapters:
271 @itemize @bullet
272
273 @item
274 @ref{Getting Started with GNAT}, describes how to get started compiling
275 and running Ada programs with the GNAT Ada programming environment.
276 @item
277 @ref{The GNAT Compilation Model}, describes the compilation model used
278 by GNAT.
279
280 @item
281 @ref{Compiling with gcc}, describes how to compile
282 Ada programs with @command{gcc}, the Ada compiler.
283
284 @item
285 @ref{Binding with gnatbind}, describes how to
286 perform binding of Ada programs with @code{gnatbind}, the GNAT binding
287 utility.
288
289 @item
290 @ref{Linking with gnatlink},
291 describes @command{gnatlink}, a
292 program that provides for linking using the GNAT run-time library to
293 construct a program. @command{gnatlink} can also incorporate foreign language
294 object units into the executable.
295
296 @item
297 @ref{The GNAT Make Program gnatmake}, describes @command{gnatmake}, a
298 utility that automatically determines the set of sources
299 needed by an Ada compilation unit, and executes the necessary compilations
300 binding and link.
301
302 @item
303 @ref{Improving Performance}, shows various techniques for making your
304 Ada program run faster or take less space and describes the effect of
305 the compiler's optimization switch.
306 It also describes
307 @ifclear FSFEDITION
308 the @command{gnatelim} tool and
309 @end ifclear
310 unused subprogram/data elimination.
311
312 @item
313 @ref{Renaming Files with gnatchop}, describes
314 @code{gnatchop}, a utility that allows you to preprocess a file that
315 contains Ada source code, and split it into one or more new files, one
316 for each compilation unit.
317
318 @item
319 @ref{Configuration Pragmas}, describes the configuration pragmas
320 handled by GNAT.
321
322 @item
323 @ref{Handling Arbitrary File Naming Conventions with gnatname},
324 shows how to override the default GNAT file naming conventions,
325 either for an individual unit or globally.
326
327 @item
328 @ref{GNAT Project Manager}, describes how to use project files
329 to organize large projects.
330
331 @item
332 @ref{The Cross-Referencing Tools gnatxref and gnatfind}, discusses
333 @code{gnatxref} and @code{gnatfind}, two tools that provide an easy
334 way to navigate through sources.
335
336 @ifclear FSFEDITION
337 @item
338 @ref{The GNAT Pretty-Printer gnatpp}, shows how to produce a reformatted
339 version of an Ada source file with control over casing, indentation,
340 comment placement, and other elements of program presentation style.
341 @end ifclear
342
343 @ifclear FSFEDITION
344 @ifclear vms
345 @item
346 @ref{The Ada-to-XML converter gnat2xml}, shows how to convert Ada
347 source code into XML.
348 @end ifclear
349 @end ifclear
350
351 @ifclear FSFEDITION
352 @item
353 @ref{The GNAT Metrics Tool gnatmetric}, shows how to compute various
354 metrics for an Ada source file, such as the number of types and subprograms,
355 and assorted complexity measures.
356 @end ifclear
357
358 @item
359 @ref{File Name Krunching with gnatkr}, describes the @code{gnatkr}
360 file name krunching utility, used to handle shortened
361 file names on operating systems with a limit on the length of names.
362
363 @item
364 @ref{Preprocessing with gnatprep}, describes @code{gnatprep}, a
365 preprocessor utility that allows a single source file to be used to
366 generate multiple or parameterized source files by means of macro
367 substitution.
368
369 @item
370 @ref{The GNAT Library Browser gnatls}, describes @code{gnatls}, a
371 utility that displays information about compiled units, including dependences
372 on the corresponding sources files, and consistency of compilations.
373
374 @item
375 @ref{Cleaning Up with gnatclean}, describes @code{gnatclean}, a utility
376 to delete files that are produced by the compiler, binder and linker.
377
378 @ifclear vms
379 @item
380 @ref{GNAT and Libraries}, describes the process of creating and using
381 Libraries with GNAT. It also describes how to recompile the GNAT run-time
382 library.
383
384 @item
385 @ref{Using the GNU make Utility}, describes some techniques for using
386 the GNAT toolset in Makefiles.
387 @end ifclear
388
389 @item
390 @ref{Memory Management Issues}, describes some useful predefined storage pools
391 and in particular the GNAT Debug Pool facility, which helps detect incorrect
392 memory references.
393 @ifclear vms
394 @ifclear FSFEDITION
395 It also describes @command{gnatmem}, a utility that monitors dynamic
396 allocation and deallocation and helps detect ``memory leaks''.
397 @end ifclear
398 @end ifclear
399
400 @item
401 @ref{Stack Related Facilities}, describes some useful tools associated with
402 stack checking and analysis.
403
404 @ifclear FSFEDITION
405 @item
406 @ref{Verifying Properties with gnatcheck}, discusses @code{gnatcheck},
407 a utility that checks Ada code against a set of rules.
408
409 @item
410 @ref{Creating Sample Bodies with gnatstub}, discusses @code{gnatstub},
411 a utility that generates empty but compilable bodies for library units.
412 @end ifclear
413
414 @ifclear FSFEDITION
415 @item
416 @ref{Creating Unit Tests with gnattest}, discusses @code{gnattest},
417 a utility that generates unit testing templates for library units.
418 @end ifclear
419
420 @item
421 @ref{Performing Dimensionality Analysis in GNAT}, describes the Ada 2012
422 facilities used in GNAT to declare dimensioned objects, and to verify that
423 uses of these objects are consistent with their given physical dimensions
424 (so that meters cannot be assigned to kilograms, and so on).
425
426 @item
427 @ref{Generating Ada Bindings for C and C++ headers}, describes how to
428 generate automatically Ada bindings from C and C++ headers.
429
430 @item
431 @ref{Other Utility Programs}, discusses several other GNAT utilities,
432 including @code{gnathtml}.
433
434 @ifclear vms
435 @item
436 @ref{Code Coverage and Profiling}, describes how to perform a structural
437 coverage and profile the execution of Ada programs.
438 @end ifclear
439
440 @item
441 @ref{Running and Debugging Ada Programs}, describes how to run and debug
442 Ada programs.
443
444 @ifset vms
445 @item
446 @ref{Compatibility with HP Ada}, details the compatibility of GNAT with
447 HP Ada 83 @footnote{``HP Ada'' refers to the legacy product originally
448 developed by Digital Equipment Corporation and currently supported by HP.}
449 for OpenVMS Alpha. This product was formerly known as DEC Ada,
450 @cindex DEC Ada
451 and for
452 historical compatibility reasons, the relevant libraries still use the
453 DEC prefix.
454 @end ifset
455
456 @item
457 @ref{Platform-Specific Information for the Run-Time Libraries},
458 describes the various run-time
459 libraries supported by GNAT on various platforms and explains how to
460 choose a particular library.
461
462 @item
463 @ref{Example of Binder Output File}, shows the source code for the binder
464 output file for a sample program.
465
466 @item
467 @ref{Elaboration Order Handling in GNAT}, describes how GNAT helps
468 you deal with elaboration order issues.
469
470 @item
471 @ref{Overflow Check Handling in GNAT}, describes how GNAT helps
472 you deal with arithmetic overflow issues.
473
474 @item
475 @ref{Conditional Compilation}, describes how to model conditional compilation,
476 both with Ada in general and with GNAT facilities in particular.
477
478 @item
479 @ref{Inline Assembler}, shows how to use the inline assembly facility
480 in an Ada program.
481
482 @item
483 @ref{Compatibility and Porting Guide}, contains sections on compatibility
484 of GNAT with other Ada development environments (including Ada 83 systems),
485 to assist in porting code from those environments.
486
487 @ifset unw
488 @item
489 @ref{Microsoft Windows Topics}, presents information relevant to the
490 Microsoft Windows platform.
491
492 @item
493 @ref{Mac OS Topics}, presents information relevant to Apple's OS X
494 platform.
495 @end ifset
496 @end itemize
497
498 @c *************************************************
499 @node What You Should Know before Reading This Guide
500 @c *************************************************
501 @unnumberedsec What You Should Know before Reading This Guide
502
503 @cindex Ada 95 Language Reference Manual
504 @cindex Ada 2005 Language Reference Manual
505 @noindent
506 This guide assumes a basic familiarity with the Ada 95 language, as
507 described in the International Standard ANSI/ISO/IEC-8652:1995, January
508 1995.
509 It does not require knowledge of the new features introduced by Ada 2005,
510 (officially known as ISO/IEC 8652:1995 with Technical Corrigendum 1
511 and Amendment 1).
512 Both reference manuals are included in the GNAT documentation
513 package.
514
515 @node Related Information
516 @unnumberedsec Related Information
517
518 @noindent
519 For further information about related tools, refer to the following
520 documents:
521
522 @itemize @bullet
523 @item
524 @xref{Top, GNAT Reference Manual, About This Guide, gnat_rm, GNAT
525 Reference Manual}, which contains all reference material for the GNAT
526 implementation of Ada.
527
528 @ifset unw
529 @item
530 @cite{Using the GNAT Programming Studio}, which describes the GPS
531 Integrated Development Environment.
532
533 @item
534 @cite{GNAT Programming Studio Tutorial}, which introduces the
535 main GPS features through examples.
536 @end ifset
537
538 @item
539 @cite{Ada 95 Reference Manual}, which contains reference
540 material for the Ada 95 programming language.
541
542 @item
543 @cite{Ada 2005 Reference Manual}, which contains reference
544 material for the Ada 2005 programming language.
545
546 @item
547 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
548 @ifset vms
549 in the GNU:[DOCS] directory,
550 @end ifset
551 for all details on the use of the GNU source-level debugger.
552
553 @item
554 @xref{Top,, The extensible self-documenting text editor, emacs,
555 GNU Emacs Manual},
556 @ifset vms
557 located in the GNU:[DOCS] directory if the EMACS kit is installed,
558 @end ifset
559 for full information on the extensible editor and programming
560 environment Emacs.
561
562 @end itemize
563
564 @c **************
565 @node Conventions
566 @unnumberedsec Conventions
567 @cindex Conventions
568 @cindex Typographical conventions
569
570 @noindent
571 Following are examples of the typographical and graphic conventions used
572 in this guide:
573
574 @itemize @bullet
575 @item
576 @code{Functions}, @command{utility program names}, @code{standard names},
577 and @code{classes}.
578
579 @item
580 @option{Option flags}
581
582 @item
583 @file{File names}, @samp{button names}, and @samp{field names}.
584
585 @item
586 @code{Variables}, @env{environment variables}, and @var{metasyntactic
587 variables}.
588
589 @item
590 @emph{Emphasis}.
591
592 @item
593 @r{[}optional information or parameters@r{]}
594
595 @item
596 Examples are described by text
597 @smallexample
598 and then shown this way.
599 @end smallexample
600 @end itemize
601
602 @noindent
603 Commands that are entered by the user are preceded in this manual by the
604 characters @w{``@code{$ }''} (dollar sign followed by space). If your system
605 uses this sequence as a prompt, then the commands will appear exactly as
606 you see them in the manual. If your system uses some other prompt, then
607 the command will appear with the @code{$} replaced by whatever prompt
608 character you are using.
609
610 @ifset unw
611 Full file names are shown with the ``@code{/}'' character
612 as the directory separator; e.g., @file{parent-dir/subdir/myfile.adb}.
613 If you are using GNAT on a Windows platform, please note that
614 the ``@code{\}'' character should be used instead.
615 @end ifset
616
617 @c ****************************
618 @node Getting Started with GNAT
619 @chapter Getting Started with GNAT
620
621 @noindent
622 This chapter describes some simple ways of using GNAT to build
623 executable Ada programs.
624 @ifset unw
625 @ref{Running GNAT}, through @ref{Using the gnatmake Utility},
626 show how to use the command line environment.
627 @ref{Introduction to GPS}, provides a brief
628 introduction to the GNAT Programming Studio, a visually-oriented
629 Integrated Development Environment for GNAT.
630 GPS offers a graphical ``look and feel'', support for development in
631 other programming languages, comprehensive browsing features, and
632 many other capabilities.
633 For information on GPS please refer to
634 @cite{Using the GNAT Programming Studio}.
635 @end ifset
636
637 @menu
638 * Running GNAT::
639 * Running a Simple Ada Program::
640 * Running a Program with Multiple Units::
641 * Using the gnatmake Utility::
642 @ifset vms
643 * Editing with Emacs::
644 @end ifset
645 @ifclear vms
646 * Introduction to GPS::
647 @end ifclear
648 @end menu
649
650 @node Running GNAT
651 @section Running GNAT
652
653 @noindent
654 Three steps are needed to create an executable file from an Ada source
655 file:
656
657 @enumerate
658 @item
659 The source file(s) must be compiled.
660 @item
661 The file(s) must be bound using the GNAT binder.
662 @item
663 All appropriate object files must be linked to produce an executable.
664 @end enumerate
665
666 @noindent
667 All three steps are most commonly handled by using the @command{gnatmake}
668 utility program that, given the name of the main program, automatically
669 performs the necessary compilation, binding and linking steps.
670
671 @node Running a Simple Ada Program
672 @section Running a Simple Ada Program
673
674 @noindent
675 Any text editor may be used to prepare an Ada program.
676 (If @code{Emacs} is
677 used, the optional Ada mode may be helpful in laying out the program.)
678 The
679 program text is a normal text file. We will assume in our initial
680 example that you have used your editor to prepare the following
681 standard format text file:
682
683 @smallexample @c ada
684 @cartouche
685 with Ada.Text_IO; use Ada.Text_IO;
686 procedure Hello is
687 begin
688 Put_Line ("Hello WORLD!");
689 end Hello;
690 @end cartouche
691 @end smallexample
692
693 @noindent
694 This file should be named @file{hello.adb}.
695 With the normal default file naming conventions, GNAT requires
696 that each file
697 contain a single compilation unit whose file name is the
698 unit name,
699 with periods replaced by hyphens; the
700 extension is @file{ads} for a
701 spec and @file{adb} for a body.
702 You can override this default file naming convention by use of the
703 special pragma @code{Source_File_Name} (@pxref{Using Other File Names}).
704 Alternatively, if you want to rename your files according to this default
705 convention, which is probably more convenient if you will be using GNAT
706 for all your compilations, then the @code{gnatchop} utility
707 can be used to generate correctly-named source files
708 (@pxref{Renaming Files with gnatchop}).
709
710 You can compile the program using the following command (@code{$} is used
711 as the command prompt in the examples in this document):
712
713 @smallexample
714 $ gcc -c hello.adb
715 @end smallexample
716
717 @noindent
718 @command{gcc} is the command used to run the compiler. This compiler is
719 capable of compiling programs in several languages, including Ada and
720 C. It assumes that you have given it an Ada program if the file extension is
721 either @file{.ads} or @file{.adb}, and it will then call
722 the GNAT compiler to compile the specified file.
723
724 @ifclear vms
725 The @option{-c} switch is required. It tells @command{gcc} to only do a
726 compilation. (For C programs, @command{gcc} can also do linking, but this
727 capability is not used directly for Ada programs, so the @option{-c}
728 switch must always be present.)
729 @end ifclear
730
731 This compile command generates a file
732 @file{hello.o}, which is the object
733 file corresponding to your Ada program. It also generates
734 an ``Ada Library Information'' file @file{hello.ali},
735 which contains additional information used to check
736 that an Ada program is consistent.
737 To build an executable file,
738 use @code{gnatbind} to bind the program
739 and @command{gnatlink} to link it. The
740 argument to both @code{gnatbind} and @command{gnatlink} is the name of the
741 @file{ALI} file, but the default extension of @file{.ali} can
742 be omitted. This means that in the most common case, the argument
743 is simply the name of the main program:
744
745 @smallexample
746 $ gnatbind hello
747 $ gnatlink hello
748 @end smallexample
749
750 @noindent
751 A simpler method of carrying out these steps is to use
752 @command{gnatmake},
753 a master program that invokes all the required
754 compilation, binding and linking tools in the correct order. In particular,
755 @command{gnatmake} automatically recompiles any sources that have been
756 modified since they were last compiled, or sources that depend
757 on such modified sources, so that ``version skew'' is avoided.
758 @cindex Version skew (avoided by @command{gnatmake})
759
760 @smallexample
761 $ gnatmake hello.adb
762 @end smallexample
763
764 @noindent
765 The result is an executable program called @file{hello}, which can be
766 run by entering:
767
768 @smallexample
769 $ ^hello^RUN HELLO^
770 @end smallexample
771
772 @noindent
773 assuming that the current directory is on the search path
774 for executable programs.
775
776 @noindent
777 and, if all has gone well, you will see
778
779 @smallexample
780 Hello WORLD!
781 @end smallexample
782
783 @noindent
784 appear in response to this command.
785
786 @c ****************************************
787 @node Running a Program with Multiple Units
788 @section Running a Program with Multiple Units
789
790 @noindent
791 Consider a slightly more complicated example that has three files: a
792 main program, and the spec and body of a package:
793
794 @smallexample @c ada
795 @cartouche
796 @group
797 package Greetings is
798 procedure Hello;
799 procedure Goodbye;
800 end Greetings;
801
802 with Ada.Text_IO; use Ada.Text_IO;
803 package body Greetings is
804 procedure Hello is
805 begin
806 Put_Line ("Hello WORLD!");
807 end Hello;
808
809 procedure Goodbye is
810 begin
811 Put_Line ("Goodbye WORLD!");
812 end Goodbye;
813 end Greetings;
814 @end group
815
816 @group
817 with Greetings;
818 procedure Gmain is
819 begin
820 Greetings.Hello;
821 Greetings.Goodbye;
822 end Gmain;
823 @end group
824 @end cartouche
825 @end smallexample
826
827 @noindent
828 Following the one-unit-per-file rule, place this program in the
829 following three separate files:
830
831 @table @file
832 @item greetings.ads
833 spec of package @code{Greetings}
834
835 @item greetings.adb
836 body of package @code{Greetings}
837
838 @item gmain.adb
839 body of main program
840 @end table
841
842 @noindent
843 To build an executable version of
844 this program, we could use four separate steps to compile, bind, and link
845 the program, as follows:
846
847 @smallexample
848 $ gcc -c gmain.adb
849 $ gcc -c greetings.adb
850 $ gnatbind gmain
851 $ gnatlink gmain
852 @end smallexample
853
854 @noindent
855 Note that there is no required order of compilation when using GNAT.
856 In particular it is perfectly fine to compile the main program first.
857 Also, it is not necessary to compile package specs in the case where
858 there is an accompanying body; you only need to compile the body. If you want
859 to submit these files to the compiler for semantic checking and not code
860 generation, then use the
861 @option{-gnatc} switch:
862
863 @smallexample
864 $ gcc -c greetings.ads -gnatc
865 @end smallexample
866
867 @noindent
868 Although the compilation can be done in separate steps as in the
869 above example, in practice it is almost always more convenient
870 to use the @command{gnatmake} tool. All you need to know in this case
871 is the name of the main program's source file. The effect of the above four
872 commands can be achieved with a single one:
873
874 @smallexample
875 $ gnatmake gmain.adb
876 @end smallexample
877
878 @noindent
879 In the next section we discuss the advantages of using @command{gnatmake} in
880 more detail.
881
882 @c *****************************
883 @node Using the gnatmake Utility
884 @section Using the @command{gnatmake} Utility
885
886 @noindent
887 If you work on a program by compiling single components at a time using
888 @command{gcc}, you typically keep track of the units you modify. In order to
889 build a consistent system, you compile not only these units, but also any
890 units that depend on the units you have modified.
891 For example, in the preceding case,
892 if you edit @file{gmain.adb}, you only need to recompile that file. But if
893 you edit @file{greetings.ads}, you must recompile both
894 @file{greetings.adb} and @file{gmain.adb}, because both files contain
895 units that depend on @file{greetings.ads}.
896
897 @code{gnatbind} will warn you if you forget one of these compilation
898 steps, so that it is impossible to generate an inconsistent program as a
899 result of forgetting to do a compilation. Nevertheless it is tedious and
900 error-prone to keep track of dependencies among units.
901 One approach to handle the dependency-bookkeeping is to use a
902 makefile. However, makefiles present maintenance problems of their own:
903 if the dependencies change as you change the program, you must make
904 sure that the makefile is kept up-to-date manually, which is also an
905 error-prone process.
906
907 The @command{gnatmake} utility takes care of these details automatically.
908 Invoke it using either one of the following forms:
909
910 @smallexample
911 $ gnatmake gmain.adb
912 $ gnatmake ^gmain^GMAIN^
913 @end smallexample
914
915 @noindent
916 The argument is the name of the file containing the main program;
917 you may omit the extension. @command{gnatmake}
918 examines the environment, automatically recompiles any files that need
919 recompiling, and binds and links the resulting set of object files,
920 generating the executable file, @file{^gmain^GMAIN.EXE^}.
921 In a large program, it
922 can be extremely helpful to use @command{gnatmake}, because working out by hand
923 what needs to be recompiled can be difficult.
924
925 Note that @command{gnatmake}
926 takes into account all the Ada rules that
927 establish dependencies among units. These include dependencies that result
928 from inlining subprogram bodies, and from
929 generic instantiation. Unlike some other
930 Ada make tools, @command{gnatmake} does not rely on the dependencies that were
931 found by the compiler on a previous compilation, which may possibly
932 be wrong when sources change. @command{gnatmake} determines the exact set of
933 dependencies from scratch each time it is run.
934
935 @ifset vms
936 @node Editing with Emacs
937 @section Editing with Emacs
938 @cindex Emacs
939
940 @noindent
941 Emacs is an extensible self-documenting text editor that is available in a
942 separate VMSINSTAL kit.
943
944 Invoke Emacs by typing @kbd{Emacs} at the command prompt. To get started,
945 click on the Emacs Help menu and run the Emacs Tutorial.
946 In a character cell terminal, Emacs help is invoked with @kbd{Ctrl-h} (also
947 written as @kbd{C-h}), and the tutorial by @kbd{C-h t}.
948
949 Documentation on Emacs and other tools is available in Emacs under the
950 pull-down menu button: @code{Help - Info}. After selecting @code{Info},
951 use the middle mouse button to select a topic (e.g.@: Emacs).
952
953 In a character cell terminal, do @kbd{C-h i} to invoke info, and then @kbd{m}
954 (stands for menu) followed by the menu item desired, as in @kbd{m Emacs}, to
955 get to the Emacs manual.
956 Help on Emacs is also available by typing @kbd{HELP EMACS} at the DCL command
957 prompt.
958
959 The tutorial is highly recommended in order to learn the intricacies of Emacs,
960 which is sufficiently extensible to provide for a complete programming
961 environment and shell for the sophisticated user.
962 @end ifset
963
964 @ifclear vms
965 @node Introduction to GPS
966 @section Introduction to GPS
967 @cindex GPS (GNAT Programming Studio)
968 @cindex GNAT Programming Studio (GPS)
969 @noindent
970 Although the command line interface (@command{gnatmake}, etc.) alone
971 is sufficient, a graphical Interactive Development
972 Environment can make it easier for you to compose, navigate, and debug
973 programs. This section describes the main features of GPS
974 (``GNAT Programming Studio''), the GNAT graphical IDE.
975 You will see how to use GPS to build and debug an executable, and
976 you will also learn some of the basics of the GNAT ``project'' facility.
977
978 GPS enables you to do much more than is presented here;
979 e.g., you can produce a call graph, interface to a third-party
980 Version Control System, and inspect the generated assembly language
981 for a program.
982 Indeed, GPS also supports languages other than Ada.
983 Such additional information, and an explanation of all of the GPS menu
984 items. may be found in the on-line help, which includes
985 a user's guide and a tutorial (these are also accessible from the GNAT
986 startup menu).
987
988 @menu
989 * Building a New Program with GPS::
990 * Simple Debugging with GPS::
991 @end menu
992
993 @node Building a New Program with GPS
994 @subsection Building a New Program with GPS
995 @noindent
996 GPS invokes the GNAT compilation tools using information
997 contained in a @emph{project} (also known as a @emph{project file}):
998 a collection of properties such
999 as source directories, identities of main subprograms, tool switches, etc.,
1000 and their associated values.
1001 See @ref{GNAT Project Manager} for details.
1002 In order to run GPS, you will need to either create a new project
1003 or else open an existing one.
1004
1005 This section will explain how you can use GPS to create a project,
1006 to associate Ada source files with a project, and to build and run
1007 programs.
1008
1009 @enumerate
1010 @item @emph{Creating a project}
1011
1012 Invoke GPS, either from the command line or the platform's IDE.
1013 After it starts, GPS will display a ``Welcome'' screen with three
1014 radio buttons:
1015
1016 @itemize @bullet
1017 @item
1018 @code{Start with default project in directory}
1019
1020 @item
1021 @code{Create new project with wizard}
1022
1023 @item
1024 @code{Open existing project}
1025 @end itemize
1026
1027 @noindent
1028 Select @code{Create new project with wizard} and press @code{OK}.
1029 A new window will appear. In the text box labeled with
1030 @code{Enter the name of the project to create}, type @file{sample}
1031 as the project name.
1032 In the next box, browse to choose the directory in which you
1033 would like to create the project file.
1034 After selecting an appropriate directory, press @code{Forward}.
1035
1036 A window will appear with the title
1037 @code{Version Control System Configuration}.
1038 Simply press @code{Forward}.
1039
1040 A window will appear with the title
1041 @code{Please select the source directories for this project}.
1042 The directory that you specified for the project file will be selected
1043 by default as the one to use for sources; simply press @code{Forward}.
1044
1045 A window will appear with the title
1046 @code{Please select the build directory for this project}.
1047 The directory that you specified for the project file will be selected
1048 by default for object files and executables;
1049 simply press @code{Forward}.
1050
1051 A window will appear with the title
1052 @code{Please select the main units for this project}.
1053 You will supply this information later, after creating the source file.
1054 Simply press @code{Forward} for now.
1055
1056 A window will appear with the title
1057 @code{Please select the switches to build the project}.
1058 Press @code{Apply}. This will create a project file named
1059 @file{sample.prj} in the directory that you had specified.
1060
1061 @item @emph{Creating and saving the source file}
1062
1063 After you create the new project, a GPS window will appear, which is
1064 partitioned into two main sections:
1065
1066 @itemize @bullet
1067 @item
1068 A @emph{Workspace area}, initially greyed out, which you will use for
1069 creating and editing source files
1070
1071 @item
1072 Directly below, a @emph{Messages area}, which initially displays a
1073 ``Welcome'' message.
1074 (If the Messages area is not visible, drag its border upward to expand it.)
1075 @end itemize
1076
1077 @noindent
1078 Select @code{File} on the menu bar, and then the @code{New} command.
1079 The Workspace area will become white, and you can now
1080 enter the source program explicitly.
1081 Type the following text
1082
1083 @smallexample @c ada
1084 @group
1085 with Ada.Text_IO; use Ada.Text_IO;
1086 procedure Hello is
1087 begin
1088 Put_Line("Hello from GPS!");
1089 end Hello;
1090 @end group
1091 @end smallexample
1092
1093 @noindent
1094 Select @code{File}, then @code{Save As}, and enter the source file name
1095 @file{hello.adb}.
1096 The file will be saved in the same directory you specified as the
1097 location of the default project file.
1098
1099 @item @emph{Updating the project file}
1100
1101 You need to add the new source file to the project.
1102 To do this, select
1103 the @code{Project} menu and then @code{Edit project properties}.
1104 Click the @code{Main files} tab on the left, and then the
1105 @code{Add} button.
1106 Choose @file{hello.adb} from the list, and press @code{Open}.
1107 The project settings window will reflect this action.
1108 Click @code{OK}.
1109
1110 @item @emph{Building and running the program}
1111
1112 In the main GPS window, now choose the @code{Build} menu, then @code{Make},
1113 and select @file{hello.adb}.
1114 The Messages window will display the resulting invocations of @command{gcc},
1115 @command{gnatbind}, and @command{gnatlink}
1116 (reflecting the default switch settings from the
1117 project file that you created) and then a ``successful compilation/build''
1118 message.
1119
1120 To run the program, choose the @code{Build} menu, then @code{Run}, and
1121 select @command{hello}.
1122 An @emph{Arguments Selection} window will appear.
1123 There are no command line arguments, so just click @code{OK}.
1124
1125 The Messages window will now display the program's output (the string
1126 @code{Hello from GPS}), and at the bottom of the GPS window a status
1127 update is displayed (@code{Run: hello}).
1128 Close the GPS window (or select @code{File}, then @code{Exit}) to
1129 terminate this GPS session.
1130 @end enumerate
1131
1132 @node Simple Debugging with GPS
1133 @subsection Simple Debugging with GPS
1134 @noindent
1135 This section illustrates basic debugging techniques (setting breakpoints,
1136 examining/modifying variables, single stepping).
1137
1138 @enumerate
1139 @item @emph{Opening a project}
1140
1141 Start GPS and select @code{Open existing project}; browse to
1142 specify the project file @file{sample.prj} that you had created in the
1143 earlier example.
1144
1145 @item @emph{Creating a source file}
1146
1147 Select @code{File}, then @code{New}, and type in the following program:
1148
1149 @smallexample @c ada
1150 @group
1151 with Ada.Text_IO; use Ada.Text_IO;
1152 procedure Example is
1153 Line : String (1..80);
1154 N : Natural;
1155 begin
1156 Put_Line("Type a line of text at each prompt; an empty line to exit");
1157 loop
1158 Put(": ");
1159 Get_Line (Line, N);
1160 Put_Line (Line (1..N) );
1161 exit when N=0;
1162 end loop;
1163 end Example;
1164 @end group
1165 @end smallexample
1166
1167 @noindent
1168 Select @code{File}, then @code{Save as}, and enter the file name
1169 @file{example.adb}.
1170
1171 @item @emph{Updating the project file}
1172
1173 Add @code{Example} as a new main unit for the project:
1174 @enumerate a
1175 @item
1176 Select @code{Project}, then @code{Edit Project Properties}.
1177
1178 @item
1179 Select the @code{Main files} tab, click @code{Add}, then
1180 select the file @file{example.adb} from the list, and
1181 click @code{Open}.
1182 You will see the file name appear in the list of main units
1183
1184 @item
1185 Click @code{OK}
1186 @end enumerate
1187
1188 @item @emph{Building/running the executable}
1189
1190 To build the executable
1191 select @code{Build}, then @code{Make}, and then choose @file{example.adb}.
1192
1193 Run the program to see its effect (in the Messages area).
1194 Each line that you enter is displayed; an empty line will
1195 cause the loop to exit and the program to terminate.
1196
1197 @item @emph{Debugging the program}
1198
1199 Note that the @option{-g} switches to @command{gcc} and @command{gnatlink},
1200 which are required for debugging, are on by default when you create
1201 a new project.
1202 Thus unless you intentionally remove these settings, you will be able
1203 to debug any program that you develop using GPS.
1204
1205 @enumerate a
1206 @item @emph{Initializing}
1207
1208 Select @code{Debug}, then @code{Initialize}, then @file{example}
1209
1210 @item @emph{Setting a breakpoint}
1211
1212 After performing the initialization step, you will observe a small
1213 icon to the right of each line number.
1214 This serves as a toggle for breakpoints; clicking the icon will
1215 set a breakpoint at the corresponding line (the icon will change to
1216 a red circle with an ``x''), and clicking it again
1217 will remove the breakpoint / reset the icon.
1218
1219 For purposes of this example, set a breakpoint at line 10 (the
1220 statement @code{Put_Line@ (Line@ (1..N));}
1221
1222 @item @emph{Starting program execution}
1223
1224 Select @code{Debug}, then @code{Run}. When the
1225 @code{Program Arguments} window appears, click @code{OK}.
1226 A console window will appear; enter some line of text,
1227 e.g.@: @code{abcde}, at the prompt.
1228 The program will pause execution when it gets to the
1229 breakpoint, and the corresponding line is highlighted.
1230
1231 @item @emph{Examining a variable}
1232
1233 Move the mouse over one of the occurrences of the variable @code{N}.
1234 You will see the value (5) displayed, in ``tool tip'' fashion.
1235 Right click on @code{N}, select @code{Debug}, then select @code{Display N}.
1236 You will see information about @code{N} appear in the @code{Debugger Data}
1237 pane, showing the value as 5.
1238
1239 @item @emph{Assigning a new value to a variable}
1240
1241 Right click on the @code{N} in the @code{Debugger Data} pane, and
1242 select @code{Set value of N}.
1243 When the input window appears, enter the value @code{4} and click
1244 @code{OK}.
1245 This value does not automatically appear in the @code{Debugger Data}
1246 pane; to see it, right click again on the @code{N} in the
1247 @code{Debugger Data} pane and select @code{Update value}.
1248 The new value, 4, will appear in red.
1249
1250 @item @emph{Single stepping}
1251
1252 Select @code{Debug}, then @code{Next}.
1253 This will cause the next statement to be executed, in this case the
1254 call of @code{Put_Line} with the string slice.
1255 Notice in the console window that the displayed string is simply
1256 @code{abcd} and not @code{abcde} which you had entered.
1257 This is because the upper bound of the slice is now 4 rather than 5.
1258
1259 @item @emph{Removing a breakpoint}
1260
1261 Toggle the breakpoint icon at line 10.
1262
1263 @item @emph{Resuming execution from a breakpoint}
1264
1265 Select @code{Debug}, then @code{Continue}.
1266 The program will reach the next iteration of the loop, and
1267 wait for input after displaying the prompt.
1268 This time, just hit the @kbd{Enter} key.
1269 The value of @code{N} will be 0, and the program will terminate.
1270 The console window will disappear.
1271 @end enumerate
1272 @end enumerate
1273 @end ifclear
1274
1275 @node The GNAT Compilation Model
1276 @chapter The GNAT Compilation Model
1277 @cindex GNAT compilation model
1278 @cindex Compilation model
1279
1280 @menu
1281 * Source Representation::
1282 * Foreign Language Representation::
1283 * File Naming Rules::
1284 * Using Other File Names::
1285 * Alternative File Naming Schemes::
1286 * Generating Object Files::
1287 * Source Dependencies::
1288 * The Ada Library Information Files::
1289 * Binding an Ada Program::
1290 * Mixed Language Programming::
1291 @ifclear vms
1292 * Building Mixed Ada & C++ Programs::
1293 * Comparison between GNAT and C/C++ Compilation Models::
1294 @end ifclear
1295 * Comparison between GNAT and Conventional Ada Library Models::
1296 @ifset vms
1297 * Placement of temporary files::
1298 @end ifset
1299 @end menu
1300
1301 @noindent
1302 This chapter describes the compilation model used by GNAT. Although
1303 similar to that used by other languages, such as C and C++, this model
1304 is substantially different from the traditional Ada compilation models,
1305 which are based on a library. The model is initially described without
1306 reference to the library-based model. If you have not previously used an
1307 Ada compiler, you need only read the first part of this chapter. The
1308 last section describes and discusses the differences between the GNAT
1309 model and the traditional Ada compiler models. If you have used other
1310 Ada compilers, this section will help you to understand those
1311 differences, and the advantages of the GNAT model.
1312
1313 @node Source Representation
1314 @section Source Representation
1315 @cindex Latin-1
1316
1317 @noindent
1318 Ada source programs are represented in standard text files, using
1319 Latin-1 coding. Latin-1 is an 8-bit code that includes the familiar
1320 7-bit ASCII set, plus additional characters used for
1321 representing foreign languages (@pxref{Foreign Language Representation}
1322 for support of non-USA character sets). The format effector characters
1323 are represented using their standard ASCII encodings, as follows:
1324
1325 @table @code
1326 @item VT
1327 @findex VT
1328 Vertical tab, @code{16#0B#}
1329
1330 @item HT
1331 @findex HT
1332 Horizontal tab, @code{16#09#}
1333
1334 @item CR
1335 @findex CR
1336 Carriage return, @code{16#0D#}
1337
1338 @item LF
1339 @findex LF
1340 Line feed, @code{16#0A#}
1341
1342 @item FF
1343 @findex FF
1344 Form feed, @code{16#0C#}
1345 @end table
1346
1347 @noindent
1348 Source files are in standard text file format. In addition, GNAT will
1349 recognize a wide variety of stream formats, in which the end of
1350 physical lines is marked by any of the following sequences:
1351 @code{LF}, @code{CR}, @code{CR-LF}, or @code{LF-CR}. This is useful
1352 in accommodating files that are imported from other operating systems.
1353
1354 @cindex End of source file
1355 @cindex Source file, end
1356 @findex SUB
1357 The end of a source file is normally represented by the physical end of
1358 file. However, the control character @code{16#1A#} (@code{SUB}) is also
1359 recognized as signalling the end of the source file. Again, this is
1360 provided for compatibility with other operating systems where this
1361 code is used to represent the end of file.
1362
1363 Each file contains a single Ada compilation unit, including any pragmas
1364 associated with the unit. For example, this means you must place a
1365 package declaration (a package @dfn{spec}) and the corresponding body in
1366 separate files. An Ada @dfn{compilation} (which is a sequence of
1367 compilation units) is represented using a sequence of files. Similarly,
1368 you will place each subunit or child unit in a separate file.
1369
1370 @node Foreign Language Representation
1371 @section Foreign Language Representation
1372
1373 @noindent
1374 GNAT supports the standard character sets defined in Ada as well as
1375 several other non-standard character sets for use in localized versions
1376 of the compiler (@pxref{Character Set Control}).
1377 @menu
1378 * Latin-1::
1379 * Other 8-Bit Codes::
1380 * Wide Character Encodings::
1381 @end menu
1382
1383 @node Latin-1
1384 @subsection Latin-1
1385 @cindex Latin-1
1386
1387 @noindent
1388 The basic character set is Latin-1. This character set is defined by ISO
1389 standard 8859, part 1. The lower half (character codes @code{16#00#}
1390 @dots{} @code{16#7F#)} is identical to standard ASCII coding, but the upper
1391 half is used to represent additional characters. These include extended letters
1392 used by European languages, such as French accents, the vowels with umlauts
1393 used in German, and the extra letter A-ring used in Swedish.
1394
1395 @findex Ada.Characters.Latin_1
1396 For a complete list of Latin-1 codes and their encodings, see the source
1397 file of library unit @code{Ada.Characters.Latin_1} in file
1398 @file{a-chlat1.ads}.
1399 You may use any of these extended characters freely in character or
1400 string literals. In addition, the extended characters that represent
1401 letters can be used in identifiers.
1402
1403 @node Other 8-Bit Codes
1404 @subsection Other 8-Bit Codes
1405
1406 @noindent
1407 GNAT also supports several other 8-bit coding schemes:
1408
1409 @table @asis
1410 @item ISO 8859-2 (Latin-2)
1411 @cindex Latin-2
1412 @cindex ISO 8859-2
1413 Latin-2 letters allowed in identifiers, with uppercase and lowercase
1414 equivalence.
1415
1416 @item ISO 8859-3 (Latin-3)
1417 @cindex Latin-3
1418 @cindex ISO 8859-3
1419 Latin-3 letters allowed in identifiers, with uppercase and lowercase
1420 equivalence.
1421
1422 @item ISO 8859-4 (Latin-4)
1423 @cindex Latin-4
1424 @cindex ISO 8859-4
1425 Latin-4 letters allowed in identifiers, with uppercase and lowercase
1426 equivalence.
1427
1428 @item ISO 8859-5 (Cyrillic)
1429 @cindex ISO 8859-5
1430 @cindex Cyrillic
1431 ISO 8859-5 letters (Cyrillic) allowed in identifiers, with uppercase and
1432 lowercase equivalence.
1433
1434 @item ISO 8859-15 (Latin-9)
1435 @cindex ISO 8859-15
1436 @cindex Latin-9
1437 ISO 8859-15 (Latin-9) letters allowed in identifiers, with uppercase and
1438 lowercase equivalence
1439
1440 @item IBM PC (code page 437)
1441 @cindex code page 437
1442 This code page is the normal default for PCs in the U.S. It corresponds
1443 to the original IBM PC character set. This set has some, but not all, of
1444 the extended Latin-1 letters, but these letters do not have the same
1445 encoding as Latin-1. In this mode, these letters are allowed in
1446 identifiers with uppercase and lowercase equivalence.
1447
1448 @item IBM PC (code page 850)
1449 @cindex code page 850
1450 This code page is a modification of 437 extended to include all the
1451 Latin-1 letters, but still not with the usual Latin-1 encoding. In this
1452 mode, all these letters are allowed in identifiers with uppercase and
1453 lowercase equivalence.
1454
1455 @item Full Upper 8-bit
1456 Any character in the range 80-FF allowed in identifiers, and all are
1457 considered distinct. In other words, there are no uppercase and lowercase
1458 equivalences in this range. This is useful in conjunction with
1459 certain encoding schemes used for some foreign character sets (e.g.,
1460 the typical method of representing Chinese characters on the PC).
1461
1462 @item No Upper-Half
1463 No upper-half characters in the range 80-FF are allowed in identifiers.
1464 This gives Ada 83 compatibility for identifier names.
1465 @end table
1466
1467 @noindent
1468 For precise data on the encodings permitted, and the uppercase and lowercase
1469 equivalences that are recognized, see the file @file{csets.adb} in
1470 the GNAT compiler sources. You will need to obtain a full source release
1471 of GNAT to obtain this file.
1472
1473 @node Wide Character Encodings
1474 @subsection Wide Character Encodings
1475
1476 @noindent
1477 GNAT allows wide character codes to appear in character and string
1478 literals, and also optionally in identifiers, by means of the following
1479 possible encoding schemes:
1480
1481 @table @asis
1482
1483 @item Hex Coding
1484 In this encoding, a wide character is represented by the following five
1485 character sequence:
1486
1487 @smallexample
1488 ESC a b c d
1489 @end smallexample
1490
1491 @noindent
1492 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1493 characters (using uppercase letters) of the wide character code. For
1494 example, ESC A345 is used to represent the wide character with code
1495 @code{16#A345#}.
1496 This scheme is compatible with use of the full Wide_Character set.
1497
1498 @item Upper-Half Coding
1499 @cindex Upper-Half Coding
1500 The wide character with encoding @code{16#abcd#} where the upper bit is on
1501 (in other words, ``a'' is in the range 8-F) is represented as two bytes,
1502 @code{16#ab#} and @code{16#cd#}. The second byte cannot be a format control
1503 character, but is not required to be in the upper half. This method can
1504 be also used for shift-JIS or EUC, where the internal coding matches the
1505 external coding.
1506
1507 @item Shift JIS Coding
1508 @cindex Shift JIS Coding
1509 A wide character is represented by a two-character sequence,
1510 @code{16#ab#} and
1511 @code{16#cd#}, with the restrictions described for upper-half encoding as
1512 described above. The internal character code is the corresponding JIS
1513 character according to the standard algorithm for Shift-JIS
1514 conversion. Only characters defined in the JIS code set table can be
1515 used with this encoding method.
1516
1517 @item EUC Coding
1518 @cindex EUC Coding
1519 A wide character is represented by a two-character sequence
1520 @code{16#ab#} and
1521 @code{16#cd#}, with both characters being in the upper half. The internal
1522 character code is the corresponding JIS character according to the EUC
1523 encoding algorithm. Only characters defined in the JIS code set table
1524 can be used with this encoding method.
1525
1526 @item UTF-8 Coding
1527 A wide character is represented using
1528 UCS Transformation Format 8 (UTF-8) as defined in Annex R of ISO
1529 10646-1/Am.2. Depending on the character value, the representation
1530 is a one, two, or three byte sequence:
1531 @smallexample
1532 @iftex
1533 @leftskip=.7cm
1534 @end iftex
1535 16#0000#-16#007f#: 2#0@var{xxxxxxx}#
1536 16#0080#-16#07ff#: 2#110@var{xxxxx}# 2#10@var{xxxxxx}#
1537 16#0800#-16#ffff#: 2#1110@var{xxxx}# 2#10@var{xxxxxx}# 2#10@var{xxxxxx}#
1538
1539 @end smallexample
1540
1541 @noindent
1542 where the @var{xxx} bits correspond to the left-padded bits of the
1543 16-bit character value. Note that all lower half ASCII characters
1544 are represented as ASCII bytes and all upper half characters and
1545 other wide characters are represented as sequences of upper-half
1546 (The full UTF-8 scheme allows for encoding 31-bit characters as
1547 6-byte sequences, but in this implementation, all UTF-8 sequences
1548 of four or more bytes length will be treated as illegal).
1549 @item Brackets Coding
1550 In this encoding, a wide character is represented by the following eight
1551 character sequence:
1552
1553 @smallexample
1554 [ " a b c d " ]
1555 @end smallexample
1556
1557 @noindent
1558 Where @code{a}, @code{b}, @code{c}, @code{d} are the four hexadecimal
1559 characters (using uppercase letters) of the wide character code. For
1560 example, [``A345''] is used to represent the wide character with code
1561 @code{16#A345#}. It is also possible (though not required) to use the
1562 Brackets coding for upper half characters. For example, the code
1563 @code{16#A3#} can be represented as @code{[``A3'']}.
1564
1565 This scheme is compatible with use of the full Wide_Character set,
1566 and is also the method used for wide character encoding in the standard
1567 ACVC (Ada Compiler Validation Capability) test suite distributions.
1568
1569 @end table
1570
1571 @noindent
1572 Note: Some of these coding schemes do not permit the full use of the
1573 Ada character set. For example, neither Shift JIS, nor EUC allow the
1574 use of the upper half of the Latin-1 set.
1575
1576 @node File Naming Rules
1577 @section File Naming Rules
1578
1579 @noindent
1580 The default file name is determined by the name of the unit that the
1581 file contains. The name is formed by taking the full expanded name of
1582 the unit and replacing the separating dots with hyphens and using
1583 ^lowercase^uppercase^ for all letters.
1584
1585 An exception arises if the file name generated by the above rules starts
1586 with one of the characters
1587 @ifset vms
1588 @samp{A}, @samp{G}, @samp{I}, or @samp{S},
1589 @end ifset
1590 @ifclear vms
1591 @samp{a}, @samp{g}, @samp{i}, or @samp{s},
1592 @end ifclear
1593 and the second character is a
1594 minus. In this case, the character ^tilde^dollar sign^ is used in place
1595 of the minus. The reason for this special rule is to avoid clashes with
1596 the standard names for child units of the packages System, Ada,
1597 Interfaces, and GNAT, which use the prefixes
1598 @ifset vms
1599 @samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},
1600 @end ifset
1601 @ifclear vms
1602 @samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},
1603 @end ifclear
1604 respectively.
1605
1606 The file extension is @file{.ads} for a spec and
1607 @file{.adb} for a body. The following list shows some
1608 examples of these rules.
1609
1610 @table @file
1611 @item main.ads
1612 Main (spec)
1613 @item main.adb
1614 Main (body)
1615 @item arith_functions.ads
1616 Arith_Functions (package spec)
1617 @item arith_functions.adb
1618 Arith_Functions (package body)
1619 @item func-spec.ads
1620 Func.Spec (child package spec)
1621 @item func-spec.adb
1622 Func.Spec (child package body)
1623 @item main-sub.adb
1624 Sub (subunit of Main)
1625 @item ^a~bad.adb^A$BAD.ADB^
1626 A.Bad (child package body)
1627 @end table
1628
1629 @noindent
1630 Following these rules can result in excessively long
1631 file names if corresponding
1632 unit names are long (for example, if child units or subunits are
1633 heavily nested). An option is available to shorten such long file names
1634 (called file name ``krunching''). This may be particularly useful when
1635 programs being developed with GNAT are to be used on operating systems
1636 with limited file name lengths. @xref{Using gnatkr}.
1637
1638 Of course, no file shortening algorithm can guarantee uniqueness over
1639 all possible unit names; if file name krunching is used, it is your
1640 responsibility to ensure no name clashes occur. Alternatively you
1641 can specify the exact file names that you want used, as described
1642 in the next section. Finally, if your Ada programs are migrating from a
1643 compiler with a different naming convention, you can use the gnatchop
1644 utility to produce source files that follow the GNAT naming conventions.
1645 (For details @pxref{Renaming Files with gnatchop}.)
1646
1647 Note: in the case of @code{Windows NT/XP} or @code{OpenVMS} operating
1648 systems, case is not significant. So for example on @code{Windows XP}
1649 if the canonical name is @code{main-sub.adb}, you can use the file name
1650 @code{Main-Sub.adb} instead. However, case is significant for other
1651 operating systems, so for example, if you want to use other than
1652 canonically cased file names on a Unix system, you need to follow
1653 the procedures described in the next section.
1654
1655 @node Using Other File Names
1656 @section Using Other File Names
1657 @cindex File names
1658
1659 @noindent
1660 In the previous section, we have described the default rules used by
1661 GNAT to determine the file name in which a given unit resides. It is
1662 often convenient to follow these default rules, and if you follow them,
1663 the compiler knows without being explicitly told where to find all
1664 the files it needs.
1665
1666 However, in some cases, particularly when a program is imported from
1667 another Ada compiler environment, it may be more convenient for the
1668 programmer to specify which file names contain which units. GNAT allows
1669 arbitrary file names to be used by means of the Source_File_Name pragma.
1670 The form of this pragma is as shown in the following examples:
1671 @cindex Source_File_Name pragma
1672
1673 @smallexample @c ada
1674 @cartouche
1675 pragma Source_File_Name (My_Utilities.Stacks,
1676 Spec_File_Name => "myutilst_a.ada");
1677 pragma Source_File_name (My_Utilities.Stacks,
1678 Body_File_Name => "myutilst.ada");
1679 @end cartouche
1680 @end smallexample
1681
1682 @noindent
1683 As shown in this example, the first argument for the pragma is the unit
1684 name (in this example a child unit). The second argument has the form
1685 of a named association. The identifier
1686 indicates whether the file name is for a spec or a body;
1687 the file name itself is given by a string literal.
1688
1689 The source file name pragma is a configuration pragma, which means that
1690 normally it will be placed in the @file{gnat.adc}
1691 file used to hold configuration
1692 pragmas that apply to a complete compilation environment.
1693 For more details on how the @file{gnat.adc} file is created and used
1694 see @ref{Handling of Configuration Pragmas}.
1695 @cindex @file{gnat.adc}
1696
1697 @ifclear vms
1698 GNAT allows completely arbitrary file names to be specified using the
1699 source file name pragma. However, if the file name specified has an
1700 extension other than @file{.ads} or @file{.adb} it is necessary to use
1701 a special syntax when compiling the file. The name in this case must be
1702 preceded by the special sequence @option{-x} followed by a space and the name
1703 of the language, here @code{ada}, as in:
1704
1705 @smallexample
1706 $ gcc -c -x ada peculiar_file_name.sim
1707 @end smallexample
1708 @end ifclear
1709
1710 @noindent
1711 @command{gnatmake} handles non-standard file names in the usual manner (the
1712 non-standard file name for the main program is simply used as the
1713 argument to gnatmake). Note that if the extension is also non-standard,
1714 then it must be included in the @command{gnatmake} command, it may not
1715 be omitted.
1716
1717 @node Alternative File Naming Schemes
1718 @section Alternative File Naming Schemes
1719 @cindex File naming schemes, alternative
1720 @cindex File names
1721
1722 In the previous section, we described the use of the @code{Source_File_Name}
1723 pragma to allow arbitrary names to be assigned to individual source files.
1724 However, this approach requires one pragma for each file, and especially in
1725 large systems can result in very long @file{gnat.adc} files, and also create
1726 a maintenance problem.
1727
1728 GNAT also provides a facility for specifying systematic file naming schemes
1729 other than the standard default naming scheme previously described. An
1730 alternative scheme for naming is specified by the use of
1731 @code{Source_File_Name} pragmas having the following format:
1732 @cindex Source_File_Name pragma
1733
1734 @smallexample @c ada
1735 pragma Source_File_Name (
1736 Spec_File_Name => FILE_NAME_PATTERN
1737 @r{[},Casing => CASING_SPEC@r{]}
1738 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1739
1740 pragma Source_File_Name (
1741 Body_File_Name => FILE_NAME_PATTERN
1742 @r{[},Casing => CASING_SPEC@r{]}
1743 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1744
1745 pragma Source_File_Name (
1746 Subunit_File_Name => FILE_NAME_PATTERN
1747 @r{[},Casing => CASING_SPEC@r{]}
1748 @r{[},Dot_Replacement => STRING_LITERAL@r{]});
1749
1750 FILE_NAME_PATTERN ::= STRING_LITERAL
1751 CASING_SPEC ::= Lowercase | Uppercase | Mixedcase
1752 @end smallexample
1753
1754 @noindent
1755 The @code{FILE_NAME_PATTERN} string shows how the file name is constructed.
1756 It contains a single asterisk character, and the unit name is substituted
1757 systematically for this asterisk. The optional parameter
1758 @code{Casing} indicates
1759 whether the unit name is to be all upper-case letters, all lower-case letters,
1760 or mixed-case. If no
1761 @code{Casing} parameter is used, then the default is all
1762 ^lower-case^upper-case^.
1763
1764 The optional @code{Dot_Replacement} string is used to replace any periods
1765 that occur in subunit or child unit names. If no @code{Dot_Replacement}
1766 argument is used then separating dots appear unchanged in the resulting
1767 file name.
1768 Although the above syntax indicates that the
1769 @code{Casing} argument must appear
1770 before the @code{Dot_Replacement} argument, but it
1771 is also permissible to write these arguments in the opposite order.
1772
1773 As indicated, it is possible to specify different naming schemes for
1774 bodies, specs, and subunits. Quite often the rule for subunits is the
1775 same as the rule for bodies, in which case, there is no need to give
1776 a separate @code{Subunit_File_Name} rule, and in this case the
1777 @code{Body_File_name} rule is used for subunits as well.
1778
1779 The separate rule for subunits can also be used to implement the rather
1780 unusual case of a compilation environment (e.g.@: a single directory) which
1781 contains a subunit and a child unit with the same unit name. Although
1782 both units cannot appear in the same partition, the Ada Reference Manual
1783 allows (but does not require) the possibility of the two units coexisting
1784 in the same environment.
1785
1786 The file name translation works in the following steps:
1787
1788 @itemize @bullet
1789
1790 @item
1791 If there is a specific @code{Source_File_Name} pragma for the given unit,
1792 then this is always used, and any general pattern rules are ignored.
1793
1794 @item
1795 If there is a pattern type @code{Source_File_Name} pragma that applies to
1796 the unit, then the resulting file name will be used if the file exists. If
1797 more than one pattern matches, the latest one will be tried first, and the
1798 first attempt resulting in a reference to a file that exists will be used.
1799
1800 @item
1801 If no pattern type @code{Source_File_Name} pragma that applies to the unit
1802 for which the corresponding file exists, then the standard GNAT default
1803 naming rules are used.
1804
1805 @end itemize
1806
1807 @noindent
1808 As an example of the use of this mechanism, consider a commonly used scheme
1809 in which file names are all lower case, with separating periods copied
1810 unchanged to the resulting file name, and specs end with @file{.1.ada}, and
1811 bodies end with @file{.2.ada}. GNAT will follow this scheme if the following
1812 two pragmas appear:
1813
1814 @smallexample @c ada
1815 pragma Source_File_Name
1816 (Spec_File_Name => "*.1.ada");
1817 pragma Source_File_Name
1818 (Body_File_Name => "*.2.ada");
1819 @end smallexample
1820
1821 @noindent
1822 The default GNAT scheme is actually implemented by providing the following
1823 default pragmas internally:
1824
1825 @smallexample @c ada
1826 pragma Source_File_Name
1827 (Spec_File_Name => "*.ads", Dot_Replacement => "-");
1828 pragma Source_File_Name
1829 (Body_File_Name => "*.adb", Dot_Replacement => "-");
1830 @end smallexample
1831
1832 @noindent
1833 Our final example implements a scheme typically used with one of the
1834 Ada 83 compilers, where the separator character for subunits was ``__''
1835 (two underscores), specs were identified by adding @file{_.ADA}, bodies
1836 by adding @file{.ADA}, and subunits by
1837 adding @file{.SEP}. All file names were
1838 upper case. Child units were not present of course since this was an
1839 Ada 83 compiler, but it seems reasonable to extend this scheme to use
1840 the same double underscore separator for child units.
1841
1842 @smallexample @c ada
1843 pragma Source_File_Name
1844 (Spec_File_Name => "*_.ADA",
1845 Dot_Replacement => "__",
1846 Casing = Uppercase);
1847 pragma Source_File_Name
1848 (Body_File_Name => "*.ADA",
1849 Dot_Replacement => "__",
1850 Casing = Uppercase);
1851 pragma Source_File_Name
1852 (Subunit_File_Name => "*.SEP",
1853 Dot_Replacement => "__",
1854 Casing = Uppercase);
1855 @end smallexample
1856
1857 @node Generating Object Files
1858 @section Generating Object Files
1859
1860 @noindent
1861 An Ada program consists of a set of source files, and the first step in
1862 compiling the program is to generate the corresponding object files.
1863 These are generated by compiling a subset of these source files.
1864 The files you need to compile are the following:
1865
1866 @itemize @bullet
1867 @item
1868 If a package spec has no body, compile the package spec to produce the
1869 object file for the package.
1870
1871 @item
1872 If a package has both a spec and a body, compile the body to produce the
1873 object file for the package. The source file for the package spec need
1874 not be compiled in this case because there is only one object file, which
1875 contains the code for both the spec and body of the package.
1876
1877 @item
1878 For a subprogram, compile the subprogram body to produce the object file
1879 for the subprogram. The spec, if one is present, is as usual in a
1880 separate file, and need not be compiled.
1881
1882 @item
1883 @cindex Subunits
1884 In the case of subunits, only compile the parent unit. A single object
1885 file is generated for the entire subunit tree, which includes all the
1886 subunits.
1887
1888 @item
1889 Compile child units independently of their parent units
1890 (though, of course, the spec of all the ancestor unit must be present in order
1891 to compile a child unit).
1892
1893 @item
1894 @cindex Generics
1895 Compile generic units in the same manner as any other units. The object
1896 files in this case are small dummy files that contain at most the
1897 flag used for elaboration checking. This is because GNAT always handles generic
1898 instantiation by means of macro expansion. However, it is still necessary to
1899 compile generic units, for dependency checking and elaboration purposes.
1900 @end itemize
1901
1902 @noindent
1903 The preceding rules describe the set of files that must be compiled to
1904 generate the object files for a program. Each object file has the same
1905 name as the corresponding source file, except that the extension is
1906 @file{.o} as usual.
1907
1908 You may wish to compile other files for the purpose of checking their
1909 syntactic and semantic correctness. For example, in the case where a
1910 package has a separate spec and body, you would not normally compile the
1911 spec. However, it is convenient in practice to compile the spec to make
1912 sure it is error-free before compiling clients of this spec, because such
1913 compilations will fail if there is an error in the spec.
1914
1915 GNAT provides an option for compiling such files purely for the
1916 purposes of checking correctness; such compilations are not required as
1917 part of the process of building a program. To compile a file in this
1918 checking mode, use the @option{-gnatc} switch.
1919
1920 @node Source Dependencies
1921 @section Source Dependencies
1922
1923 @noindent
1924 A given object file clearly depends on the source file which is compiled
1925 to produce it. Here we are using @dfn{depends} in the sense of a typical
1926 @code{make} utility; in other words, an object file depends on a source
1927 file if changes to the source file require the object file to be
1928 recompiled.
1929 In addition to this basic dependency, a given object may depend on
1930 additional source files as follows:
1931
1932 @itemize @bullet
1933 @item
1934 If a file being compiled @code{with}'s a unit @var{X}, the object file
1935 depends on the file containing the spec of unit @var{X}. This includes
1936 files that are @code{with}'ed implicitly either because they are parents
1937 of @code{with}'ed child units or they are run-time units required by the
1938 language constructs used in a particular unit.
1939
1940 @item
1941 If a file being compiled instantiates a library level generic unit, the
1942 object file depends on both the spec and body files for this generic
1943 unit.
1944
1945 @item
1946 If a file being compiled instantiates a generic unit defined within a
1947 package, the object file depends on the body file for the package as
1948 well as the spec file.
1949
1950 @item
1951 @findex Inline
1952 @cindex @option{-gnatn} switch
1953 If a file being compiled contains a call to a subprogram for which
1954 pragma @code{Inline} applies and inlining is activated with the
1955 @option{-gnatn} switch, the object file depends on the file containing the
1956 body of this subprogram as well as on the file containing the spec. Note
1957 that for inlining to actually occur as a result of the use of this switch,
1958 it is necessary to compile in optimizing mode.
1959
1960 @cindex @option{-gnatN} switch
1961 The use of @option{-gnatN} activates inlining optimization
1962 that is performed by the front end of the compiler. This inlining does
1963 not require that the code generation be optimized. Like @option{-gnatn},
1964 the use of this switch generates additional dependencies.
1965
1966 When using a gcc-based back end (in practice this means using any version
1967 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
1968 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
1969 Historically front end inlining was more extensive than the gcc back end
1970 inlining, but that is no longer the case.
1971
1972 @item
1973 If an object file @file{O} depends on the proper body of a subunit through
1974 inlining or instantiation, it depends on the parent unit of the subunit.
1975 This means that any modification of the parent unit or one of its subunits
1976 affects the compilation of @file{O}.
1977
1978 @item
1979 The object file for a parent unit depends on all its subunit body files.
1980
1981 @item
1982 The previous two rules meant that for purposes of computing dependencies and
1983 recompilation, a body and all its subunits are treated as an indivisible whole.
1984
1985 @noindent
1986 These rules are applied transitively: if unit @code{A} @code{with}'s
1987 unit @code{B}, whose elaboration calls an inlined procedure in package
1988 @code{C}, the object file for unit @code{A} will depend on the body of
1989 @code{C}, in file @file{c.adb}.
1990
1991 The set of dependent files described by these rules includes all the
1992 files on which the unit is semantically dependent, as dictated by the
1993 Ada language standard. However, it is a superset of what the
1994 standard describes, because it includes generic, inline, and subunit
1995 dependencies.
1996
1997 An object file must be recreated by recompiling the corresponding source
1998 file if any of the source files on which it depends are modified. For
1999 example, if the @code{make} utility is used to control compilation,
2000 the rule for an Ada object file must mention all the source files on
2001 which the object file depends, according to the above definition.
2002 The determination of the necessary
2003 recompilations is done automatically when one uses @command{gnatmake}.
2004 @end itemize
2005
2006 @node The Ada Library Information Files
2007 @section The Ada Library Information Files
2008 @cindex Ada Library Information files
2009 @cindex @file{ALI} files
2010
2011 @noindent
2012 Each compilation actually generates two output files. The first of these
2013 is the normal object file that has a @file{.o} extension. The second is a
2014 text file containing full dependency information. It has the same
2015 name as the source file, but an @file{.ali} extension.
2016 This file is known as the Ada Library Information (@file{ALI}) file.
2017 The following information is contained in the @file{ALI} file.
2018
2019 @itemize @bullet
2020 @item
2021 Version information (indicates which version of GNAT was used to compile
2022 the unit(s) in question)
2023
2024 @item
2025 Main program information (including priority and time slice settings,
2026 as well as the wide character encoding used during compilation).
2027
2028 @item
2029 List of arguments used in the @command{gcc} command for the compilation
2030
2031 @item
2032 Attributes of the unit, including configuration pragmas used, an indication
2033 of whether the compilation was successful, exception model used etc.
2034
2035 @item
2036 A list of relevant restrictions applying to the unit (used for consistency)
2037 checking.
2038
2039 @item
2040 Categorization information (e.g.@: use of pragma @code{Pure}).
2041
2042 @item
2043 Information on all @code{with}'ed units, including presence of
2044 @code{Elaborate} or @code{Elaborate_All} pragmas.
2045
2046 @item
2047 Information from any @code{Linker_Options} pragmas used in the unit
2048
2049 @item
2050 Information on the use of @code{Body_Version} or @code{Version}
2051 attributes in the unit.
2052
2053 @item
2054 Dependency information. This is a list of files, together with
2055 time stamp and checksum information. These are files on which
2056 the unit depends in the sense that recompilation is required
2057 if any of these units are modified.
2058
2059 @item
2060 Cross-reference data. Contains information on all entities referenced
2061 in the unit. Used by tools like @code{gnatxref} and @code{gnatfind} to
2062 provide cross-reference information.
2063
2064 @end itemize
2065
2066 @noindent
2067 For a full detailed description of the format of the @file{ALI} file,
2068 see the source of the body of unit @code{Lib.Writ}, contained in file
2069 @file{lib-writ.adb} in the GNAT compiler sources.
2070
2071 @node Binding an Ada Program
2072 @section Binding an Ada Program
2073
2074 @noindent
2075 When using languages such as C and C++, once the source files have been
2076 compiled the only remaining step in building an executable program
2077 is linking the object modules together. This means that it is possible to
2078 link an inconsistent version of a program, in which two units have
2079 included different versions of the same header.
2080
2081 The rules of Ada do not permit such an inconsistent program to be built.
2082 For example, if two clients have different versions of the same package,
2083 it is illegal to build a program containing these two clients.
2084 These rules are enforced by the GNAT binder, which also determines an
2085 elaboration order consistent with the Ada rules.
2086
2087 The GNAT binder is run after all the object files for a program have
2088 been created. It is given the name of the main program unit, and from
2089 this it determines the set of units required by the program, by reading the
2090 corresponding ALI files. It generates error messages if the program is
2091 inconsistent or if no valid order of elaboration exists.
2092
2093 If no errors are detected, the binder produces a main program, in Ada by
2094 default, that contains calls to the elaboration procedures of those
2095 compilation unit that require them, followed by
2096 a call to the main program. This Ada program is compiled to generate the
2097 object file for the main program. The name of
2098 the Ada file is @file{b~@var{xxx}.adb} (with the corresponding spec
2099 @file{b~@var{xxx}.ads}) where @var{xxx} is the name of the
2100 main program unit.
2101
2102 Finally, the linker is used to build the resulting executable program,
2103 using the object from the main program from the bind step as well as the
2104 object files for the Ada units of the program.
2105
2106 @node Mixed Language Programming
2107 @section Mixed Language Programming
2108 @cindex Mixed Language Programming
2109
2110 @noindent
2111 This section describes how to develop a mixed-language program,
2112 specifically one that comprises units in both Ada and C.
2113
2114 @menu
2115 * Interfacing to C::
2116 * Calling Conventions::
2117 @end menu
2118
2119 @node Interfacing to C
2120 @subsection Interfacing to C
2121 @noindent
2122 Interfacing Ada with a foreign language such as C involves using
2123 compiler directives to import and/or export entity definitions in each
2124 language---using @code{extern} statements in C, for instance, and the
2125 @code{Import}, @code{Export}, and @code{Convention} pragmas in Ada.
2126 A full treatment of these topics is provided in Appendix B, section 1
2127 of the Ada Reference Manual.
2128
2129 There are two ways to build a program using GNAT that contains some Ada
2130 sources and some foreign language sources, depending on whether or not
2131 the main subprogram is written in Ada. Here is a source example with
2132 the main subprogram in Ada:
2133
2134 @smallexample
2135 /* file1.c */
2136 #include <stdio.h>
2137
2138 void print_num (int num)
2139 @{
2140 printf ("num is %d.\n", num);
2141 return;
2142 @}
2143
2144 /* file2.c */
2145
2146 /* num_from_Ada is declared in my_main.adb */
2147 extern int num_from_Ada;
2148
2149 int get_num (void)
2150 @{
2151 return num_from_Ada;
2152 @}
2153 @end smallexample
2154
2155 @smallexample @c ada
2156 -- my_main.adb
2157 procedure My_Main is
2158
2159 -- Declare then export an Integer entity called num_from_Ada
2160 My_Num : Integer := 10;
2161 pragma Export (C, My_Num, "num_from_Ada");
2162
2163 -- Declare an Ada function spec for Get_Num, then use
2164 -- C function get_num for the implementation.
2165 function Get_Num return Integer;
2166 pragma Import (C, Get_Num, "get_num");
2167
2168 -- Declare an Ada procedure spec for Print_Num, then use
2169 -- C function print_num for the implementation.
2170 procedure Print_Num (Num : Integer);
2171 pragma Import (C, Print_Num, "print_num");
2172
2173 begin
2174 Print_Num (Get_Num);
2175 end My_Main;
2176 @end smallexample
2177
2178 @enumerate
2179 @item
2180 To build this example, first compile the foreign language files to
2181 generate object files:
2182 @smallexample
2183 ^gcc -c file1.c^gcc -c FILE1.C^
2184 ^gcc -c file2.c^gcc -c FILE2.C^
2185 @end smallexample
2186
2187 @item
2188 Then, compile the Ada units to produce a set of object files and ALI
2189 files:
2190 @smallexample
2191 gnatmake ^-c^/ACTIONS=COMPILE^ my_main.adb
2192 @end smallexample
2193
2194 @item
2195 Run the Ada binder on the Ada main program:
2196 @smallexample
2197 gnatbind my_main.ali
2198 @end smallexample
2199
2200 @item
2201 Link the Ada main program, the Ada objects and the other language
2202 objects:
2203 @smallexample
2204 gnatlink my_main.ali file1.o file2.o
2205 @end smallexample
2206 @end enumerate
2207
2208 The last three steps can be grouped in a single command:
2209 @smallexample
2210 gnatmake my_main.adb -largs file1.o file2.o
2211 @end smallexample
2212
2213 @cindex Binder output file
2214 @noindent
2215 If the main program is in a language other than Ada, then you may have
2216 more than one entry point into the Ada subsystem. You must use a special
2217 binder option to generate callable routines that initialize and
2218 finalize the Ada units (@pxref{Binding with Non-Ada Main Programs}).
2219 Calls to the initialization and finalization routines must be inserted
2220 in the main program, or some other appropriate point in the code. The
2221 call to initialize the Ada units must occur before the first Ada
2222 subprogram is called, and the call to finalize the Ada units must occur
2223 after the last Ada subprogram returns. The binder will place the
2224 initialization and finalization subprograms into the
2225 @file{b~@var{xxx}.adb} file where they can be accessed by your C
2226 sources. To illustrate, we have the following example:
2227
2228 @smallexample
2229 /* main.c */
2230 extern void adainit (void);
2231 extern void adafinal (void);
2232 extern int add (int, int);
2233 extern int sub (int, int);
2234
2235 int main (int argc, char *argv[])
2236 @{
2237 int a = 21, b = 7;
2238
2239 adainit();
2240
2241 /* Should print "21 + 7 = 28" */
2242 printf ("%d + %d = %d\n", a, b, add (a, b));
2243 /* Should print "21 - 7 = 14" */
2244 printf ("%d - %d = %d\n", a, b, sub (a, b));
2245
2246 adafinal();
2247 @}
2248 @end smallexample
2249
2250 @smallexample @c ada
2251 -- unit1.ads
2252 package Unit1 is
2253 function Add (A, B : Integer) return Integer;
2254 pragma Export (C, Add, "add");
2255 end Unit1;
2256
2257 -- unit1.adb
2258 package body Unit1 is
2259 function Add (A, B : Integer) return Integer is
2260 begin
2261 return A + B;
2262 end Add;
2263 end Unit1;
2264
2265 -- unit2.ads
2266 package Unit2 is
2267 function Sub (A, B : Integer) return Integer;
2268 pragma Export (C, Sub, "sub");
2269 end Unit2;
2270
2271 -- unit2.adb
2272 package body Unit2 is
2273 function Sub (A, B : Integer) return Integer is
2274 begin
2275 return A - B;
2276 end Sub;
2277 end Unit2;
2278 @end smallexample
2279
2280 @enumerate
2281 @item
2282 The build procedure for this application is similar to the last
2283 example's. First, compile the foreign language files to generate object
2284 files:
2285 @smallexample
2286 ^gcc -c main.c^gcc -c main.c^
2287 @end smallexample
2288
2289 @item
2290 Next, compile the Ada units to produce a set of object files and ALI
2291 files:
2292 @smallexample
2293 gnatmake ^-c^/ACTIONS=COMPILE^ unit1.adb
2294 gnatmake ^-c^/ACTIONS=COMPILE^ unit2.adb
2295 @end smallexample
2296
2297 @item
2298 Run the Ada binder on every generated ALI file. Make sure to use the
2299 @option{-n} option to specify a foreign main program:
2300 @smallexample
2301 gnatbind ^-n^/NOMAIN^ unit1.ali unit2.ali
2302 @end smallexample
2303
2304 @item
2305 Link the Ada main program, the Ada objects and the foreign language
2306 objects. You need only list the last ALI file here:
2307 @smallexample
2308 gnatlink unit2.ali main.o -o exec_file
2309 @end smallexample
2310
2311 This procedure yields a binary executable called @file{exec_file}.
2312 @end enumerate
2313
2314 @noindent
2315 Depending on the circumstances (for example when your non-Ada main object
2316 does not provide symbol @code{main}), you may also need to instruct the
2317 GNAT linker not to include the standard startup objects by passing the
2318 @option{^-nostartfiles^/NOSTART_FILES^} switch to @command{gnatlink}.
2319
2320 @node Calling Conventions
2321 @subsection Calling Conventions
2322 @cindex Foreign Languages
2323 @cindex Calling Conventions
2324 GNAT follows standard calling sequence conventions and will thus interface
2325 to any other language that also follows these conventions. The following
2326 Convention identifiers are recognized by GNAT:
2327
2328 @table @code
2329 @cindex Interfacing to Ada
2330 @cindex Other Ada compilers
2331 @cindex Convention Ada
2332 @item Ada
2333 This indicates that the standard Ada calling sequence will be
2334 used and all Ada data items may be passed without any limitations in the
2335 case where GNAT is used to generate both the caller and callee. It is also
2336 possible to mix GNAT generated code and code generated by another Ada
2337 compiler. In this case, the data types should be restricted to simple
2338 cases, including primitive types. Whether complex data types can be passed
2339 depends on the situation. Probably it is safe to pass simple arrays, such
2340 as arrays of integers or floats. Records may or may not work, depending
2341 on whether both compilers lay them out identically. Complex structures
2342 involving variant records, access parameters, tasks, or protected types,
2343 are unlikely to be able to be passed.
2344
2345 Note that in the case of GNAT running
2346 on a platform that supports HP Ada 83, a higher degree of compatibility
2347 can be guaranteed, and in particular records are laid out in an identical
2348 manner in the two compilers. Note also that if output from two different
2349 compilers is mixed, the program is responsible for dealing with elaboration
2350 issues. Probably the safest approach is to write the main program in the
2351 version of Ada other than GNAT, so that it takes care of its own elaboration
2352 requirements, and then call the GNAT-generated adainit procedure to ensure
2353 elaboration of the GNAT components. Consult the documentation of the other
2354 Ada compiler for further details on elaboration.
2355
2356 However, it is not possible to mix the tasking run time of GNAT and
2357 HP Ada 83, All the tasking operations must either be entirely within
2358 GNAT compiled sections of the program, or entirely within HP Ada 83
2359 compiled sections of the program.
2360
2361 @cindex Interfacing to Assembly
2362 @cindex Convention Assembler
2363 @item Assembler
2364 Specifies assembler as the convention. In practice this has the
2365 same effect as convention Ada (but is not equivalent in the sense of being
2366 considered the same convention).
2367
2368 @cindex Convention Asm
2369 @findex Asm
2370 @item Asm
2371 Equivalent to Assembler.
2372
2373 @cindex Interfacing to COBOL
2374 @cindex Convention COBOL
2375 @findex COBOL
2376 @item COBOL
2377 Data will be passed according to the conventions described
2378 in section B.4 of the Ada Reference Manual.
2379
2380 @findex C
2381 @cindex Interfacing to C
2382 @cindex Convention C
2383 @item C
2384 Data will be passed according to the conventions described
2385 in section B.3 of the Ada Reference Manual.
2386
2387 A note on interfacing to a C ``varargs'' function:
2388 @findex C varargs function
2389 @cindex Interfacing to C varargs function
2390 @cindex varargs function interfaces
2391
2392 @itemize @bullet
2393 @item
2394 In C, @code{varargs} allows a function to take a variable number of
2395 arguments. There is no direct equivalent in this to Ada. One
2396 approach that can be used is to create a C wrapper for each
2397 different profile and then interface to this C wrapper. For
2398 example, to print an @code{int} value using @code{printf},
2399 create a C function @code{printfi} that takes two arguments, a
2400 pointer to a string and an int, and calls @code{printf}.
2401 Then in the Ada program, use pragma @code{Import} to
2402 interface to @code{printfi}.
2403
2404 @item
2405 It may work on some platforms to directly interface to
2406 a @code{varargs} function by providing a specific Ada profile
2407 for a particular call. However, this does not work on
2408 all platforms, since there is no guarantee that the
2409 calling sequence for a two argument normal C function
2410 is the same as for calling a @code{varargs} C function with
2411 the same two arguments.
2412 @end itemize
2413
2414 @cindex Convention Default
2415 @findex Default
2416 @item Default
2417 Equivalent to C.
2418
2419 @cindex Convention External
2420 @findex External
2421 @item External
2422 Equivalent to C.
2423
2424 @ifclear vms
2425 @findex C++
2426 @cindex Interfacing to C++
2427 @cindex Convention C++
2428 @item C_Plus_Plus (or CPP)
2429 This stands for C++. For most purposes this is identical to C.
2430 See the separate description of the specialized GNAT pragmas relating to
2431 C++ interfacing for further details.
2432 @end ifclear
2433
2434 @findex Fortran
2435 @cindex Interfacing to Fortran
2436 @cindex Convention Fortran
2437 @item Fortran
2438 Data will be passed according to the conventions described
2439 in section B.5 of the Ada Reference Manual.
2440
2441 @item Intrinsic
2442 This applies to an intrinsic operation, as defined in the Ada
2443 Reference Manual. If a pragma Import (Intrinsic) applies to a subprogram,
2444 this means that the body of the subprogram is provided by the compiler itself,
2445 usually by means of an efficient code sequence, and that the user does not
2446 supply an explicit body for it. In an application program, the pragma may
2447 be applied to the following sets of names:
2448
2449 @itemize @bullet
2450 @item
2451 Rotate_Left, Rotate_Right, Shift_Left, Shift_Right,
2452 Shift_Right_Arithmetic. The corresponding subprogram declaration must have
2453 two formal parameters. The
2454 first one must be a signed integer type or a modular type with a binary
2455 modulus, and the second parameter must be of type Natural.
2456 The return type must be the same as the type of the first argument. The size
2457 of this type can only be 8, 16, 32, or 64.
2458
2459 @item
2460 Binary arithmetic operators: ``+'', ``-'', ``*'', ``/''
2461 The corresponding operator declaration must have parameters and result type
2462 that have the same root numeric type (for example, all three are long_float
2463 types). This simplifies the definition of operations that use type checking
2464 to perform dimensional checks:
2465
2466 @smallexample @c ada
2467 type Distance is new Long_Float;
2468 type Time is new Long_Float;
2469 type Velocity is new Long_Float;
2470 function "/" (D : Distance; T : Time)
2471 return Velocity;
2472 pragma Import (Intrinsic, "/");
2473 @end smallexample
2474
2475 @noindent
2476 This common idiom is often programmed with a generic definition and an
2477 explicit body. The pragma makes it simpler to introduce such declarations.
2478 It incurs no overhead in compilation time or code size, because it is
2479 implemented as a single machine instruction.
2480
2481 @item
2482 General subprogram entities, to bind an Ada subprogram declaration to
2483 a compiler builtin by name with back-ends where such interfaces are
2484 available. A typical example is the set of ``__builtin'' functions
2485 exposed by the GCC back-end, as in the following example:
2486
2487 @smallexample @c ada
2488 function builtin_sqrt (F : Float) return Float;
2489 pragma Import (Intrinsic, builtin_sqrt, "__builtin_sqrtf");
2490 @end smallexample
2491
2492 Most of the GCC builtins are accessible this way, and as for other
2493 import conventions (e.g. C), it is the user's responsibility to ensure
2494 that the Ada subprogram profile matches the underlying builtin
2495 expectations.
2496 @end itemize
2497
2498 @noindent
2499
2500 @ifset unw
2501 @findex Stdcall
2502 @cindex Convention Stdcall
2503 @item Stdcall
2504 This is relevant only to Windows XP/2000/NT implementations of GNAT,
2505 and specifies that the @code{Stdcall} calling sequence will be used,
2506 as defined by the NT API. Nevertheless, to ease building
2507 cross-platform bindings this convention will be handled as a @code{C} calling
2508 convention on non-Windows platforms.
2509
2510 @findex DLL
2511 @cindex Convention DLL
2512 @item DLL
2513 This is equivalent to @code{Stdcall}.
2514
2515 @findex Win32
2516 @cindex Convention Win32
2517 @item Win32
2518 This is equivalent to @code{Stdcall}.
2519 @end ifset
2520
2521 @findex Stubbed
2522 @cindex Convention Stubbed
2523 @item Stubbed
2524 This is a special convention that indicates that the compiler
2525 should provide a stub body that raises @code{Program_Error}.
2526 @end table
2527
2528 @noindent
2529 GNAT additionally provides a useful pragma @code{Convention_Identifier}
2530 that can be used to parameterize conventions and allow additional synonyms
2531 to be specified. For example if you have legacy code in which the convention
2532 identifier Fortran77 was used for Fortran, you can use the configuration
2533 pragma:
2534
2535 @smallexample @c ada
2536 pragma Convention_Identifier (Fortran77, Fortran);
2537 @end smallexample
2538
2539 @noindent
2540 And from now on the identifier Fortran77 may be used as a convention
2541 identifier (for example in an @code{Import} pragma) with the same
2542 meaning as Fortran.
2543
2544 @ifclear vms
2545 @node Building Mixed Ada & C++ Programs
2546 @section Building Mixed Ada and C++ Programs
2547
2548 @noindent
2549 A programmer inexperienced with mixed-language development may find that
2550 building an application containing both Ada and C++ code can be a
2551 challenge. This section gives a few
2552 hints that should make this task easier. The first section addresses
2553 the differences between interfacing with C and interfacing with C++.
2554 The second section
2555 looks into the delicate problem of linking the complete application from
2556 its Ada and C++ parts. The last section gives some hints on how the GNAT
2557 run-time library can be adapted in order to allow inter-language dispatching
2558 with a new C++ compiler.
2559
2560 @menu
2561 * Interfacing to C++::
2562 * Linking a Mixed C++ & Ada Program::
2563 * A Simple Example::
2564 * Interfacing with C++ constructors::
2565 * Interfacing with C++ at the Class Level::
2566 @end menu
2567
2568 @node Interfacing to C++
2569 @subsection Interfacing to C++
2570
2571 @noindent
2572 GNAT supports interfacing with the G++ compiler (or any C++ compiler
2573 generating code that is compatible with the G++ Application Binary
2574 Interface ---see http://www.codesourcery.com/archives/cxx-abi).
2575
2576 @noindent
2577 Interfacing can be done at 3 levels: simple data, subprograms, and
2578 classes. In the first two cases, GNAT offers a specific @code{Convention
2579 C_Plus_Plus} (or @code{CPP}) that behaves exactly like @code{Convention C}.
2580 Usually, C++ mangles the names of subprograms. To generate proper mangled
2581 names automatically, see @ref{Generating Ada Bindings for C and C++ headers}).
2582 This problem can also be addressed manually in two ways:
2583
2584 @itemize @bullet
2585 @item
2586 by modifying the C++ code in order to force a C convention using
2587 the @code{extern "C"} syntax.
2588
2589 @item
2590 by figuring out the mangled name (using e.g. @command{nm}) and using it as the
2591 Link_Name argument of the pragma import.
2592 @end itemize
2593
2594 @noindent
2595 Interfacing at the class level can be achieved by using the GNAT specific
2596 pragmas such as @code{CPP_Constructor}. @xref{Interfacing to C++,,,
2597 gnat_rm, GNAT Reference Manual}, for additional information.
2598
2599 @node Linking a Mixed C++ & Ada Program
2600 @subsection Linking a Mixed C++ & Ada Program
2601
2602 @noindent
2603 Usually the linker of the C++ development system must be used to link
2604 mixed applications because most C++ systems will resolve elaboration
2605 issues (such as calling constructors on global class instances)
2606 transparently during the link phase. GNAT has been adapted to ease the
2607 use of a foreign linker for the last phase. Three cases can be
2608 considered:
2609 @enumerate
2610
2611 @item
2612 Using GNAT and G++ (GNU C++ compiler) from the same GCC installation:
2613 The C++ linker can simply be called by using the C++ specific driver
2614 called @code{g++}.
2615
2616 Note that if the C++ code uses inline functions, you will need to
2617 compile your C++ code with the @code{-fkeep-inline-functions} switch in
2618 order to provide an existing function implementation that the Ada code can
2619 link with.
2620
2621 @smallexample
2622 $ g++ -c -fkeep-inline-functions file1.C
2623 $ g++ -c -fkeep-inline-functions file2.C
2624 $ gnatmake ada_unit -largs file1.o file2.o --LINK=g++
2625 @end smallexample
2626
2627 @item
2628 Using GNAT and G++ from two different GCC installations: If both
2629 compilers are on the @env{PATH}, the previous method may be used. It is
2630 important to note that environment variables such as
2631 @env{C_INCLUDE_PATH}, @env{GCC_EXEC_PREFIX}, @env{BINUTILS_ROOT}, and
2632 @env{GCC_ROOT} will affect both compilers
2633 at the same time and may make one of the two compilers operate
2634 improperly if set during invocation of the wrong compiler. It is also
2635 very important that the linker uses the proper @file{libgcc.a} GCC
2636 library -- that is, the one from the C++ compiler installation. The
2637 implicit link command as suggested in the @command{gnatmake} command
2638 from the former example can be replaced by an explicit link command with
2639 the full-verbosity option in order to verify which library is used:
2640 @smallexample
2641 $ gnatbind ada_unit
2642 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=c++
2643 @end smallexample
2644 If there is a problem due to interfering environment variables, it can
2645 be worked around by using an intermediate script. The following example
2646 shows the proper script to use when GNAT has not been installed at its
2647 default location and g++ has been installed at its default location:
2648
2649 @smallexample
2650 $ cat ./my_script
2651 #!/bin/sh
2652 unset BINUTILS_ROOT
2653 unset GCC_ROOT
2654 c++ $*
2655 $ gnatlink -v -v ada_unit file1.o file2.o --LINK=./my_script
2656 @end smallexample
2657
2658 @item
2659 Using a non-GNU C++ compiler: The commands previously described can be
2660 used to insure that the C++ linker is used. Nonetheless, you need to add
2661 a few more parameters to the link command line, depending on the exception
2662 mechanism used.
2663
2664 If the @code{setjmp/longjmp} exception mechanism is used, only the paths
2665 to the libgcc libraries are required:
2666
2667 @smallexample
2668 $ cat ./my_script
2669 #!/bin/sh
2670 CC $* `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a`
2671 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2672 @end smallexample
2673
2674 Where CC is the name of the non-GNU C++ compiler.
2675
2676 If the @code{zero cost} exception mechanism is used, and the platform
2677 supports automatic registration of exception tables (e.g.@: Solaris),
2678 paths to more objects are required:
2679
2680 @smallexample
2681 $ cat ./my_script
2682 #!/bin/sh
2683 CC `gcc -print-file-name=crtbegin.o` $* \
2684 `gcc -print-file-name=libgcc.a` `gcc -print-file-name=libgcc_eh.a` \
2685 `gcc -print-file-name=crtend.o`
2686 $ gnatlink ada_unit file1.o file2.o --LINK=./my_script
2687 @end smallexample
2688
2689 If the @code{zero cost} exception mechanism is used, and the platform
2690 doesn't support automatic registration of exception tables (e.g.@: HP-UX
2691 or AIX), the simple approach described above will not work and
2692 a pre-linking phase using GNAT will be necessary.
2693
2694 @end enumerate
2695
2696 Another alternative is to use the @command{gprbuild} multi-language builder
2697 which has a large knowledge base and knows how to link Ada and C++ code
2698 together automatically in most cases.
2699
2700 @node A Simple Example
2701 @subsection A Simple Example
2702 @noindent
2703 The following example, provided as part of the GNAT examples, shows how
2704 to achieve procedural interfacing between Ada and C++ in both
2705 directions. The C++ class A has two methods. The first method is exported
2706 to Ada by the means of an extern C wrapper function. The second method
2707 calls an Ada subprogram. On the Ada side, The C++ calls are modelled by
2708 a limited record with a layout comparable to the C++ class. The Ada
2709 subprogram, in turn, calls the C++ method. So, starting from the C++
2710 main program, the process passes back and forth between the two
2711 languages.
2712
2713 @noindent
2714 Here are the compilation commands:
2715 @smallexample
2716 $ gnatmake -c simple_cpp_interface
2717 $ g++ -c cpp_main.C
2718 $ g++ -c ex7.C
2719 $ gnatbind -n simple_cpp_interface
2720 $ gnatlink simple_cpp_interface -o cpp_main --LINK=g++
2721 -lstdc++ ex7.o cpp_main.o
2722 @end smallexample
2723
2724 @noindent
2725 Here are the corresponding sources:
2726 @smallexample
2727
2728 //cpp_main.C
2729
2730 #include "ex7.h"
2731
2732 extern "C" @{
2733 void adainit (void);
2734 void adafinal (void);
2735 void method1 (A *t);
2736 @}
2737
2738 void method1 (A *t)
2739 @{
2740 t->method1 ();
2741 @}
2742
2743 int main ()
2744 @{
2745 A obj;
2746 adainit ();
2747 obj.method2 (3030);
2748 adafinal ();
2749 @}
2750
2751 //ex7.h
2752
2753 class Origin @{
2754 public:
2755 int o_value;
2756 @};
2757 class A : public Origin @{
2758 public:
2759 void method1 (void);
2760 void method2 (int v);
2761 A();
2762 int a_value;
2763 @};
2764
2765 //ex7.C
2766
2767 #include "ex7.h"
2768 #include <stdio.h>
2769
2770 extern "C" @{ void ada_method2 (A *t, int v);@}
2771
2772 void A::method1 (void)
2773 @{
2774 a_value = 2020;
2775 printf ("in A::method1, a_value = %d \n",a_value);
2776
2777 @}
2778
2779 void A::method2 (int v)
2780 @{
2781 ada_method2 (this, v);
2782 printf ("in A::method2, a_value = %d \n",a_value);
2783
2784 @}
2785
2786 A::A(void)
2787 @{
2788 a_value = 1010;
2789 printf ("in A::A, a_value = %d \n",a_value);
2790 @}
2791 @end smallexample
2792
2793 @smallexample @c ada
2794 -- Ada sources
2795 package body Simple_Cpp_Interface is
2796
2797 procedure Ada_Method2 (This : in out A; V : Integer) is
2798 begin
2799 Method1 (This);
2800 This.A_Value := V;
2801 end Ada_Method2;
2802
2803 end Simple_Cpp_Interface;
2804
2805 with System;
2806 package Simple_Cpp_Interface is
2807 type A is limited
2808 record
2809 Vptr : System.Address;
2810 O_Value : Integer;
2811 A_Value : Integer;
2812 end record;
2813 pragma Convention (C, A);
2814
2815 procedure Method1 (This : in out A);
2816 pragma Import (C, Method1);
2817
2818 procedure Ada_Method2 (This : in out A; V : Integer);
2819 pragma Export (C, Ada_Method2);
2820
2821 end Simple_Cpp_Interface;
2822 @end smallexample
2823
2824 @node Interfacing with C++ constructors
2825 @subsection Interfacing with C++ constructors
2826 @noindent
2827
2828 In order to interface with C++ constructors GNAT provides the
2829 @code{pragma CPP_Constructor} (@xref{Interfacing to C++,,,
2830 gnat_rm, GNAT Reference Manual}, for additional information).
2831 In this section we present some common uses of C++ constructors
2832 in mixed-languages programs in GNAT.
2833
2834 Let us assume that we need to interface with the following
2835 C++ class:
2836
2837 @smallexample
2838 @b{class} Root @{
2839 @b{public}:
2840 int a_value;
2841 int b_value;
2842 @b{virtual} int Get_Value ();
2843 Root(); // Default constructor
2844 Root(int v); // 1st non-default constructor
2845 Root(int v, int w); // 2nd non-default constructor
2846 @};
2847 @end smallexample
2848
2849 For this purpose we can write the following package spec (further
2850 information on how to build this spec is available in
2851 @ref{Interfacing with C++ at the Class Level} and
2852 @ref{Generating Ada Bindings for C and C++ headers}).
2853
2854 @smallexample @c ada
2855 with Interfaces.C; use Interfaces.C;
2856 package Pkg_Root is
2857 type Root is tagged limited record
2858 A_Value : int;
2859 B_Value : int;
2860 end record;
2861 pragma Import (CPP, Root);
2862
2863 function Get_Value (Obj : Root) return int;
2864 pragma Import (CPP, Get_Value);
2865
2866 function Constructor return Root;
2867 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ev");
2868
2869 function Constructor (v : Integer) return Root;
2870 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Ei");
2871
2872 function Constructor (v, w : Integer) return Root;
2873 pragma Cpp_Constructor (Constructor, "_ZN4RootC1Eii");
2874 end Pkg_Root;
2875 @end smallexample
2876
2877 On the Ada side the constructor is represented by a function (whose
2878 name is arbitrary) that returns the classwide type corresponding to
2879 the imported C++ class. Although the constructor is described as a
2880 function, it is typically a procedure with an extra implicit argument
2881 (the object being initialized) at the implementation level. GNAT
2882 issues the appropriate call, whatever it is, to get the object
2883 properly initialized.
2884
2885 Constructors can only appear in the following contexts:
2886
2887 @itemize @bullet
2888 @item
2889 On the right side of an initialization of an object of type @var{T}.
2890 @item
2891 On the right side of an initialization of a record component of type @var{T}.
2892 @item
2893 In an Ada 2005 limited aggregate.
2894 @item
2895 In an Ada 2005 nested limited aggregate.
2896 @item
2897 In an Ada 2005 limited aggregate that initializes an object built in
2898 place by an extended return statement.
2899 @end itemize
2900
2901 @noindent
2902 In a declaration of an object whose type is a class imported from C++,
2903 either the default C++ constructor is implicitly called by GNAT, or
2904 else the required C++ constructor must be explicitly called in the
2905 expression that initializes the object. For example:
2906
2907 @smallexample @c ada
2908 Obj1 : Root;
2909 Obj2 : Root := Constructor;
2910 Obj3 : Root := Constructor (v => 10);
2911 Obj4 : Root := Constructor (30, 40);
2912 @end smallexample
2913
2914 The first two declarations are equivalent: in both cases the default C++
2915 constructor is invoked (in the former case the call to the constructor is
2916 implicit, and in the latter case the call is explicit in the object
2917 declaration). @code{Obj3} is initialized by the C++ non-default constructor
2918 that takes an integer argument, and @code{Obj4} is initialized by the
2919 non-default C++ constructor that takes two integers.
2920
2921 Let us derive the imported C++ class in the Ada side. For example:
2922
2923 @smallexample @c ada
2924 type DT is new Root with record
2925 C_Value : Natural := 2009;
2926 end record;
2927 @end smallexample
2928
2929 In this case the components DT inherited from the C++ side must be
2930 initialized by a C++ constructor, and the additional Ada components
2931 of type DT are initialized by GNAT. The initialization of such an
2932 object is done either by default, or by means of a function returning
2933 an aggregate of type DT, or by means of an extension aggregate.
2934
2935 @smallexample @c ada
2936 Obj5 : DT;
2937 Obj6 : DT := Function_Returning_DT (50);
2938 Obj7 : DT := (Constructor (30,40) with C_Value => 50);
2939 @end smallexample
2940
2941 The declaration of @code{Obj5} invokes the default constructors: the
2942 C++ default constructor of the parent type takes care of the initialization
2943 of the components inherited from Root, and GNAT takes care of the default
2944 initialization of the additional Ada components of type DT (that is,
2945 @code{C_Value} is initialized to value 2009). The order of invocation of
2946 the constructors is consistent with the order of elaboration required by
2947 Ada and C++. That is, the constructor of the parent type is always called
2948 before the constructor of the derived type.
2949
2950 Let us now consider a record that has components whose type is imported
2951 from C++. For example:
2952
2953 @smallexample @c ada
2954 type Rec1 is limited record
2955 Data1 : Root := Constructor (10);
2956 Value : Natural := 1000;
2957 end record;
2958
2959 type Rec2 (D : Integer := 20) is limited record
2960 Rec : Rec1;
2961 Data2 : Root := Constructor (D, 30);
2962 end record;
2963 @end smallexample
2964
2965 The initialization of an object of type @code{Rec2} will call the
2966 non-default C++ constructors specified for the imported components.
2967 For example:
2968
2969 @smallexample @c ada
2970 Obj8 : Rec2 (40);
2971 @end smallexample
2972
2973 Using Ada 2005 we can use limited aggregates to initialize an object
2974 invoking C++ constructors that differ from those specified in the type
2975 declarations. For example:
2976
2977 @smallexample @c ada
2978 Obj9 : Rec2 := (Rec => (Data1 => Constructor (15, 16),
2979 others => <>),
2980 others => <>);
2981 @end smallexample
2982
2983 The above declaration uses an Ada 2005 limited aggregate to
2984 initialize @code{Obj9}, and the C++ constructor that has two integer
2985 arguments is invoked to initialize the @code{Data1} component instead
2986 of the constructor specified in the declaration of type @code{Rec1}. In
2987 Ada 2005 the box in the aggregate indicates that unspecified components
2988 are initialized using the expression (if any) available in the component
2989 declaration. That is, in this case discriminant @code{D} is initialized
2990 to value @code{20}, @code{Value} is initialized to value 1000, and the
2991 non-default C++ constructor that handles two integers takes care of
2992 initializing component @code{Data2} with values @code{20,30}.
2993
2994 In Ada 2005 we can use the extended return statement to build the Ada
2995 equivalent to C++ non-default constructors. For example:
2996
2997 @smallexample @c ada
2998 function Constructor (V : Integer) return Rec2 is
2999 begin
3000 return Obj : Rec2 := (Rec => (Data1 => Constructor (V, 20),
3001 others => <>),
3002 others => <>) do
3003 -- Further actions required for construction of
3004 -- objects of type Rec2
3005 ...
3006 end record;
3007 end Constructor;
3008 @end smallexample
3009
3010 In this example the extended return statement construct is used to
3011 build in place the returned object whose components are initialized
3012 by means of a limited aggregate. Any further action associated with
3013 the constructor can be placed inside the construct.
3014
3015 @node Interfacing with C++ at the Class Level
3016 @subsection Interfacing with C++ at the Class Level
3017 @noindent
3018 In this section we demonstrate the GNAT features for interfacing with
3019 C++ by means of an example making use of Ada 2005 abstract interface
3020 types. This example consists of a classification of animals; classes
3021 have been used to model our main classification of animals, and
3022 interfaces provide support for the management of secondary
3023 classifications. We first demonstrate a case in which the types and
3024 constructors are defined on the C++ side and imported from the Ada
3025 side, and latter the reverse case.
3026
3027 The root of our derivation will be the @code{Animal} class, with a
3028 single private attribute (the @code{Age} of the animal) and two public
3029 primitives to set and get the value of this attribute.
3030
3031 @smallexample
3032 @b{class} Animal @{
3033 @b{public}:
3034 @b{virtual} void Set_Age (int New_Age);
3035 @b{virtual} int Age ();
3036 @b{private}:
3037 int Age_Count;
3038 @};
3039 @end smallexample
3040
3041 Abstract interface types are defined in C++ by means of classes with pure
3042 virtual functions and no data members. In our example we will use two
3043 interfaces that provide support for the common management of @code{Carnivore}
3044 and @code{Domestic} animals:
3045
3046 @smallexample
3047 @b{class} Carnivore @{
3048 @b{public}:
3049 @b{virtual} int Number_Of_Teeth () = 0;
3050 @};
3051
3052 @b{class} Domestic @{
3053 @b{public}:
3054 @b{virtual void} Set_Owner (char* Name) = 0;
3055 @};
3056 @end smallexample
3057
3058 Using these declarations, we can now say that a @code{Dog} is an animal that is
3059 both Carnivore and Domestic, that is:
3060
3061 @smallexample
3062 @b{class} Dog : Animal, Carnivore, Domestic @{
3063 @b{public}:
3064 @b{virtual} int Number_Of_Teeth ();
3065 @b{virtual} void Set_Owner (char* Name);
3066
3067 Dog(); // Constructor
3068 @b{private}:
3069 int Tooth_Count;
3070 char *Owner;
3071 @};
3072 @end smallexample
3073
3074 In the following examples we will assume that the previous declarations are
3075 located in a file named @code{animals.h}. The following package demonstrates
3076 how to import these C++ declarations from the Ada side:
3077
3078 @smallexample @c ada
3079 with Interfaces.C.Strings; use Interfaces.C.Strings;
3080 package Animals is
3081 type Carnivore is interface;
3082 pragma Convention (C_Plus_Plus, Carnivore);
3083 function Number_Of_Teeth (X : Carnivore)
3084 return Natural is abstract;
3085
3086 type Domestic is interface;
3087 pragma Convention (C_Plus_Plus, Set_Owner);
3088 procedure Set_Owner
3089 (X : in out Domestic;
3090 Name : Chars_Ptr) is abstract;
3091
3092 type Animal is tagged record
3093 Age : Natural := 0;
3094 end record;
3095 pragma Import (C_Plus_Plus, Animal);
3096
3097 procedure Set_Age (X : in out Animal; Age : Integer);
3098 pragma Import (C_Plus_Plus, Set_Age);
3099
3100 function Age (X : Animal) return Integer;
3101 pragma Import (C_Plus_Plus, Age);
3102
3103 type Dog is new Animal and Carnivore and Domestic with record
3104 Tooth_Count : Natural;
3105 Owner : String (1 .. 30);
3106 end record;
3107 pragma Import (C_Plus_Plus, Dog);
3108
3109 function Number_Of_Teeth (A : Dog) return Integer;
3110 pragma Import (C_Plus_Plus, Number_Of_Teeth);
3111
3112 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3113 pragma Import (C_Plus_Plus, Set_Owner);
3114
3115 function New_Dog return Dog;
3116 pragma CPP_Constructor (New_Dog);
3117 pragma Import (CPP, New_Dog, "_ZN3DogC2Ev");
3118 end Animals;
3119 @end smallexample
3120
3121 Thanks to the compatibility between GNAT run-time structures and the C++ ABI,
3122 interfacing with these C++ classes is easy. The only requirement is that all
3123 the primitives and components must be declared exactly in the same order in
3124 the two languages.
3125
3126 Regarding the abstract interfaces, we must indicate to the GNAT compiler by
3127 means of a @code{pragma Convention (C_Plus_Plus)}, the convention used to pass
3128 the arguments to the called primitives will be the same as for C++. For the
3129 imported classes we use @code{pragma Import} with convention @code{C_Plus_Plus}
3130 to indicate that they have been defined on the C++ side; this is required
3131 because the dispatch table associated with these tagged types will be built
3132 in the C++ side and therefore will not contain the predefined Ada primitives
3133 which Ada would otherwise expect.
3134
3135 As the reader can see there is no need to indicate the C++ mangled names
3136 associated with each subprogram because it is assumed that all the calls to
3137 these primitives will be dispatching calls. The only exception is the
3138 constructor, which must be registered with the compiler by means of
3139 @code{pragma CPP_Constructor} and needs to provide its associated C++
3140 mangled name because the Ada compiler generates direct calls to it.
3141
3142 With the above packages we can now declare objects of type Dog on the Ada side
3143 and dispatch calls to the corresponding subprograms on the C++ side. We can
3144 also extend the tagged type Dog with further fields and primitives, and
3145 override some of its C++ primitives on the Ada side. For example, here we have
3146 a type derivation defined on the Ada side that inherits all the dispatching
3147 primitives of the ancestor from the C++ side.
3148
3149 @smallexample
3150 @b{with} Animals; @b{use} Animals;
3151 @b{package} Vaccinated_Animals @b{is}
3152 @b{type} Vaccinated_Dog @b{is new} Dog @b{with null record};
3153 @b{function} Vaccination_Expired (A : Vaccinated_Dog) @b{return} Boolean;
3154 @b{end} Vaccinated_Animals;
3155 @end smallexample
3156
3157 It is important to note that, because of the ABI compatibility, the programmer
3158 does not need to add any further information to indicate either the object
3159 layout or the dispatch table entry associated with each dispatching operation.
3160
3161 Now let us define all the types and constructors on the Ada side and export
3162 them to C++, using the same hierarchy of our previous example:
3163
3164 @smallexample @c ada
3165 with Interfaces.C.Strings;
3166 use Interfaces.C.Strings;
3167 package Animals is
3168 type Carnivore is interface;
3169 pragma Convention (C_Plus_Plus, Carnivore);
3170 function Number_Of_Teeth (X : Carnivore)
3171 return Natural is abstract;
3172
3173 type Domestic is interface;
3174 pragma Convention (C_Plus_Plus, Set_Owner);
3175 procedure Set_Owner
3176 (X : in out Domestic;
3177 Name : Chars_Ptr) is abstract;
3178
3179 type Animal is tagged record
3180 Age : Natural := 0;
3181 end record;
3182 pragma Convention (C_Plus_Plus, Animal);
3183
3184 procedure Set_Age (X : in out Animal; Age : Integer);
3185 pragma Export (C_Plus_Plus, Set_Age);
3186
3187 function Age (X : Animal) return Integer;
3188 pragma Export (C_Plus_Plus, Age);
3189
3190 type Dog is new Animal and Carnivore and Domestic with record
3191 Tooth_Count : Natural;
3192 Owner : String (1 .. 30);
3193 end record;
3194 pragma Convention (C_Plus_Plus, Dog);
3195
3196 function Number_Of_Teeth (A : Dog) return Integer;
3197 pragma Export (C_Plus_Plus, Number_Of_Teeth);
3198
3199 procedure Set_Owner (A : in out Dog; Name : Chars_Ptr);
3200 pragma Export (C_Plus_Plus, Set_Owner);
3201
3202 function New_Dog return Dog'Class;
3203 pragma Export (C_Plus_Plus, New_Dog);
3204 end Animals;
3205 @end smallexample
3206
3207 Compared with our previous example the only difference is the use of
3208 @code{pragma Export} to indicate to the GNAT compiler that the primitives will
3209 be available to C++. Thanks to the ABI compatibility, on the C++ side there is
3210 nothing else to be done; as explained above, the only requirement is that all
3211 the primitives and components are declared in exactly the same order.
3212
3213 For completeness, let us see a brief C++ main program that uses the
3214 declarations available in @code{animals.h} (presented in our first example) to
3215 import and use the declarations from the Ada side, properly initializing and
3216 finalizing the Ada run-time system along the way:
3217
3218 @smallexample
3219 @b{#include} "animals.h"
3220 @b{#include} <iostream>
3221 @b{using namespace} std;
3222
3223 void Check_Carnivore (Carnivore *obj) @{@dots{}@}
3224 void Check_Domestic (Domestic *obj) @{@dots{}@}
3225 void Check_Animal (Animal *obj) @{@dots{}@}
3226 void Check_Dog (Dog *obj) @{@dots{}@}
3227
3228 @b{extern} "C" @{
3229 void adainit (void);
3230 void adafinal (void);
3231 Dog* new_dog ();
3232 @}
3233
3234 void test ()
3235 @{
3236 Dog *obj = new_dog(); // Ada constructor
3237 Check_Carnivore (obj); // Check secondary DT
3238 Check_Domestic (obj); // Check secondary DT
3239 Check_Animal (obj); // Check primary DT
3240 Check_Dog (obj); // Check primary DT
3241 @}
3242
3243 int main ()
3244 @{
3245 adainit (); test(); adafinal ();
3246 return 0;
3247 @}
3248 @end smallexample
3249
3250 @node Comparison between GNAT and C/C++ Compilation Models
3251 @section Comparison between GNAT and C/C++ Compilation Models
3252
3253 @noindent
3254 The GNAT model of compilation is close to the C and C++ models. You can
3255 think of Ada specs as corresponding to header files in C. As in C, you
3256 don't need to compile specs; they are compiled when they are used. The
3257 Ada @code{with} is similar in effect to the @code{#include} of a C
3258 header.
3259
3260 One notable difference is that, in Ada, you may compile specs separately
3261 to check them for semantic and syntactic accuracy. This is not always
3262 possible with C headers because they are fragments of programs that have
3263 less specific syntactic or semantic rules.
3264
3265 The other major difference is the requirement for running the binder,
3266 which performs two important functions. First, it checks for
3267 consistency. In C or C++, the only defense against assembling
3268 inconsistent programs lies outside the compiler, in a makefile, for
3269 example. The binder satisfies the Ada requirement that it be impossible
3270 to construct an inconsistent program when the compiler is used in normal
3271 mode.
3272
3273 @cindex Elaboration order control
3274 The other important function of the binder is to deal with elaboration
3275 issues. There are also elaboration issues in C++ that are handled
3276 automatically. This automatic handling has the advantage of being
3277 simpler to use, but the C++ programmer has no control over elaboration.
3278 Where @code{gnatbind} might complain there was no valid order of
3279 elaboration, a C++ compiler would simply construct a program that
3280 malfunctioned at run time.
3281 @end ifclear
3282
3283 @node Comparison between GNAT and Conventional Ada Library Models
3284 @section Comparison between GNAT and Conventional Ada Library Models
3285
3286 @noindent
3287 This section is intended for Ada programmers who have
3288 used an Ada compiler implementing the traditional Ada library
3289 model, as described in the Ada Reference Manual.
3290
3291 @cindex GNAT library
3292 In GNAT, there is no ``library'' in the normal sense. Instead, the set of
3293 source files themselves acts as the library. Compiling Ada programs does
3294 not generate any centralized information, but rather an object file and
3295 a ALI file, which are of interest only to the binder and linker.
3296 In a traditional system, the compiler reads information not only from
3297 the source file being compiled, but also from the centralized library.
3298 This means that the effect of a compilation depends on what has been
3299 previously compiled. In particular:
3300
3301 @itemize @bullet
3302 @item
3303 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3304 to the version of the unit most recently compiled into the library.
3305
3306 @item
3307 Inlining is effective only if the necessary body has already been
3308 compiled into the library.
3309
3310 @item
3311 Compiling a unit may obsolete other units in the library.
3312 @end itemize
3313
3314 @noindent
3315 In GNAT, compiling one unit never affects the compilation of any other
3316 units because the compiler reads only source files. Only changes to source
3317 files can affect the results of a compilation. In particular:
3318
3319 @itemize @bullet
3320 @item
3321 When a unit is @code{with}'ed, the unit seen by the compiler corresponds
3322 to the source version of the unit that is currently accessible to the
3323 compiler.
3324
3325 @item
3326 @cindex Inlining
3327 Inlining requires the appropriate source files for the package or
3328 subprogram bodies to be available to the compiler. Inlining is always
3329 effective, independent of the order in which units are complied.
3330
3331 @item
3332 Compiling a unit never affects any other compilations. The editing of
3333 sources may cause previous compilations to be out of date if they
3334 depended on the source file being modified.
3335 @end itemize
3336
3337 @noindent
3338 The most important result of these differences is that order of compilation
3339 is never significant in GNAT. There is no situation in which one is
3340 required to do one compilation before another. What shows up as order of
3341 compilation requirements in the traditional Ada library becomes, in
3342 GNAT, simple source dependencies; in other words, there is only a set
3343 of rules saying what source files must be present when a file is
3344 compiled.
3345
3346 @ifset vms
3347 @node Placement of temporary files
3348 @section Placement of temporary files
3349 @cindex Temporary files (user control over placement)
3350
3351 @noindent
3352 GNAT creates temporary files in the directory designated by the environment
3353 variable @env{TMPDIR}.
3354 (See the HP @emph{C RTL Reference Manual} on the function @code{getenv()}
3355 for detailed information on how environment variables are resolved.
3356 For most users the easiest way to make use of this feature is to simply
3357 define @env{TMPDIR} as a job level logical name).
3358 For example, if you wish to use a Ramdisk (assuming DECRAM is installed)
3359 for compiler temporary files, then you can include something like the
3360 following command in your @file{LOGIN.COM} file:
3361
3362 @smallexample
3363 $ define/job TMPDIR "/disk$scratchram/000000/temp/"
3364 @end smallexample
3365
3366 @noindent
3367 If @env{TMPDIR} is not defined, then GNAT uses the directory designated by
3368 @env{TMP}; if @env{TMP} is not defined, then GNAT uses the directory
3369 designated by @env{TEMP}.
3370 If none of these environment variables are defined then GNAT uses the
3371 directory designated by the logical name @code{SYS$SCRATCH:}
3372 (by default the user's home directory). If all else fails
3373 GNAT uses the current directory for temporary files.
3374 @end ifset
3375
3376 @c *************************
3377 @node Compiling with gcc
3378 @chapter Compiling with @command{gcc}
3379
3380 @noindent
3381 This chapter discusses how to compile Ada programs using the @command{gcc}
3382 command. It also describes the set of switches
3383 that can be used to control the behavior of the compiler.
3384 @menu
3385 * Compiling Programs::
3386 * Switches for gcc::
3387 * Search Paths and the Run-Time Library (RTL)::
3388 * Order of Compilation Issues::
3389 * Examples::
3390 @end menu
3391
3392 @node Compiling Programs
3393 @section Compiling Programs
3394
3395 @noindent
3396 The first step in creating an executable program is to compile the units
3397 of the program using the @command{gcc} command. You must compile the
3398 following files:
3399
3400 @itemize @bullet
3401 @item
3402 the body file (@file{.adb}) for a library level subprogram or generic
3403 subprogram
3404
3405 @item
3406 the spec file (@file{.ads}) for a library level package or generic
3407 package that has no body
3408
3409 @item
3410 the body file (@file{.adb}) for a library level package
3411 or generic package that has a body
3412
3413 @end itemize
3414
3415 @noindent
3416 You need @emph{not} compile the following files
3417
3418 @itemize @bullet
3419
3420 @item
3421 the spec of a library unit which has a body
3422
3423 @item
3424 subunits
3425 @end itemize
3426
3427 @noindent
3428 because they are compiled as part of compiling related units. GNAT
3429 package specs
3430 when the corresponding body is compiled, and subunits when the parent is
3431 compiled.
3432
3433 @cindex cannot generate code
3434 If you attempt to compile any of these files, you will get one of the
3435 following error messages (where @var{fff} is the name of the file you
3436 compiled):
3437
3438 @smallexample
3439 cannot generate code for file @var{fff} (package spec)
3440 to check package spec, use -gnatc
3441
3442 cannot generate code for file @var{fff} (missing subunits)
3443 to check parent unit, use -gnatc
3444
3445 cannot generate code for file @var{fff} (subprogram spec)
3446 to check subprogram spec, use -gnatc
3447
3448 cannot generate code for file @var{fff} (subunit)
3449 to check subunit, use -gnatc
3450 @end smallexample
3451
3452 @noindent
3453 As indicated by the above error messages, if you want to submit
3454 one of these files to the compiler to check for correct semantics
3455 without generating code, then use the @option{-gnatc} switch.
3456
3457 The basic command for compiling a file containing an Ada unit is
3458
3459 @smallexample
3460 @c $ gcc -c @ovar{switches} @file{file name}
3461 @c Expanding @ovar macro inline (explanation in macro def comments)
3462 $ gcc -c @r{[}@var{switches}@r{]} @file{file name}
3463 @end smallexample
3464
3465 @noindent
3466 where @var{file name} is the name of the Ada file (usually
3467 having an extension
3468 @file{.ads} for a spec or @file{.adb} for a body).
3469 @ifclear vms
3470 You specify the
3471 @option{-c} switch to tell @command{gcc} to compile, but not link, the file.
3472 @end ifclear
3473 The result of a successful compilation is an object file, which has the
3474 same name as the source file but an extension of @file{.o} and an Ada
3475 Library Information (ALI) file, which also has the same name as the
3476 source file, but with @file{.ali} as the extension. GNAT creates these
3477 two output files in the current directory, but you may specify a source
3478 file in any directory using an absolute or relative path specification
3479 containing the directory information.
3480
3481 @findex gnat1
3482 @command{gcc} is actually a driver program that looks at the extensions of
3483 the file arguments and loads the appropriate compiler. For example, the
3484 GNU C compiler is @file{cc1}, and the Ada compiler is @file{gnat1}.
3485 These programs are in directories known to the driver program (in some
3486 configurations via environment variables you set), but need not be in
3487 your path. The @command{gcc} driver also calls the assembler and any other
3488 utilities needed to complete the generation of the required object
3489 files.
3490
3491 It is possible to supply several file names on the same @command{gcc}
3492 command. This causes @command{gcc} to call the appropriate compiler for
3493 each file. For example, the following command lists two separate
3494 files to be compiled:
3495
3496 @smallexample
3497 $ gcc -c x.adb y.adb
3498 @end smallexample
3499
3500 @noindent
3501 calls @code{gnat1} (the Ada compiler) twice to compile @file{x.adb} and
3502 @file{y.adb}.
3503 The compiler generates two object files @file{x.o} and @file{y.o}
3504 and the two ALI files @file{x.ali} and @file{y.ali}.
3505 Any switches apply to all the files ^listed,^listed.^
3506
3507 @node Switches for gcc
3508 @section Switches for @command{gcc}
3509
3510 @noindent
3511 The @command{gcc} command accepts switches that control the
3512 compilation process. These switches are fully described in this section.
3513 First we briefly list all the switches, in alphabetical order, then we
3514 describe the switches in more detail in functionally grouped sections.
3515
3516 More switches exist for GCC than those documented here, especially
3517 for specific targets. However, their use is not recommended as
3518 they may change code generation in ways that are incompatible with
3519 the Ada run-time library, or can cause inconsistencies between
3520 compilation units.
3521
3522 @menu
3523 * Output and Error Message Control::
3524 * Warning Message Control::
3525 * Debugging and Assertion Control::
3526 * Validity Checking::
3527 * Style Checking::
3528 * Run-Time Checks::
3529 * Using gcc for Syntax Checking::
3530 * Using gcc for Semantic Checking::
3531 * Compiling Different Versions of Ada::
3532 * Character Set Control::
3533 * File Naming Control::
3534 * Subprogram Inlining Control::
3535 * Auxiliary Output Control::
3536 * Debugging Control::
3537 * Exception Handling Control::
3538 * Units to Sources Mapping Files::
3539 * Integrated Preprocessing::
3540 * Code Generation Control::
3541 @ifset vms
3542 * Return Codes::
3543 @end ifset
3544 @end menu
3545
3546 @table @option
3547 @c !sort!
3548 @ifclear vms
3549 @cindex @option{-b} (@command{gcc})
3550 @item -b @var{target}
3551 Compile your program to run on @var{target}, which is the name of a
3552 system configuration. You must have a GNAT cross-compiler built if
3553 @var{target} is not the same as your host system.
3554
3555 @item -B@var{dir}
3556 @cindex @option{-B} (@command{gcc})
3557 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
3558 from @var{dir} instead of the default location. Only use this switch
3559 when multiple versions of the GNAT compiler are available.
3560 @xref{Directory Options,, Options for Directory Search, gcc, Using the
3561 GNU Compiler Collection (GCC)}, for further details. You would normally
3562 use the @option{-b} or @option{-V} switch instead.
3563
3564 @item -c
3565 @cindex @option{-c} (@command{gcc})
3566 Compile. Always use this switch when compiling Ada programs.
3567
3568 Note: for some other languages when using @command{gcc}, notably in
3569 the case of C and C++, it is possible to use
3570 use @command{gcc} without a @option{-c} switch to
3571 compile and link in one step. In the case of GNAT, you
3572 cannot use this approach, because the binder must be run
3573 and @command{gcc} cannot be used to run the GNAT binder.
3574 @end ifclear
3575
3576 @item -fcallgraph-info@r{[}=su,da@r{]}
3577 @cindex @option{-fcallgraph-info} (@command{gcc})
3578 Makes the compiler output callgraph information for the program, on a
3579 per-file basis. The information is generated in the VCG format. It can
3580 be decorated with additional, per-node and/or per-edge information, if a
3581 list of comma-separated markers is additionally specified. When the
3582 @var{su} marker is specified, the callgraph is decorated with stack usage information; it is equivalent to @option{-fstack-usage}. When the @var{da}
3583 marker is specified, the callgraph is decorated with information about
3584 dynamically allocated objects.
3585
3586 @item -fdump-scos
3587 @cindex @option{-fdump-scos} (@command{gcc})
3588 Generates SCO (Source Coverage Obligation) information in the ALI file.
3589 This information is used by advanced coverage tools. See unit @file{SCOs}
3590 in the compiler sources for details in files @file{scos.ads} and
3591 @file{scos.adb}.
3592
3593 @item -fdump-xref
3594 @cindex @option{-fdump-xref} (@command{gcc})
3595 Generates cross reference information in GLI files for C and C++ sources.
3596 The GLI files have the same syntax as the ALI files for Ada, and can be used
3597 for source navigation in IDEs and on the command line using e.g. gnatxref
3598 and the @option{--ext=gli} switch.
3599
3600 @item -flto@r{[}=n@r{]}
3601 @cindex @option{-flto} (@command{gcc})
3602 Enables Link Time Optimization. This switch must be used in conjunction
3603 with the traditional @option{-Ox} switches and instructs the compiler to
3604 defer most optimizations until the link stage. The advantage of this
3605 approach is that the compiler can do a whole-program analysis and choose
3606 the best interprocedural optimization strategy based on a complete view
3607 of the program, instead of a fragmentary view with the usual approach.
3608 This can also speed up the compilation of huge programs and reduce the
3609 size of the final executable, compared with a per-unit compilation with
3610 full inlining across modules enabled with the @option{-gnatn2} switch.
3611 The drawback of this approach is that it may require much more memory.
3612 The switch, as well as the accompanying @option{-Ox} switches, must be
3613 specified both for the compilation and the link phases.
3614 If the @var{n} parameter is specified, the optimization and final code
3615 generation at link time are executed using @var{n} parallel jobs by
3616 means of an installed @command{make} program.
3617
3618 @item -fno-inline
3619 @cindex @option{-fno-inline} (@command{gcc})
3620 Suppresses all inlining, even if other optimization or inlining
3621 switches are set. This includes suppression of inlining that
3622 results from the use of the pragma @code{Inline_Always}.
3623 Any occurrences of pragma @code{Inline} or @code{Inline_Always}
3624 are ignored, and @option{-gnatn} and @option{-gnatN} have no
3625 effects if this switch is present. Note that inlining can also
3626 be suppressed on a finer-grained basis with pragma @code{No_Inline}.
3627
3628 @item -fno-inline-functions
3629 @cindex @option{-fno-inline-functions} (@command{gcc})
3630 Suppresses automatic inlining of subprograms, which is enabled
3631 if @option{-O3} is used.
3632
3633 @item -fno-inline-small-functions
3634 @cindex @option{-fno-inline-small-functions} (@command{gcc})
3635 Suppresses automatic inlining of small subprograms, which is enabled
3636 if @option{-O2} is used.
3637
3638 @item -fno-inline-functions-called-once
3639 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
3640 Suppresses inlining of subprograms local to the unit and called once
3641 from within it, which is enabled if @option{-O1} is used.
3642
3643 @item -fno-ivopts
3644 @cindex @option{-fno-ivopts} (@command{gcc})
3645 Suppresses high-level loop induction variable optimizations, which are
3646 enabled if @option{-O1} is used. These optimizations are generally
3647 profitable but, for some specific cases of loops with numerous uses
3648 of the iteration variable that follow a common pattern, they may end
3649 up destroying the regularity that could be exploited at a lower level
3650 and thus producing inferior code.
3651
3652 @item -fno-strict-aliasing
3653 @cindex @option{-fno-strict-aliasing} (@command{gcc})
3654 Causes the compiler to avoid assumptions regarding non-aliasing
3655 of objects of different types. See
3656 @ref{Optimization and Strict Aliasing} for details.
3657
3658 @item -fstack-check
3659 @cindex @option{-fstack-check} (@command{gcc})
3660 Activates stack checking.
3661 See @ref{Stack Overflow Checking} for details.
3662
3663 @item -fstack-usage
3664 @cindex @option{-fstack-usage} (@command{gcc})
3665 Makes the compiler output stack usage information for the program, on a
3666 per-subprogram basis. See @ref{Static Stack Usage Analysis} for details.
3667
3668 @item ^-g^/DEBUG^
3669 @cindex @option{^-g^/DEBUG^} (@command{gcc})
3670 Generate debugging information. This information is stored in the object
3671 file and copied from there to the final executable file by the linker,
3672 where it can be read by the debugger. You must use the
3673 @option{^-g^/DEBUG^} switch if you plan on using the debugger.
3674
3675 @item -gnat83
3676 @cindex @option{-gnat83} (@command{gcc})
3677 Enforce Ada 83 restrictions.
3678
3679 @item -gnat95
3680 @cindex @option{-gnat95} (@command{gcc})
3681 Enforce Ada 95 restrictions.
3682
3683 @item -gnat05
3684 @cindex @option{-gnat05} (@command{gcc})
3685 Allow full Ada 2005 features.
3686
3687 @item -gnat2005
3688 @cindex @option{-gnat2005} (@command{gcc})
3689 Allow full Ada 2005 features (same as @option{-gnat05})
3690
3691 @item -gnat12
3692 @cindex @option{-gnat12} (@command{gcc})
3693
3694 @item -gnat2012
3695 @cindex @option{-gnat2012} (@command{gcc})
3696 Allow full Ada 2012 features (same as @option{-gnat12})
3697
3698 @item -gnata
3699 @cindex @option{-gnata} (@command{gcc})
3700 Assertions enabled. @code{Pragma Assert} and @code{pragma Debug} to be
3701 activated. Note that these pragmas can also be controlled using the
3702 configuration pragmas @code{Assertion_Policy} and @code{Debug_Policy}.
3703 It also activates pragmas @code{Check}, @code{Precondition}, and
3704 @code{Postcondition}. Note that these pragmas can also be controlled
3705 using the configuration pragma @code{Check_Policy}. In Ada 2012, it
3706 also activates all assertions defined in the RM as aspects: preconditions,
3707 postconditions, type invariants and (sub)type predicates. In all Ada modes,
3708 corresponding pragmas for type invariants and (sub)type predicates are
3709 also activated.
3710
3711 @item -gnatA
3712 @cindex @option{-gnatA} (@command{gcc})
3713 Avoid processing @file{gnat.adc}. If a @file{gnat.adc} file is present,
3714 it will be ignored.
3715
3716 @item -gnatb
3717 @cindex @option{-gnatb} (@command{gcc})
3718 Generate brief messages to @file{stderr} even if verbose mode set.
3719
3720 @item -gnatB
3721 @cindex @option{-gnatB} (@command{gcc})
3722 Assume no invalid (bad) values except for 'Valid attribute use
3723 (@pxref{Validity Checking}).
3724
3725 @item -gnatc
3726 @cindex @option{-gnatc} (@command{gcc})
3727 Check syntax and semantics only (no code generation attempted). When the
3728 compiler is invoked by @command{gnatmake}, if the switch @option{-gnatc} is
3729 only given to the compiler (after @option{-cargs} or in package Compiler of
3730 the project file, @command{gnatmake} will fail because it will not find the
3731 object file after compilation. If @command{gnatmake} is called with
3732 @option{-gnatc} as a builder switch (before @option{-cargs} or in package
3733 Builder of the project file) then @command{gnatmake} will not fail because
3734 it will not look for the object files after compilation, and it will not try
3735 to build and link. This switch may not be given if a previous @code{-gnatR}
3736 switch has been given, since @code{-gnatR} requires that the code generator
3737 be called to complete determination of representation information.
3738
3739 @item -gnatC
3740 @cindex @option{-gnatC} (@command{gcc})
3741 Generate CodePeer intermediate format (no code generation attempted).
3742 This switch will generate an intermediate representation suitable for
3743 use by CodePeer (@file{.scil} files). This switch is not compatible with
3744 code generation (it will, among other things, disable some switches such
3745 as -gnatn, and enable others such as -gnata).
3746
3747 @item -gnatd
3748 @cindex @option{-gnatd} (@command{gcc})
3749 Specify debug options for the compiler. The string of characters after
3750 the @option{-gnatd} specify the specific debug options. The possible
3751 characters are 0-9, a-z, A-Z, optionally preceded by a dot. See
3752 compiler source file @file{debug.adb} for details of the implemented
3753 debug options. Certain debug options are relevant to applications
3754 programmers, and these are documented at appropriate points in this
3755 users guide.
3756
3757 @ifclear vms
3758 @item -gnatD
3759 @cindex @option{-gnatD[nn]} (@command{gcc})
3760 @end ifclear
3761 @ifset vms
3762 @item /XDEBUG /LXDEBUG=nnn
3763 @end ifset
3764 Create expanded source files for source level debugging. This switch
3765 also suppress generation of cross-reference information
3766 (see @option{-gnatx}). Note that this switch is not allowed if a previous
3767 -gnatR switch has been given, since these two switches are not compatible.
3768
3769 @item ^-gnateA^/ALIASING_CHECK^
3770 @cindex @option{-gnateA} (@command{gcc})
3771 Check that there is no aliasing between two parameters of the same subprogram.
3772
3773 @item -gnatec=@var{path}
3774 @cindex @option{-gnatec} (@command{gcc})
3775 Specify a configuration pragma file
3776 @ifclear vms
3777 (the equal sign is optional)
3778 @end ifclear
3779 (@pxref{The Configuration Pragmas Files}).
3780
3781 @item -gnateC
3782 @cindex @option{-gnateC} (@command{gcc})
3783 Generate CodePeer messages in a compiler-like format. This switch is only
3784 effective if @option{-gnatcC} is also specified and requires an installation
3785 of CodePeer.
3786
3787 @item ^-gnated^/DISABLE_ATOMIC_SYNCHRONIZATION^
3788 @cindex @option{-gnated} (@command{gcc})
3789 Disable atomic synchronization
3790
3791 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=@var{value}@r{]}
3792 @cindex @option{-gnateD} (@command{gcc})
3793 Defines a symbol, associated with @var{value}, for preprocessing.
3794 (@pxref{Integrated Preprocessing}).
3795
3796 @item -gnateE
3797 @cindex @option{-gnateE} (@command{gcc})
3798 Generate extra information in exception messages. In particular, display
3799 extra column information and the value and range associated with index and
3800 range check failures, and extra column information for access checks.
3801 In cases where the compiler is able to determine at compile time that
3802 a check will fail, it gives a warning, and the extra information is not
3803 produced at run time.
3804
3805 @item -gnatef
3806 @cindex @option{-gnatef} (@command{gcc})
3807 Display full source path name in brief error messages.
3808
3809 @item -gnateF
3810 @cindex @option{-gnateF} (@command{gcc})
3811 Check for overflow on all floating-point operations, including those
3812 for unconstrained predefined types. See description of pragma
3813 @code{Check_Float_Overflow} in GNAT RM.
3814
3815 @item -gnateG
3816 @cindex @option{-gnateG} (@command{gcc})
3817 Save result of preprocessing in a text file.
3818
3819 @item -gnatei@var{nnn}
3820 @cindex @option{-gnatei} (@command{gcc})
3821 Set maximum number of instantiations during compilation of a single unit to
3822 @var{nnn}. This may be useful in increasing the default maximum of 8000 for
3823 the rare case when a single unit legitimately exceeds this limit.
3824
3825 @item -gnateI@var{nnn}
3826 @cindex @option{-gnateI} (@command{gcc})
3827 Indicates that the source is a multi-unit source and that the index of the
3828 unit to compile is @var{nnn}. @var{nnn} needs to be a positive number and need
3829 to be a valid index in the multi-unit source.
3830
3831 @item -gnatel
3832 @cindex @option{-gnatel} (@command{gcc})
3833 This switch can be used with the static elaboration model to issue info
3834 messages showing
3835 where implicit @code{pragma Elaborate} and @code{pragma Elaborate_All}
3836 are generated. This is useful in diagnosing elaboration circularities
3837 caused by these implicit pragmas when using the static elaboration
3838 model. See See the section in this guide on elaboration checking for
3839 further details. These messages are not generated by default, and are
3840 intended only for temporary use when debugging circularity problems.
3841
3842 @item -gnateL
3843 @cindex @option{-gnatel} (@command{gcc})
3844 This switch turns off the info messages about implicit elaboration pragmas.
3845
3846 @item -gnatem=@var{path}
3847 @cindex @option{-gnatem} (@command{gcc})
3848 Specify a mapping file
3849 @ifclear vms
3850 (the equal sign is optional)
3851 @end ifclear
3852 (@pxref{Units to Sources Mapping Files}).
3853
3854 @item -gnatep=@var{file}
3855 @cindex @option{-gnatep} (@command{gcc})
3856 Specify a preprocessing data file
3857 @ifclear vms
3858 (the equal sign is optional)
3859 @end ifclear
3860 (@pxref{Integrated Preprocessing}).
3861
3862 @item -gnateP
3863 @cindex @option{-gnateP} (@command{gcc})
3864 Turn categorization dependency errors into warnings.
3865 Ada requires that units that WITH one another have compatible categories, for
3866 example a Pure unit cannot WITH a Preelaborate unit. If this switch is used,
3867 these errors become warnings (which can be ignored, or suppressed in the usual
3868 manner). This can be useful in some specialized circumstances such as the
3869 temporary use of special test software.
3870
3871 @item -gnateS
3872 @cindex @option{-gnateS} (@command{gcc})
3873 Synonym of @option{-fdump-scos}, kept for backwards compatibility.
3874
3875 @item -gnatet=@var{path}
3876 @cindex @option{-gnatet=file} (@command{gcc})
3877 Generate target dependent information. The format of the output file is
3878 described in the section about switch @option{-gnateT}.
3879
3880 @item -gnateT=@var{path}
3881 @cindex @option{-gnateT} (@command{gcc})
3882 Read target dependent information, such as endianness or sizes and alignments
3883 of base type. If this switch is passed, the default target dependent
3884 information of the compiler is replaced by the one read from the input file.
3885 This is used by tools other than the compiler, e.g. to do
3886 semantic analysis of programs that will run on some other target than
3887 the machine on which the tool is run.
3888
3889 The following target dependent values should be defined,
3890 where @code{Nat} denotes a natural integer value, @code{Pos} denotes a
3891 positive integer value, and fields marked with a question mark are
3892 boolean fields, where a value of 0 is False, and a value of 1 is True:
3893
3894 @smallexample
3895 Bits_BE : Nat; -- Bits stored big-endian?
3896 Bits_Per_Unit : Pos; -- Bits in a storage unit
3897 Bits_Per_Word : Pos; -- Bits in a word
3898 Bytes_BE : Nat; -- Bytes stored big-endian?
3899 Char_Size : Pos; -- Standard.Character'Size
3900 Double_Float_Alignment : Nat; -- Alignment of double float
3901 Double_Scalar_Alignment : Nat; -- Alignment of double length scalar
3902 Double_Size : Pos; -- Standard.Long_Float'Size
3903 Float_Size : Pos; -- Standard.Float'Size
3904 Float_Words_BE : Nat; -- Float words stored big-endian?
3905 Int_Size : Pos; -- Standard.Integer'Size
3906 Long_Double_Size : Pos; -- Standard.Long_Long_Float'Size
3907 Long_Long_Size : Pos; -- Standard.Long_Long_Integer'Size
3908 Long_Size : Pos; -- Standard.Long_Integer'Size
3909 Maximum_Alignment : Pos; -- Maximum permitted alignment
3910 Max_Unaligned_Field : Pos; -- Maximum size for unaligned bit field
3911 Pointer_Size : Pos; -- System.Address'Size
3912 Short_Enums : Nat; -- Short foreign convention enums?
3913 Short_Size : Pos; -- Standard.Short_Integer'Size
3914 Strict_Alignment : Nat; -- Strict alignment?
3915 System_Allocator_Alignment : Nat; -- Alignment for malloc calls
3916 Wchar_T_Size : Pos; -- Interfaces.C.wchar_t'Size
3917 Words_BE : Nat; -- Words stored big-endian?
3918 @end smallexample
3919
3920 The format of the input file is as follows. First come the values of
3921 the variables defined above, with one line per value:
3922
3923 @smallexample
3924 name value
3925 @end smallexample
3926
3927 where @code{name} is the name of the parameter, spelled out in full,
3928 and cased as in the above list, and @code{value} is an unsigned decimal
3929 integer. Two or more blanks separates the name from the value.
3930
3931 All the variables must be present, in alphabetical order (i.e. the
3932 same order as the list above).
3933
3934 Then there is a blank line to separate the two parts of the file. Then
3935 come the lines showing the floating-point types to be registered, with
3936 one line per registered mode:
3937
3938 @smallexample
3939 name digs float_rep size alignment
3940 @end smallexample
3941
3942 where @code{name} is the string name of the type (which can have
3943 single spaces embedded in the name (e.g. long double), @code{digs} is
3944 the number of digits for the floating-point type, @code{float_rep} is
3945 the float representation (I/V/A for IEEE-754-Binary, Vax_Native,
3946 AAMP), @code{size} is the size in bits, @code{alignment} is the
3947 alignment in bits. The name is followed by at least two blanks, fields
3948 are separated by at least one blank, and a LF character immediately
3949 follows the alignment field.
3950
3951 Here is an example of a target parameterization file:
3952
3953 @smallexample
3954 Bits_BE 0
3955 Bits_Per_Unit 8
3956 Bits_Per_Word 64
3957 Bytes_BE 0
3958 Char_Size 8
3959 Double_Float_Alignment 0
3960 Double_Scalar_Alignment 0
3961 Double_Size 64
3962 Float_Size 32
3963 Float_Words_BE 0
3964 Int_Size 64
3965 Long_Double_Size 128
3966 Long_Long_Size 64
3967 Long_Size 64
3968 Maximum_Alignment 16
3969 Max_Unaligned_Field 64
3970 Pointer_Size 64
3971 Short_Size 16
3972 Strict_Alignment 0
3973 System_Allocator_Alignment 16
3974 Wchar_T_Size 32
3975 Words_BE 0
3976
3977 float 15 I 64 64
3978 double 15 I 64 64
3979 long double 18 I 80 128
3980 TF 33 I 128 128
3981 @end smallexample
3982
3983 @item -gnateu
3984 @cindex @option{-gnateu} (@command{gcc})
3985 Ignore unrecognized validity, warning, and style switches that
3986 appear after this switch is given. This may be useful when
3987 compiling sources developed on a later version of the compiler
3988 with an earlier version. Of course the earlier version must
3989 support this switch.
3990
3991 @item ^-gnateV^/PARAMETER_VALIDITY_CHECK^
3992 @cindex @option{-gnateV} (@command{gcc})
3993 Check validity of subprogram parameters.
3994
3995 @item ^-gnateY^/IGNORE_SUPPRESS_SYLE_CHECK_PRAGMAS^
3996 @cindex @option{-gnateY} (@command{gcc})
3997 Ignore all STYLE_CHECKS pragmas. Full legality checks
3998 are still carried out, but the pragmas have no effect
3999 on what style checks are active. This allows all style
4000 checking options to be controlled from the command line.
4001
4002 @item -gnatE
4003 @cindex @option{-gnatE} (@command{gcc})
4004 Full dynamic elaboration checks.
4005
4006 @item -gnatf
4007 @cindex @option{-gnatf} (@command{gcc})
4008 Full errors. Multiple errors per line, all undefined references, do not
4009 attempt to suppress cascaded errors.
4010
4011 @item -gnatF
4012 @cindex @option{-gnatF} (@command{gcc})
4013 Externals names are folded to all uppercase.
4014
4015 @item ^-gnatg^/GNAT_INTERNAL^
4016 @cindex @option{^-gnatg^/GNAT_INTERNAL^} (@command{gcc})
4017 Internal GNAT implementation mode. This should not be used for
4018 applications programs, it is intended only for use by the compiler
4019 and its run-time library. For documentation, see the GNAT sources.
4020 Note that @option{^-gnatg^/GNAT_INTERNAL^} implies
4021 @option{^-gnatw.ge^/WARNINGS=GNAT,ERRORS^} and
4022 @option{^-gnatyg^/STYLE_CHECKS=GNAT^}
4023 so that all standard warnings and all standard style options are turned on.
4024 All warnings and style messages are treated as errors.
4025
4026 @ifclear vms
4027 @item -gnatG=nn
4028 @cindex @option{-gnatG[nn]} (@command{gcc})
4029 @end ifclear
4030 @ifset vms
4031 @item /EXPAND_SOURCE, /LEXPAND_SOURCE=nnn
4032 @end ifset
4033 List generated expanded code in source form.
4034
4035 @item ^-gnath^/HELP^
4036 @cindex @option{^-gnath^/HELP^} (@command{gcc})
4037 Output usage information. The output is written to @file{stdout}.
4038
4039 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
4040 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
4041 Identifier character set
4042 @ifclear vms
4043 (@var{c}=1/2/3/4/8/9/p/f/n/w).
4044 @end ifclear
4045 For details of the possible selections for @var{c},
4046 see @ref{Character Set Control}.
4047
4048 @item ^-gnatI^/IGNORE_REP_CLAUSES^
4049 @cindex @option{^-gnatI^IGNORE_REP_CLAUSES^} (@command{gcc})
4050 Ignore representation clauses. When this switch is used,
4051 representation clauses are treated as comments. This is useful
4052 when initially porting code where you want to ignore rep clause
4053 problems, and also for compiling foreign code (particularly
4054 for use with ASIS). The representation clauses that are ignored
4055 are: enumeration_representation_clause, record_representation_clause,
4056 and attribute_definition_clause for the following attributes:
4057 Address, Alignment, Bit_Order, Component_Size, Machine_Radix,
4058 Object_Size, Size, Small, Stream_Size, and Value_Size.
4059 Note that this option should be used only for compiling -- the
4060 code is likely to malfunction at run time.
4061
4062 @item -gnatjnn
4063 @cindex @option{-gnatjnn} (@command{gcc})
4064 Reformat error messages to fit on nn character lines
4065
4066 @item -gnatk=@var{n}
4067 @cindex @option{-gnatk} (@command{gcc})
4068 Limit file names to @var{n} (1-999) characters ^(@code{k} = krunch)^^.
4069
4070 @item -gnatl
4071 @cindex @option{-gnatl} (@command{gcc})
4072 Output full source listing with embedded error messages.
4073
4074 @item -gnatL
4075 @cindex @option{-gnatL} (@command{gcc})
4076 Used in conjunction with -gnatG or -gnatD to intersperse original
4077 source lines (as comment lines with line numbers) in the expanded
4078 source output.
4079
4080 @item -gnatm=@var{n}
4081 @cindex @option{-gnatm} (@command{gcc})
4082 Limit number of detected error or warning messages to @var{n}
4083 where @var{n} is in the range 1..999999. The default setting if
4084 no switch is given is 9999. If the number of warnings reaches this
4085 limit, then a message is output and further warnings are suppressed,
4086 but the compilation is continued. If the number of error messages
4087 reaches this limit, then a message is output and the compilation
4088 is abandoned. The equal sign here is optional. A value of zero
4089 means that no limit applies.
4090
4091 @item -gnatn[12]
4092 @cindex @option{-gnatn} (@command{gcc})
4093 Activate inlining for subprograms for which pragma @code{Inline} is
4094 specified. This inlining is performed by the GCC back-end. An optional
4095 digit sets the inlining level: 1 for moderate inlining across modules
4096 or 2 for full inlining across modules. If no inlining level is specified,
4097 the compiler will pick it based on the optimization level.
4098
4099 @item -gnatN
4100 @cindex @option{-gnatN} (@command{gcc})
4101 Activate front end inlining for subprograms for which
4102 pragma @code{Inline} is specified. This inlining is performed
4103 by the front end and will be visible in the
4104 @option{-gnatG} output.
4105
4106 When using a gcc-based back end (in practice this means using any version
4107 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
4108 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
4109 Historically front end inlining was more extensive than the gcc back end
4110 inlining, but that is no longer the case.
4111
4112 @item -gnato??
4113 @cindex @option{-gnato??} (@command{gcc})
4114 Set default mode for handling generation of code to avoid intermediate
4115 arithmetic overflow. Here `@code{??}' is two digits, a
4116 single digit, or nothing. Each digit is one of the digits `@code{1}'
4117 through `@code{3}':
4118
4119 @itemize @bullet
4120 @item @code{1}:
4121 all intermediate overflows checked against base type (@code{STRICT})
4122 @item @code{2}:
4123 minimize intermediate overflows (@code{MINIMIZED})
4124 @item @code{3}:
4125 eliminate intermediate overflows (@code{ELIMINATED})
4126 @end itemize
4127
4128 If only one digit appears then it applies to all
4129 cases; if two digits are given, then the first applies outside
4130 assertions, and the second within assertions.
4131
4132 If no digits follow the @option{-gnato}, then it is equivalent to
4133 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
4134 causing all intermediate overflows to be handled in strict mode.
4135
4136 This switch also causes arithmetic overflow checking to be performed
4137 (as though pragma @code{Unsuppress (Overflow_Mode)} has been specified.
4138
4139 The default if no option @option{-gnato} is given is that overflow handling
4140 is in @code{STRICT} mode (computations done using the base type), and that
4141 overflow checking is suppressed.
4142
4143 Note that division by zero is a separate check that is not
4144 controlled by this switch (division by zero checking is on by default).
4145
4146 See also @ref{Specifying the Desired Mode}.
4147
4148 @item -gnatp
4149 @cindex @option{-gnatp} (@command{gcc})
4150 Suppress all checks. See @ref{Run-Time Checks} for details. This switch
4151 has no effect if cancelled by a subsequent @option{-gnat-p} switch.
4152
4153 @item -gnat-p
4154 @cindex @option{-gnat-p} (@command{gcc})
4155 Cancel effect of previous @option{-gnatp} switch.
4156
4157 @item -gnatP
4158 @cindex @option{-gnatP} (@command{gcc})
4159 Enable polling. This is required on some systems (notably Windows NT) to
4160 obtain asynchronous abort and asynchronous transfer of control capability.
4161 @xref{Pragma Polling,,, gnat_rm, GNAT Reference Manual}, for full
4162 details.
4163
4164 @item -gnatq
4165 @cindex @option{-gnatq} (@command{gcc})
4166 Don't quit. Try semantics, even if parse errors.
4167
4168 @item -gnatQ
4169 @cindex @option{-gnatQ} (@command{gcc})
4170 Don't quit. Generate @file{ALI} and tree files even if illegalities.
4171
4172 @item -gnatr
4173 @cindex @option{-gnatr} (@command{gcc})
4174 Treat pragma Restrictions as Restriction_Warnings.
4175
4176 @item ^-gnatR@r{[}0@r{/}1@r{/}2@r{/}3@r{[}s@r{]]}^/REPRESENTATION_INFO^
4177 @cindex @option{-gnatR} (@command{gcc})
4178 Output representation information for declared types and objects.
4179 Note that this switch is not allowed if a previous @code{-gnatD} switch has
4180 been given, since these two switches are not compatible. It is also not allowed
4181 if a previous @code{-gnatc} switch has been given, since we must be generating
4182 code to be able to determine representation information.
4183
4184 @item ^-gnatRm[s]^/REPRESENTATION_INFO^
4185 Output convention and parameter passing mechanisms for all subprograms.
4186 This form is also incompatible with the use of @code{-gnatc}.
4187
4188 @item -gnats
4189 @cindex @option{-gnats} (@command{gcc})
4190 Syntax check only.
4191
4192 @item -gnatS
4193 @cindex @option{-gnatS} (@command{gcc})
4194 Print package Standard.
4195
4196 @item -gnatt
4197 @cindex @option{-gnatt} (@command{gcc})
4198 Generate tree output file.
4199
4200 @item ^-gnatT^/TABLE_MULTIPLIER=^@var{nnn}
4201 @cindex @option{^-gnatT^/TABLE_MULTIPLIER^} (@command{gcc})
4202 All compiler tables start at @var{nnn} times usual starting size.
4203
4204 @item -gnatu
4205 @cindex @option{-gnatu} (@command{gcc})
4206 List units for this compilation.
4207
4208 @item -gnatU
4209 @cindex @option{-gnatU} (@command{gcc})
4210 Tag all error messages with the unique string ``error:''
4211
4212 @item -gnatv
4213 @cindex @option{-gnatv} (@command{gcc})
4214 Verbose mode. Full error output with source lines to @file{stdout}.
4215
4216 @item -gnatV
4217 @cindex @option{-gnatV} (@command{gcc})
4218 Control level of validity checking (@pxref{Validity Checking}).
4219
4220 @item ^-gnatw@var{xxx}^/WARNINGS=(@var{option}@r{[},@dots{}@r{]})^
4221 @cindex @option{^-gnatw^/WARNINGS^} (@command{gcc})
4222 Warning mode where
4223 ^@var{xxx} is a string of option letters that^the list of options^ denotes
4224 the exact warnings that
4225 are enabled or disabled (@pxref{Warning Message Control}).
4226
4227 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
4228 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
4229 Wide character encoding method
4230 @ifclear vms
4231 (@var{e}=n/h/u/s/e/8).
4232 @end ifclear
4233 @ifset vms
4234 (@var{e}=@code{BRACKETS, NONE, HEX, UPPER, SHIFT_JIS, EUC, UTF8})
4235 @end ifset
4236
4237 @item -gnatx
4238 @cindex @option{-gnatx} (@command{gcc})
4239 Suppress generation of cross-reference information.
4240
4241 @item -gnatX
4242 @cindex @option{-gnatX} (@command{gcc})
4243 Enable GNAT implementation extensions and latest Ada version.
4244
4245 @item ^-gnaty^/STYLE_CHECKS=(option,option@dots{})^
4246 @cindex @option{^-gnaty^/STYLE_CHECKS^} (@command{gcc})
4247 Enable built-in style checks (@pxref{Style Checking}).
4248
4249 @item ^-gnatz^/DISTRIBUTION_STUBS=^@var{m}
4250 @cindex @option{^-gnatz^/DISTRIBUTION_STUBS^} (@command{gcc})
4251 Distribution stub generation and compilation
4252 @ifclear vms
4253 (@var{m}=r/c for receiver/caller stubs).
4254 @end ifclear
4255 @ifset vms
4256 (@var{m}=@code{RECEIVER} or @code{CALLER} to specify the type of stubs
4257 to be generated and compiled).
4258 @end ifset
4259
4260 @item ^-I^/SEARCH=^@var{dir}
4261 @cindex @option{^-I^/SEARCH^} (@command{gcc})
4262 @cindex RTL
4263 Direct GNAT to search the @var{dir} directory for source files needed by
4264 the current compilation
4265 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4266
4267 @item ^-I-^/NOCURRENT_DIRECTORY^
4268 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gcc})
4269 @cindex RTL
4270 Except for the source file named in the command line, do not look for source
4271 files in the directory containing the source file named in the command line
4272 (@pxref{Search Paths and the Run-Time Library (RTL)}).
4273
4274 @ifclear vms
4275 @item -mbig-switch
4276 @cindex @option{-mbig-switch} (@command{gcc})
4277 @cindex @code{case} statement (effect of @option{-mbig-switch} option)
4278 This standard gcc switch causes the compiler to use larger offsets in its
4279 jump table representation for @code{case} statements.
4280 This may result in less efficient code, but is sometimes necessary
4281 (for example on HP-UX targets)
4282 @cindex HP-UX and @option{-mbig-switch} option
4283 in order to compile large and/or nested @code{case} statements.
4284
4285 @item -o @var{file}
4286 @cindex @option{-o} (@command{gcc})
4287 This switch is used in @command{gcc} to redirect the generated object file
4288 and its associated ALI file. Beware of this switch with GNAT, because it may
4289 cause the object file and ALI file to have different names which in turn
4290 may confuse the binder and the linker.
4291 @end ifclear
4292
4293 @item -nostdinc
4294 @cindex @option{-nostdinc} (@command{gcc})
4295 Inhibit the search of the default location for the GNAT Run Time
4296 Library (RTL) source files.
4297
4298 @item -nostdlib
4299 @cindex @option{-nostdlib} (@command{gcc})
4300 Inhibit the search of the default location for the GNAT Run Time
4301 Library (RTL) ALI files.
4302
4303 @ifclear vms
4304 @c @item -O@ovar{n}
4305 @c Expanding @ovar macro inline (explanation in macro def comments)
4306 @item -O@r{[}@var{n}@r{]}
4307 @cindex @option{-O} (@command{gcc})
4308 @var{n} controls the optimization level.
4309
4310 @table @asis
4311 @item n = 0
4312 No optimization, the default setting if no @option{-O} appears
4313
4314 @item n = 1
4315 Normal optimization, the default if you specify @option{-O} without
4316 an operand. A good compromise between code quality and compilation
4317 time.
4318
4319 @item n = 2
4320 Extensive optimization, may improve execution time, possibly at the cost of
4321 substantially increased compilation time.
4322
4323 @item n = 3
4324 Same as @option{-O2}, and also includes inline expansion for small subprograms
4325 in the same unit.
4326
4327 @item n = s
4328 Optimize space usage
4329 @end table
4330
4331 @noindent
4332 See also @ref{Optimization Levels}.
4333 @end ifclear
4334
4335 @ifset vms
4336 @item /NOOPTIMIZE
4337 @cindex @option{/NOOPTIMIZE} (@code{GNAT COMPILE})
4338 Equivalent to @option{/OPTIMIZE=NONE}.
4339 This is the default behavior in the absence of an @option{/OPTIMIZE}
4340 qualifier.
4341
4342 @item /OPTIMIZE@r{[}=(keyword@r{[},@dots{}@r{]})@r{]}
4343 @cindex @option{/OPTIMIZE} (@code{GNAT COMPILE})
4344 Selects the level of optimization for your program. The supported
4345 keywords are as follows:
4346 @table @code
4347 @item ALL
4348 Perform most optimizations, including those that
4349 are expensive.
4350 This is the default if the @option{/OPTIMIZE} qualifier is supplied
4351 without keyword options.
4352
4353 @item NONE
4354 Do not do any optimizations. Same as @code{/NOOPTIMIZE}.
4355
4356 @item SOME
4357 Perform some optimizations, but omit ones that are costly.
4358
4359 @item DEVELOPMENT
4360 Same as @code{SOME}.
4361
4362 @item INLINING
4363 Full optimization as in @option{/OPTIMIZE=ALL}, and also attempts
4364 automatic inlining of small subprograms within a unit
4365
4366 @item UNROLL_LOOPS
4367 Try to unroll loops. This keyword may be specified together with
4368 any keyword above other than @code{NONE}. Loop unrolling
4369 usually, but not always, improves the performance of programs.
4370
4371 @item SPACE
4372 Optimize space usage
4373 @end table
4374
4375 @noindent
4376 See also @ref{Optimization Levels}.
4377 @end ifset
4378
4379 @ifclear vms
4380 @item -pass-exit-codes
4381 @cindex @option{-pass-exit-codes} (@command{gcc})
4382 Catch exit codes from the compiler and use the most meaningful as
4383 exit status.
4384 @end ifclear
4385
4386 @item --RTS=@var{rts-path}
4387 @cindex @option{--RTS} (@command{gcc})
4388 Specifies the default location of the runtime library. Same meaning as the
4389 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
4390
4391 @item ^-S^/ASM^
4392 @cindex @option{^-S^/ASM^} (@command{gcc})
4393 ^Used in place of @option{-c} to^Used to^
4394 cause the assembler source file to be
4395 generated, using @file{^.s^.S^} as the extension,
4396 instead of the object file.
4397 This may be useful if you need to examine the generated assembly code.
4398
4399 @item ^-fverbose-asm^/VERBOSE_ASM^
4400 @cindex @option{^-fverbose-asm^/VERBOSE_ASM^} (@command{gcc})
4401 ^Used in conjunction with @option{-S}^Used in place of @option{/ASM}^
4402 to cause the generated assembly code file to be annotated with variable
4403 names, making it significantly easier to follow.
4404
4405 @item ^-v^/VERBOSE^
4406 @cindex @option{^-v^/VERBOSE^} (@command{gcc})
4407 Show commands generated by the @command{gcc} driver. Normally used only for
4408 debugging purposes or if you need to be sure what version of the
4409 compiler you are executing.
4410
4411 @ifclear vms
4412 @item -V @var{ver}
4413 @cindex @option{-V} (@command{gcc})
4414 Execute @var{ver} version of the compiler. This is the @command{gcc}
4415 version, not the GNAT version.
4416 @end ifclear
4417
4418 @item ^-w^/NO_BACK_END_WARNINGS^
4419 @cindex @option{-w} (@command{gcc})
4420 Turn off warnings generated by the back end of the compiler. Use of
4421 this switch also causes the default for front end warnings to be set
4422 to suppress (as though @option{-gnatws} had appeared at the start of
4423 the options).
4424
4425 @end table
4426
4427 @ifclear vms
4428 @c Combining qualifiers does not work on VMS
4429 You may combine a sequence of GNAT switches into a single switch. For
4430 example, the combined switch
4431
4432 @cindex Combining GNAT switches
4433 @smallexample
4434 -gnatofi3
4435 @end smallexample
4436
4437 @noindent
4438 is equivalent to specifying the following sequence of switches:
4439
4440 @smallexample
4441 -gnato -gnatf -gnati3
4442 @end smallexample
4443 @end ifclear
4444
4445 @noindent
4446 The following restrictions apply to the combination of switches
4447 in this manner:
4448
4449 @itemize @bullet
4450 @item
4451 The switch @option{-gnatc} if combined with other switches must come
4452 first in the string.
4453
4454 @item
4455 The switch @option{-gnats} if combined with other switches must come
4456 first in the string.
4457
4458 @item
4459 The switches
4460 ^^@option{/DISTRIBUTION_STUBS=},^
4461 @option{-gnatzc} and @option{-gnatzr} may not be combined with any other
4462 switches, and only one of them may appear in the command line.
4463
4464 @item
4465 The switch @option{-gnat-p} may not be combined with any other switch.
4466
4467 @ifclear vms
4468 @item
4469 Once a ``y'' appears in the string (that is a use of the @option{-gnaty}
4470 switch), then all further characters in the switch are interpreted
4471 as style modifiers (see description of @option{-gnaty}).
4472
4473 @item
4474 Once a ``d'' appears in the string (that is a use of the @option{-gnatd}
4475 switch), then all further characters in the switch are interpreted
4476 as debug flags (see description of @option{-gnatd}).
4477
4478 @item
4479 Once a ``w'' appears in the string (that is a use of the @option{-gnatw}
4480 switch), then all further characters in the switch are interpreted
4481 as warning mode modifiers (see description of @option{-gnatw}).
4482
4483 @item
4484 Once a ``V'' appears in the string (that is a use of the @option{-gnatV}
4485 switch), then all further characters in the switch are interpreted
4486 as validity checking options (@pxref{Validity Checking}).
4487
4488 @item
4489 Option ``em'', ``ec'', ``ep'', ``l='' and ``R'' must be the last options in
4490 a combined list of options.
4491 @end ifclear
4492 @end itemize
4493
4494 @node Output and Error Message Control
4495 @subsection Output and Error Message Control
4496 @findex stderr
4497
4498 @noindent
4499 The standard default format for error messages is called ``brief format''.
4500 Brief format messages are written to @file{stderr} (the standard error
4501 file) and have the following form:
4502
4503 @smallexample
4504 e.adb:3:04: Incorrect spelling of keyword "function"
4505 e.adb:4:20: ";" should be "is"
4506 @end smallexample
4507
4508 @noindent
4509 The first integer after the file name is the line number in the file,
4510 and the second integer is the column number within the line.
4511 @ifclear vms
4512 @code{GPS} can parse the error messages
4513 and point to the referenced character.
4514 @end ifclear
4515 The following switches provide control over the error message
4516 format:
4517
4518 @table @option
4519 @c !sort!
4520 @item -gnatv
4521 @cindex @option{-gnatv} (@command{gcc})
4522 @findex stdout
4523 @ifclear vms
4524 The v stands for verbose.
4525 @end ifclear
4526 The effect of this setting is to write long-format error
4527 messages to @file{stdout} (the standard output file.
4528 The same program compiled with the
4529 @option{-gnatv} switch would generate:
4530
4531 @smallexample
4532 @cartouche
4533 3. funcion X (Q : Integer)
4534 |
4535 >>> Incorrect spelling of keyword "function"
4536 4. return Integer;
4537 |
4538 >>> ";" should be "is"
4539 @end cartouche
4540 @end smallexample
4541
4542 @noindent
4543 The vertical bar indicates the location of the error, and the @samp{>>>}
4544 prefix can be used to search for error messages. When this switch is
4545 used the only source lines output are those with errors.
4546
4547 @item -gnatl
4548 @cindex @option{-gnatl} (@command{gcc})
4549 @ifclear vms
4550 The @code{l} stands for list.
4551 @end ifclear
4552 This switch causes a full listing of
4553 the file to be generated. In the case where a body is
4554 compiled, the corresponding spec is also listed, along
4555 with any subunits. Typical output from compiling a package
4556 body @file{p.adb} might look like:
4557
4558 @smallexample @c ada
4559 @cartouche
4560 Compiling: p.adb
4561
4562 1. package body p is
4563 2. procedure a;
4564 3. procedure a is separate;
4565 4. begin
4566 5. null
4567 |
4568 >>> missing ";"
4569
4570 6. end;
4571
4572 Compiling: p.ads
4573
4574 1. package p is
4575 2. pragma Elaborate_Body
4576 |
4577 >>> missing ";"
4578
4579 3. end p;
4580
4581 Compiling: p-a.adb
4582
4583 1. separate p
4584 |
4585 >>> missing "("
4586
4587 2. procedure a is
4588 3. begin
4589 4. null
4590 |
4591 >>> missing ";"
4592
4593 5. end;
4594 @end cartouche
4595 @end smallexample
4596
4597 @noindent
4598 @findex stderr
4599 When you specify the @option{-gnatv} or @option{-gnatl} switches and
4600 standard output is redirected, a brief summary is written to
4601 @file{stderr} (standard error) giving the number of error messages and
4602 warning messages generated.
4603
4604 @item ^-gnatl^/OUTPUT_FILE^=file
4605 @cindex @option{^-gnatl^/OUTPUT_FILE^=fname} (@command{gcc})
4606 This has the same effect as @option{-gnatl} except that the output is
4607 written to a file instead of to standard output. If the given name
4608 @file{fname} does not start with a period, then it is the full name
4609 of the file to be written. If @file{fname} is an extension, it is
4610 appended to the name of the file being compiled. For example, if
4611 file @file{xyz.adb} is compiled with @option{^-gnatl^/OUTPUT_FILE^=.lst},
4612 then the output is written to file ^xyz.adb.lst^xyz.adb_lst^.
4613
4614 @item -gnatU
4615 @cindex @option{-gnatU} (@command{gcc})
4616 This switch forces all error messages to be preceded by the unique
4617 string ``error:''. This means that error messages take a few more
4618 characters in space, but allows easy searching for and identification
4619 of error messages.
4620
4621 @item -gnatb
4622 @cindex @option{-gnatb} (@command{gcc})
4623 @ifclear vms
4624 The @code{b} stands for brief.
4625 @end ifclear
4626 This switch causes GNAT to generate the
4627 brief format error messages to @file{stderr} (the standard error
4628 file) as well as the verbose
4629 format message or full listing (which as usual is written to
4630 @file{stdout} (the standard output file).
4631
4632 @item -gnatm=@var{n}
4633 @cindex @option{-gnatm} (@command{gcc})
4634 @ifclear vms
4635 The @code{m} stands for maximum.
4636 @end ifclear
4637 @var{n} is a decimal integer in the
4638 range of 1 to 999999 and limits the number of error or warning
4639 messages to be generated. For example, using
4640 @option{-gnatm2} might yield
4641
4642 @smallexample
4643 e.adb:3:04: Incorrect spelling of keyword "function"
4644 e.adb:5:35: missing ".."
4645 fatal error: maximum number of errors detected
4646 compilation abandoned
4647 @end smallexample
4648
4649 @noindent
4650 The default setting if
4651 no switch is given is 9999. If the number of warnings reaches this
4652 limit, then a message is output and further warnings are suppressed,
4653 but the compilation is continued. If the number of error messages
4654 reaches this limit, then a message is output and the compilation
4655 is abandoned. A value of zero means that no limit applies.
4656
4657 @noindent
4658 Note that the equal sign is optional, so the switches
4659 @option{-gnatm2} and @option{-gnatm=2} are equivalent.
4660
4661 @item -gnatf
4662 @cindex @option{-gnatf} (@command{gcc})
4663 @cindex Error messages, suppressing
4664 @ifclear vms
4665 The @code{f} stands for full.
4666 @end ifclear
4667 Normally, the compiler suppresses error messages that are likely to be
4668 redundant. This switch causes all error
4669 messages to be generated. In particular, in the case of
4670 references to undefined variables. If a given variable is referenced
4671 several times, the normal format of messages is
4672 @smallexample
4673 e.adb:7:07: "V" is undefined (more references follow)
4674 @end smallexample
4675
4676 @noindent
4677 where the parenthetical comment warns that there are additional
4678 references to the variable @code{V}. Compiling the same program with the
4679 @option{-gnatf} switch yields
4680
4681 @smallexample
4682 e.adb:7:07: "V" is undefined
4683 e.adb:8:07: "V" is undefined
4684 e.adb:8:12: "V" is undefined
4685 e.adb:8:16: "V" is undefined
4686 e.adb:9:07: "V" is undefined
4687 e.adb:9:12: "V" is undefined
4688 @end smallexample
4689
4690 @noindent
4691 The @option{-gnatf} switch also generates additional information for
4692 some error messages. Some examples are:
4693
4694 @itemize @bullet
4695 @item
4696 Details on possibly non-portable unchecked conversion
4697 @item
4698 List possible interpretations for ambiguous calls
4699 @item
4700 Additional details on incorrect parameters
4701 @end itemize
4702
4703 @item -gnatjnn
4704 @cindex @option{-gnatjnn} (@command{gcc})
4705 In normal operation mode (or if @option{-gnatj0} is used), then error messages
4706 with continuation lines are treated as though the continuation lines were
4707 separate messages (and so a warning with two continuation lines counts as
4708 three warnings, and is listed as three separate messages).
4709
4710 If the @option{-gnatjnn} switch is used with a positive value for nn, then
4711 messages are output in a different manner. A message and all its continuation
4712 lines are treated as a unit, and count as only one warning or message in the
4713 statistics totals. Furthermore, the message is reformatted so that no line
4714 is longer than nn characters.
4715
4716 @item -gnatq
4717 @cindex @option{-gnatq} (@command{gcc})
4718 @ifclear vms
4719 The @code{q} stands for quit (really ``don't quit'').
4720 @end ifclear
4721 In normal operation mode, the compiler first parses the program and
4722 determines if there are any syntax errors. If there are, appropriate
4723 error messages are generated and compilation is immediately terminated.
4724 This switch tells
4725 GNAT to continue with semantic analysis even if syntax errors have been
4726 found. This may enable the detection of more errors in a single run. On
4727 the other hand, the semantic analyzer is more likely to encounter some
4728 internal fatal error when given a syntactically invalid tree.
4729
4730 @item -gnatQ
4731 @cindex @option{-gnatQ} (@command{gcc})
4732 In normal operation mode, the @file{ALI} file is not generated if any
4733 illegalities are detected in the program. The use of @option{-gnatQ} forces
4734 generation of the @file{ALI} file. This file is marked as being in
4735 error, so it cannot be used for binding purposes, but it does contain
4736 reasonably complete cross-reference information, and thus may be useful
4737 for use by tools (e.g., semantic browsing tools or integrated development
4738 environments) that are driven from the @file{ALI} file. This switch
4739 implies @option{-gnatq}, since the semantic phase must be run to get a
4740 meaningful ALI file.
4741
4742 In addition, if @option{-gnatt} is also specified, then the tree file is
4743 generated even if there are illegalities. It may be useful in this case
4744 to also specify @option{-gnatq} to ensure that full semantic processing
4745 occurs. The resulting tree file can be processed by ASIS, for the purpose
4746 of providing partial information about illegal units, but if the error
4747 causes the tree to be badly malformed, then ASIS may crash during the
4748 analysis.
4749
4750 When @option{-gnatQ} is used and the generated @file{ALI} file is marked as
4751 being in error, @command{gnatmake} will attempt to recompile the source when it
4752 finds such an @file{ALI} file, including with switch @option{-gnatc}.
4753
4754 Note that @option{-gnatQ} has no effect if @option{-gnats} is specified,
4755 since ALI files are never generated if @option{-gnats} is set.
4756
4757 @end table
4758
4759 @node Warning Message Control
4760 @subsection Warning Message Control
4761 @cindex Warning messages
4762 @noindent
4763 In addition to error messages, which correspond to illegalities as defined
4764 in the Ada Reference Manual, the compiler detects two kinds of warning
4765 situations.
4766
4767 First, the compiler considers some constructs suspicious and generates a
4768 warning message to alert you to a possible error. Second, if the
4769 compiler detects a situation that is sure to raise an exception at
4770 run time, it generates a warning message. The following shows an example
4771 of warning messages:
4772 @smallexample
4773 e.adb:4:24: warning: creation of object may raise Storage_Error
4774 e.adb:10:17: warning: static value out of range
4775 e.adb:10:17: warning: "Constraint_Error" will be raised at run time
4776 @end smallexample
4777
4778 @noindent
4779 GNAT considers a large number of situations as appropriate
4780 for the generation of warning messages. As always, warnings are not
4781 definite indications of errors. For example, if you do an out-of-range
4782 assignment with the deliberate intention of raising a
4783 @code{Constraint_Error} exception, then the warning that may be
4784 issued does not indicate an error. Some of the situations for which GNAT
4785 issues warnings (at least some of the time) are given in the following
4786 list. This list is not complete, and new warnings are often added to
4787 subsequent versions of GNAT. The list is intended to give a general idea
4788 of the kinds of warnings that are generated.
4789
4790 @itemize @bullet
4791 @item
4792 Possible infinitely recursive calls
4793
4794 @item
4795 Out-of-range values being assigned
4796
4797 @item
4798 Possible order of elaboration problems
4799
4800 @item
4801 Size not a multiple of alignment for a record type
4802
4803 @item
4804 Assertions (pragma Assert) that are sure to fail
4805
4806 @item
4807 Unreachable code
4808
4809 @item
4810 Address clauses with possibly unaligned values, or where an attempt is
4811 made to overlay a smaller variable with a larger one.
4812
4813 @item
4814 Fixed-point type declarations with a null range
4815
4816 @item
4817 Direct_IO or Sequential_IO instantiated with a type that has access values
4818
4819 @item
4820 Variables that are never assigned a value
4821
4822 @item
4823 Variables that are referenced before being initialized
4824
4825 @item
4826 Task entries with no corresponding @code{accept} statement
4827
4828 @item
4829 Duplicate accepts for the same task entry in a @code{select}
4830
4831 @item
4832 Objects that take too much storage
4833
4834 @item
4835 Unchecked conversion between types of differing sizes
4836
4837 @item
4838 Missing @code{return} statement along some execution path in a function
4839
4840 @item
4841 Incorrect (unrecognized) pragmas
4842
4843 @item
4844 Incorrect external names
4845
4846 @item
4847 Allocation from empty storage pool
4848
4849 @item
4850 Potentially blocking operation in protected type
4851
4852 @item
4853 Suspicious parenthesization of expressions
4854
4855 @item
4856 Mismatching bounds in an aggregate
4857
4858 @item
4859 Attempt to return local value by reference
4860
4861 @item
4862 Premature instantiation of a generic body
4863
4864 @item
4865 Attempt to pack aliased components
4866
4867 @item
4868 Out of bounds array subscripts
4869
4870 @item
4871 Wrong length on string assignment
4872
4873 @item
4874 Violations of style rules if style checking is enabled
4875
4876 @item
4877 Unused @code{with} clauses
4878
4879 @item
4880 @code{Bit_Order} usage that does not have any effect
4881
4882 @item
4883 @code{Standard.Duration} used to resolve universal fixed expression
4884
4885 @item
4886 Dereference of possibly null value
4887
4888 @item
4889 Declaration that is likely to cause storage error
4890
4891 @item
4892 Internal GNAT unit @code{with}'ed by application unit
4893
4894 @item
4895 Values known to be out of range at compile time
4896
4897 @item
4898 Unreferenced or unmodified variables. Note that a special
4899 exemption applies to variables which contain any of the substrings
4900 @code{DISCARD, DUMMY, IGNORE, JUNK, UNUSED}, in any casing. Such variables
4901 are considered likely to be intentionally used in a situation where
4902 otherwise a warning would be given, so warnings of this kind are
4903 always suppressed for such variables.
4904
4905 @item
4906 Address overlays that could clobber memory
4907
4908 @item
4909 Unexpected initialization when address clause present
4910
4911 @item
4912 Bad alignment for address clause
4913
4914 @item
4915 Useless type conversions
4916
4917 @item
4918 Redundant assignment statements and other redundant constructs
4919
4920 @item
4921 Useless exception handlers
4922
4923 @item
4924 Accidental hiding of name by child unit
4925
4926 @item
4927 Access before elaboration detected at compile time
4928
4929 @item
4930 A range in a @code{for} loop that is known to be null or might be null
4931
4932 @end itemize
4933
4934 @noindent
4935 The following section lists compiler switches that are available
4936 to control the handling of warning messages. It is also possible
4937 to exercise much finer control over what warnings are issued and
4938 suppressed using the GNAT pragma Warnings, @xref{Pragma Warnings,,,
4939 gnat_rm, GNAT Reference manual}.
4940
4941 @table @option
4942 @c !sort!
4943 @item -gnatwa
4944 @emph{Activate most optional warnings.}
4945 @cindex @option{-gnatwa} (@command{gcc})
4946 This switch activates most optional warning messages. See the remaining list
4947 in this section for details on optional warning messages that can be
4948 individually controlled. The warnings that are not turned on by this
4949 switch are:
4950 @option{-gnatwd} (implicit dereferencing),
4951 @option{-gnatwh} (hiding),
4952 @option{-gnatw.d} (tag warnings with -gnatw switch)
4953 @option{-gnatw.h} (holes (gaps) in record layouts)
4954 @option{-gnatw.i} (overlapping actuals),
4955 @option{-gnatw.k} (redefinition of names in standard),
4956 @option{-gnatwl} (elaboration warnings),
4957 @option{-gnatw.l} (inherited aspects),
4958 @option{-gnatw.o} (warn on values set by out parameters ignored),
4959 @option{-gnatwt} (tracking of deleted conditional code)
4960 and @option{-gnatw.u} (unordered enumeration),
4961 All other optional warnings are turned on.
4962
4963 @item -gnatwA
4964 @emph{Suppress all optional errors.}
4965 @cindex @option{-gnatwA} (@command{gcc})
4966 This switch suppresses all optional warning messages, see remaining list
4967 in this section for details on optional warning messages that can be
4968 individually controlled. Note that unlike switch @option{-gnatws}, the
4969 use of switch @option{-gnatwA} does not suppress warnings that are
4970 normally given unconditionally and cannot be individually controlled
4971 (for example, the warning about a missing exit path in a function).
4972 Also, again unlike switch @option{-gnatws}, warnings suppressed by
4973 the use of switch @option{-gnatwA} can be individually turned back
4974 on. For example the use of switch @option{-gnatwA} followed by
4975 switch @option{-gnatwd} will suppress all optional warnings except
4976 the warnings for implicit dereferencing.
4977
4978 @item -gnatw.a
4979 @emph{Activate warnings on failing assertions.}
4980 @cindex @option{-gnatw.a} (@command{gcc})
4981 @cindex Assert failures
4982 This switch activates warnings for assertions where the compiler can tell at
4983 compile time that the assertion will fail. Note that this warning is given
4984 even if assertions are disabled. The default is that such warnings are
4985 generated.
4986
4987 @item -gnatw.A
4988 @emph{Suppress warnings on failing assertions.}
4989 @cindex @option{-gnatw.A} (@command{gcc})
4990 @cindex Assert failures
4991 This switch suppresses warnings for assertions where the compiler can tell at
4992 compile time that the assertion will fail.
4993
4994 @item -gnatwb
4995 @emph{Activate warnings on bad fixed values.}
4996 @cindex @option{-gnatwb} (@command{gcc})
4997 @cindex Bad fixed values
4998 @cindex Fixed-point Small value
4999 @cindex Small value
5000 This switch activates warnings for static fixed-point expressions whose
5001 value is not an exact multiple of Small. Such values are implementation
5002 dependent, since an implementation is free to choose either of the multiples
5003 that surround the value. GNAT always chooses the closer one, but this is not
5004 required behavior, and it is better to specify a value that is an exact
5005 multiple, ensuring predictable execution. The default is that such warnings
5006 are not generated.
5007
5008 @item -gnatwB
5009 @emph{Suppress warnings on bad fixed values.}
5010 @cindex @option{-gnatwB} (@command{gcc})
5011 This switch suppresses warnings for static fixed-point expressions whose
5012 value is not an exact multiple of Small.
5013
5014 @item -gnatw.b
5015 @emph{Activate warnings on biased representation.}
5016 @cindex @option{-gnatw.b} (@command{gcc})
5017 @cindex Biased representation
5018 This switch activates warnings when a size clause, value size clause, component
5019 clause, or component size clause forces the use of biased representation for an
5020 integer type (e.g. representing a range of 10..11 in a single bit by using 0/1
5021 to represent 10/11). The default is that such warnings are generated.
5022
5023 @item -gnatw.B
5024 @emph{Suppress warnings on biased representation.}
5025 @cindex @option{-gnatwB} (@command{gcc})
5026 This switch suppresses warnings for representation clauses that force the use
5027 of biased representation.
5028
5029 @item -gnatwc
5030 @emph{Activate warnings on conditionals.}
5031 @cindex @option{-gnatwc} (@command{gcc})
5032 @cindex Conditionals, constant
5033 This switch activates warnings for conditional expressions used in
5034 tests that are known to be True or False at compile time. The default
5035 is that such warnings are not generated.
5036 Note that this warning does
5037 not get issued for the use of boolean variables or constants whose
5038 values are known at compile time, since this is a standard technique
5039 for conditional compilation in Ada, and this would generate too many
5040 false positive warnings.
5041
5042 This warning option also activates a special test for comparisons using
5043 the operators ``>='' and`` <=''.
5044 If the compiler can tell that only the equality condition is possible,
5045 then it will warn that the ``>'' or ``<'' part of the test
5046 is useless and that the operator could be replaced by ``=''.
5047 An example would be comparing a @code{Natural} variable <= 0.
5048
5049 This warning option also generates warnings if
5050 one or both tests is optimized away in a membership test for integer
5051 values if the result can be determined at compile time. Range tests on
5052 enumeration types are not included, since it is common for such tests
5053 to include an end point.
5054
5055 This warning can also be turned on using @option{-gnatwa}.
5056
5057 @item -gnatwC
5058 @emph{Suppress warnings on conditionals.}
5059 @cindex @option{-gnatwC} (@command{gcc})
5060 This switch suppresses warnings for conditional expressions used in
5061 tests that are known to be True or False at compile time.
5062
5063 @item -gnatw.c
5064 @emph{Activate warnings on missing component clauses.}
5065 @cindex @option{-gnatw.c} (@command{gcc})
5066 @cindex Component clause, missing
5067 This switch activates warnings for record components where a record
5068 representation clause is present and has component clauses for the
5069 majority, but not all, of the components. A warning is given for each
5070 component for which no component clause is present.
5071
5072 This warning can also be turned on using @option{-gnatwa}.
5073
5074 @item -gnatw.C
5075 @emph{Suppress warnings on missing component clauses.}
5076 @cindex @option{-gnatwC} (@command{gcc})
5077 This switch suppresses warnings for record components that are
5078 missing a component clause in the situation described above.
5079
5080 @item -gnatwd
5081 @emph{Activate warnings on implicit dereferencing.}
5082 @cindex @option{-gnatwd} (@command{gcc})
5083 If this switch is set, then the use of a prefix of an access type
5084 in an indexed component, slice, or selected component without an
5085 explicit @code{.all} will generate a warning. With this warning
5086 enabled, access checks occur only at points where an explicit
5087 @code{.all} appears in the source code (assuming no warnings are
5088 generated as a result of this switch). The default is that such
5089 warnings are not generated.
5090 Note that @option{-gnatwa} does not affect the setting of
5091 this warning option.
5092
5093 @item -gnatwD
5094 @emph{Suppress warnings on implicit dereferencing.}
5095 @cindex @option{-gnatwD} (@command{gcc})
5096 @cindex Implicit dereferencing
5097 @cindex Dereferencing, implicit
5098 This switch suppresses warnings for implicit dereferences in
5099 indexed components, slices, and selected components.
5100
5101 @item -gnatw.d
5102 @emph{Activate tagging of warning and info messages.}
5103 @cindex @option{-gnatw.d} (@command{gcc})
5104 If this switch is set, then warning messages are tagged, with one of the
5105 following strings:
5106
5107 @table @option
5108
5109 @item [-gnatw?]
5110 Used to tag warnings controlled by the switch @option{-gnatwx} where x
5111 is a letter a-z.
5112
5113 @item [-gnatw.?]
5114 Used to tag warnings controlled by the switch @option{-gnatw.x} where x
5115 is a letter a-z.
5116
5117 @item [-gnatel]
5118 Used to tag elaboration information (info) messages generated when the
5119 static model of elaboration is used and the @option{-gnatel} switch is set.
5120
5121 @item [restriction warning]
5122 Used to tag warning messages for restriction violations, activated by use
5123 of the pragma @option{Restriction_Warnings}.
5124
5125 @item [warning-as-error]
5126 Used to tag warning messages that have been converted to error messages by
5127 use of the pragma Warning_As_Error. Note that such warnings are prefixed by
5128 the string "error: " rather than "warning: ".
5129
5130 @item [enabled by default]
5131 Used to tag all other warnings that are always given by default, unless
5132 warnings are completely suppressed using pragma @option{Warnings(Off)} or
5133 the switch @option{-gnatws}.
5134
5135 @end table
5136
5137 @item -gnatw.D
5138 @emph{Deactivate tagging of warning and info messages messages.}
5139 @cindex @option{-gnatw.d} (@command{gcc})
5140 If this switch is set, then warning messages return to the default
5141 mode in which warnings and info messages are not tagged as described above for
5142 @code{-gnatw.d}.
5143
5144 @item -gnatwe
5145 @emph{Treat warnings and style checks as errors.}
5146 @cindex @option{-gnatwe} (@command{gcc})
5147 @cindex Warnings, treat as error
5148 This switch causes warning messages and style check messages to be
5149 treated as errors.
5150 The warning string still appears, but the warning messages are counted
5151 as errors, and prevent the generation of an object file. Note that this
5152 is the only -gnatw switch that affects the handling of style check messages.
5153
5154 @item -gnatw.e
5155 @emph{Activate every optional warning}
5156 @cindex @option{-gnatw.e} (@command{gcc})
5157 @cindex Warnings, activate every optional warning
5158 This switch activates all optional warnings, including those which
5159 are not activated by @code{-gnatwa}. The use of this switch is not
5160 recommended for normal use. If you turn this switch on, it is almost
5161 certain that you will get large numbers of useless warnings. The
5162 warnings that are excluded from @code{-gnatwa} are typically highly
5163 specialized warnings that are suitable for use only in code that has
5164 been specifically designed according to specialized coding rules.
5165
5166 @item -gnatwf
5167 @emph{Activate warnings on unreferenced formals.}
5168 @cindex @option{-gnatwf} (@command{gcc})
5169 @cindex Formals, unreferenced
5170 This switch causes a warning to be generated if a formal parameter
5171 is not referenced in the body of the subprogram. This warning can
5172 also be turned on using @option{-gnatwa} or @option{-gnatwu}. The
5173 default is that these warnings are not generated.
5174
5175 @item -gnatwF
5176 @emph{Suppress warnings on unreferenced formals.}
5177 @cindex @option{-gnatwF} (@command{gcc})
5178 This switch suppresses warnings for unreferenced formal
5179 parameters. Note that the
5180 combination @option{-gnatwu} followed by @option{-gnatwF} has the
5181 effect of warning on unreferenced entities other than subprogram
5182 formals.
5183
5184 @item -gnatwg
5185 @emph{Activate warnings on unrecognized pragmas.}
5186 @cindex @option{-gnatwg} (@command{gcc})
5187 @cindex Pragmas, unrecognized
5188 This switch causes a warning to be generated if an unrecognized
5189 pragma is encountered. Apart from issuing this warning, the
5190 pragma is ignored and has no effect. This warning can
5191 also be turned on using @option{-gnatwa}. The default
5192 is that such warnings are issued (satisfying the Ada Reference
5193 Manual requirement that such warnings appear).
5194
5195 @item -gnatwG
5196 @emph{Suppress warnings on unrecognized pragmas.}
5197 @cindex @option{-gnatwG} (@command{gcc})
5198 This switch suppresses warnings for unrecognized pragmas.
5199
5200 @item -gnatw.g
5201 @emph{Warnings used for GNAT sources}
5202 @cindex @option{-gnatw.g} (@command{gcc})
5203 This switch sets the warning categories that are used by the standard
5204 GNAT style. Currently this is equivalent to
5205 @option{-gnatwAao.sI.C.V.X}
5206 but more warnings may be added in the future without advanced notice.
5207
5208 @item -gnatwh
5209 @emph{Activate warnings on hiding.}
5210 @cindex @option{-gnatwh} (@command{gcc})
5211 @cindex Hiding of Declarations
5212 This switch activates warnings on hiding declarations.
5213 A declaration is considered hiding
5214 if it is for a non-overloadable entity, and it declares an entity with the
5215 same name as some other entity that is directly or use-visible. The default
5216 is that such warnings are not generated.
5217 Note that @option{-gnatwa} does not affect the setting of this warning option.
5218
5219 @item -gnatwH
5220 @emph{Suppress warnings on hiding.}
5221 @cindex @option{-gnatwH} (@command{gcc})
5222 This switch suppresses warnings on hiding declarations.
5223
5224 @item -gnatw.h
5225 @emph{Activate warnings on holes/gaps in records.}
5226 @cindex @option{-gnatw.h} (@command{gcc})
5227 @cindex Record Representation (gaps)
5228 This switch activates warnings on component clauses in record
5229 representation clauses that leave holes (gaps) in the record layout.
5230 If this warning option is active, then record representation clauses
5231 should specify a contiguous layout, adding unused fill fields if needed.
5232 Note that @option{-gnatwa} does not affect the setting of this warning option.
5233
5234 @item -gnatw.H
5235 @emph{Suppress warnings on holes/gaps in records.}
5236 @cindex @option{-gnatw.H} (@command{gcc})
5237 This switch suppresses warnings on component clauses in record
5238 representation clauses that leave holes (haps) in the record layout.
5239
5240 @item -gnatwi
5241 @emph{Activate warnings on implementation units.}
5242 @cindex @option{-gnatwi} (@command{gcc})
5243 This switch activates warnings for a @code{with} of an internal GNAT
5244 implementation unit, defined as any unit from the @code{Ada},
5245 @code{Interfaces}, @code{GNAT},
5246 ^^@code{DEC},^ or @code{System}
5247 hierarchies that is not
5248 documented in either the Ada Reference Manual or the GNAT
5249 Programmer's Reference Manual. Such units are intended only
5250 for internal implementation purposes and should not be @code{with}'ed
5251 by user programs. The default is that such warnings are generated
5252 This warning can also be turned on using @option{-gnatwa}.
5253
5254 @item -gnatwI
5255 @emph{Disable warnings on implementation units.}
5256 @cindex @option{-gnatwI} (@command{gcc})
5257 This switch disables warnings for a @code{with} of an internal GNAT
5258 implementation unit.
5259
5260 @item -gnatw.i
5261 @emph{Activate warnings on overlapping actuals.}
5262 @cindex @option{-gnatw.i} (@command{gcc})
5263 This switch enables a warning on statically detectable overlapping actuals in
5264 a subprogram call, when one of the actuals is an in-out parameter, and the
5265 types of the actuals are not by-copy types. The warning is off by default,
5266 and is not included under -gnatwa.
5267
5268 @item -gnatw.I
5269 @emph{Disable warnings on overlapping actuals.}
5270 @cindex @option{-gnatw.I} (@command{gcc})
5271 This switch disables warnings on overlapping actuals in a call..
5272
5273 @item -gnatwj
5274 @emph{Activate warnings on obsolescent features (Annex J).}
5275 @cindex @option{-gnatwj} (@command{gcc})
5276 @cindex Features, obsolescent
5277 @cindex Obsolescent features
5278 If this warning option is activated, then warnings are generated for
5279 calls to subprograms marked with @code{pragma Obsolescent} and
5280 for use of features in Annex J of the Ada Reference Manual. In the
5281 case of Annex J, not all features are flagged. In particular use
5282 of the renamed packages (like @code{Text_IO}) and use of package
5283 @code{ASCII} are not flagged, since these are very common and
5284 would generate many annoying positive warnings. The default is that
5285 such warnings are not generated. This warning is also turned on by
5286 the use of @option{-gnatwa}.
5287
5288 In addition to the above cases, warnings are also generated for
5289 GNAT features that have been provided in past versions but which
5290 have been superseded (typically by features in the new Ada standard).
5291 For example, @code{pragma Ravenscar} will be flagged since its
5292 function is replaced by @code{pragma Profile(Ravenscar)}, and
5293 @code{pragma Interface_Name} will be flagged since its function
5294 is replaced by @code{pragma Import}.
5295
5296 Note that this warning option functions differently from the
5297 restriction @code{No_Obsolescent_Features} in two respects.
5298 First, the restriction applies only to annex J features.
5299 Second, the restriction does flag uses of package @code{ASCII}.
5300
5301 @item -gnatwJ
5302 @emph{Suppress warnings on obsolescent features (Annex J).}
5303 @cindex @option{-gnatwJ} (@command{gcc})
5304 This switch disables warnings on use of obsolescent features.
5305
5306 @item -gnatwk
5307 @emph{Activate warnings on variables that could be constants.}
5308 @cindex @option{-gnatwk} (@command{gcc})
5309 This switch activates warnings for variables that are initialized but
5310 never modified, and then could be declared constants. The default is that
5311 such warnings are not given.
5312 This warning can also be turned on using @option{-gnatwa}.
5313
5314 @item -gnatwK
5315 @emph{Suppress warnings on variables that could be constants.}
5316 @cindex @option{-gnatwK} (@command{gcc})
5317 This switch disables warnings on variables that could be declared constants.
5318
5319 @item -gnatw.k
5320 @emph{Activate warnings on redefinition of names in standard.}
5321 @cindex @option{-gnatw.k} (@command{gcc})
5322 This switch activates warnings for declarations that declare a name that
5323 is defined in package Standard. Such declarations can be confusing,
5324 especially since the names in package Standard continue to be directly
5325 visible, meaning that use visibiliy on such redeclared names does not
5326 work as expected. Names of discriminants and components in records are
5327 not included in this check.
5328 This warning is not part of the warnings activated by @option{-gnatwa}.
5329 It must be explicitly activated.
5330
5331 @item -gnatw.K
5332 @emph{Suppress warnings on variables that could be constants.}
5333 @cindex @option{-gnatwK} (@command{gcc})
5334 This switch activates warnings for declarations that declare a name that
5335 is defined in package Standard.
5336
5337 @item -gnatwl
5338 @emph{Activate warnings for elaboration pragmas.}
5339 @cindex @option{-gnatwl} (@command{gcc})
5340 @cindex Elaboration, warnings
5341 This switch activates warnings on missing
5342 for possible elaboration problems, including suspicious use
5343 of @code{Elaborate} pragmas, when using the static elaboration model, and
5344 possible situations that may raise @code{Program_Error} when using the
5345 dynamic elaboration model.
5346 See the section in this guide on elaboration checking for further details.
5347 The default is that such warnings
5348 are not generated.
5349 This warning is not automatically turned on by the use of @option{-gnatwa}.
5350
5351 @item -gnatwL
5352 @emph{Suppress warnings for elaboration pragmas.}
5353 @cindex @option{-gnatwL} (@command{gcc})
5354 This switch suppresses warnings for possible elaboration problems.
5355
5356 @item -gnatw.l
5357 @emph{List inherited aspects.}
5358 @cindex @option{-gnatw.l} (@command{gcc})
5359 This switch causes the compiler to list inherited invariants,
5360 preconditions, and postconditions from Type_Invariant'Class, Invariant'Class,
5361 Pre'Class, and Post'Class aspects. Also list inherited subtype predicates.
5362 These messages are not automatically turned on by the use of @option{-gnatwa}.
5363
5364 @item -gnatw.L
5365 @emph{Suppress listing of inherited aspects.}
5366 @cindex @option{-gnatw.L} (@command{gcc})
5367 This switch suppresses listing of inherited aspects.
5368
5369 @item -gnatwm
5370 @emph{Activate warnings on modified but unreferenced variables.}
5371 @cindex @option{-gnatwm} (@command{gcc})
5372 This switch activates warnings for variables that are assigned (using
5373 an initialization value or with one or more assignment statements) but
5374 whose value is never read. The warning is suppressed for volatile
5375 variables and also for variables that are renamings of other variables
5376 or for which an address clause is given.
5377 This warning can also be turned on using @option{-gnatwa}.
5378 The default is that these warnings are not given.
5379
5380 @item -gnatwM
5381 @emph{Disable warnings on modified but unreferenced variables.}
5382 @cindex @option{-gnatwM} (@command{gcc})
5383 This switch disables warnings for variables that are assigned or
5384 initialized, but never read.
5385
5386 @item -gnatw.m
5387 @emph{Activate warnings on suspicious modulus values.}
5388 @cindex @option{-gnatw.m} (@command{gcc})
5389 This switch activates warnings for modulus values that seem suspicious.
5390 The cases caught are where the size is the same as the modulus (e.g.
5391 a modulus of 7 with a size of 7 bits), and modulus values of 32 or 64
5392 with no size clause. The guess in both cases is that 2**x was intended
5393 rather than x. In addition expressions of the form 2*x for small x
5394 generate a warning (the almost certainly accurate guess being that
5395 2**x was intended). The default is that these warnings are given.
5396
5397 @item -gnatw.M
5398 @emph{Disable warnings on suspicious modulus values.}
5399 @cindex @option{-gnatw.M} (@command{gcc})
5400 This switch disables warnings for suspicious modulus values.
5401
5402 @item -gnatwn
5403 @emph{Set normal warnings mode.}
5404 @cindex @option{-gnatwn} (@command{gcc})
5405 This switch sets normal warning mode, in which enabled warnings are
5406 issued and treated as warnings rather than errors. This is the default
5407 mode. the switch @option{-gnatwn} can be used to cancel the effect of
5408 an explicit @option{-gnatws} or
5409 @option{-gnatwe}. It also cancels the effect of the
5410 implicit @option{-gnatwe} that is activated by the
5411 use of @option{-gnatg}.
5412
5413 @item -gnatw.n
5414 @emph{Activate warnings on atomic synchronization.}
5415 @cindex @option{-gnatw.n} (@command{gcc})
5416 @cindex Atomic Synchronization, warnings
5417 This switch actives warnings when an access to an atomic variable
5418 requires the generation of atomic synchronization code. These
5419 warnings are off by default and this warning is not included
5420 in @code{-gnatwa}.
5421
5422 @item -gnatw.N
5423 @emph{Suppress warnings on atomic synchronization.}
5424 @cindex @option{-gnatw.n} (@command{gcc})
5425 @cindex Atomic Synchronization, warnings
5426 This switch suppresses warnings when an access to an atomic variable
5427 requires the generation of atomic synchronization code.
5428
5429 @item -gnatwo
5430 @emph{Activate warnings on address clause overlays.}
5431 @cindex @option{-gnatwo} (@command{gcc})
5432 @cindex Address Clauses, warnings
5433 This switch activates warnings for possibly unintended initialization
5434 effects of defining address clauses that cause one variable to overlap
5435 another. The default is that such warnings are generated.
5436 This warning can also be turned on using @option{-gnatwa}.
5437
5438 @item -gnatwO
5439 @emph{Suppress warnings on address clause overlays.}
5440 @cindex @option{-gnatwO} (@command{gcc})
5441 This switch suppresses warnings on possibly unintended initialization
5442 effects of defining address clauses that cause one variable to overlap
5443 another.
5444
5445 @item -gnatw.o
5446 @emph{Activate warnings on modified but unreferenced out parameters.}
5447 @cindex @option{-gnatw.o} (@command{gcc})
5448 This switch activates warnings for variables that are modified by using
5449 them as actuals for a call to a procedure with an out mode formal, where
5450 the resulting assigned value is never read. It is applicable in the case
5451 where there is more than one out mode formal. If there is only one out
5452 mode formal, the warning is issued by default (controlled by -gnatwu).
5453 The warning is suppressed for volatile
5454 variables and also for variables that are renamings of other variables
5455 or for which an address clause is given.
5456 The default is that these warnings are not given. Note that this warning
5457 is not included in -gnatwa, it must be activated explicitly.
5458
5459 @item -gnatw.O
5460 @emph{Disable warnings on modified but unreferenced out parameters.}
5461 @cindex @option{-gnatw.O} (@command{gcc})
5462 This switch suppresses warnings for variables that are modified by using
5463 them as actuals for a call to a procedure with an out mode formal, where
5464 the resulting assigned value is never read.
5465
5466 @item -gnatwp
5467 @emph{Activate warnings on ineffective pragma Inlines.}
5468 @cindex @option{-gnatwp} (@command{gcc})
5469 @cindex Inlining, warnings
5470 This switch activates warnings for failure of front end inlining
5471 (activated by @option{-gnatN}) to inline a particular call. There are
5472 many reasons for not being able to inline a call, including most
5473 commonly that the call is too complex to inline. The default is
5474 that such warnings are not given.
5475 This warning can also be turned on using @option{-gnatwa}.
5476 Warnings on ineffective inlining by the gcc back-end can be activated
5477 separately, using the gcc switch -Winline.
5478
5479 @item -gnatwP
5480 @emph{Suppress warnings on ineffective pragma Inlines.}
5481 @cindex @option{-gnatwP} (@command{gcc})
5482 This switch suppresses warnings on ineffective pragma Inlines. If the
5483 inlining mechanism cannot inline a call, it will simply ignore the
5484 request silently.
5485
5486 @item -gnatw.p
5487 @emph{Activate warnings on parameter ordering.}
5488 @cindex @option{-gnatw.p} (@command{gcc})
5489 @cindex Parameter order, warnings
5490 This switch activates warnings for cases of suspicious parameter
5491 ordering when the list of arguments are all simple identifiers that
5492 match the names of the formals, but are in a different order. The
5493 warning is suppressed if any use of named parameter notation is used,
5494 so this is the appropriate way to suppress a false positive (and
5495 serves to emphasize that the "misordering" is deliberate). The
5496 default is
5497 that such warnings are not given.
5498 This warning can also be turned on using @option{-gnatwa}.
5499
5500 @item -gnatw.P
5501 @emph{Suppress warnings on parameter ordering.}
5502 @cindex @option{-gnatw.P} (@command{gcc})
5503 This switch suppresses warnings on cases of suspicious parameter
5504 ordering.
5505
5506 @item -gnatwq
5507 @emph{Activate warnings on questionable missing parentheses.}
5508 @cindex @option{-gnatwq} (@command{gcc})
5509 @cindex Parentheses, warnings
5510 This switch activates warnings for cases where parentheses are not used and
5511 the result is potential ambiguity from a readers point of view. For example
5512 (not a > b) when a and b are modular means ((not a) > b) and very likely the
5513 programmer intended (not (a > b)). Similarly (-x mod 5) means (-(x mod 5)) and
5514 quite likely ((-x) mod 5) was intended. In such situations it seems best to
5515 follow the rule of always parenthesizing to make the association clear, and
5516 this warning switch warns if such parentheses are not present. The default
5517 is that these warnings are given.
5518 This warning can also be turned on using @option{-gnatwa}.
5519
5520 @item -gnatwQ
5521 @emph{Suppress warnings on questionable missing parentheses.}
5522 @cindex @option{-gnatwQ} (@command{gcc})
5523 This switch suppresses warnings for cases where the association is not
5524 clear and the use of parentheses is preferred.
5525
5526 @item -gnatwr
5527 @emph{Activate warnings on redundant constructs.}
5528 @cindex @option{-gnatwr} (@command{gcc})
5529 This switch activates warnings for redundant constructs. The following
5530 is the current list of constructs regarded as redundant:
5531
5532 @itemize @bullet
5533 @item
5534 Assignment of an item to itself.
5535 @item
5536 Type conversion that converts an expression to its own type.
5537 @item
5538 Use of the attribute @code{Base} where @code{typ'Base} is the same
5539 as @code{typ}.
5540 @item
5541 Use of pragma @code{Pack} when all components are placed by a record
5542 representation clause.
5543 @item
5544 Exception handler containing only a reraise statement (raise with no
5545 operand) which has no effect.
5546 @item
5547 Use of the operator abs on an operand that is known at compile time
5548 to be non-negative
5549 @item
5550 Comparison of boolean expressions to an explicit True value.
5551 @end itemize
5552
5553 This warning can also be turned on using @option{-gnatwa}.
5554 The default is that warnings for redundant constructs are not given.
5555
5556 @item -gnatwR
5557 @emph{Suppress warnings on redundant constructs.}
5558 @cindex @option{-gnatwR} (@command{gcc})
5559 This switch suppresses warnings for redundant constructs.
5560
5561 @item -gnatw.r
5562 @emph{Activate warnings for object renaming function.}
5563 @cindex @option{-gnatw.r} (@command{gcc})
5564 This switch activates warnings for an object renaming that renames a
5565 function call, which is equivalent to a constant declaration (as
5566 opposed to renaming the function itself). The default is that these
5567 warnings are given. This warning can also be turned on using
5568 @option{-gnatwa}.
5569
5570 @item -gnatw.R
5571 @emph{Suppress warnings for object renaming function.}
5572 @cindex @option{-gnatwT} (@command{gcc})
5573 This switch suppresses warnings for object renaming function.
5574
5575 @item -gnatws
5576 @emph{Suppress all warnings.}
5577 @cindex @option{-gnatws} (@command{gcc})
5578 This switch completely suppresses the
5579 output of all warning messages from the GNAT front end, including
5580 both warnings that can be controlled by switches described in this
5581 section, and those that are normally given unconditionally. The
5582 effect of this suppress action can only be cancelled by a subsequent
5583 use of the switch @option{-gnatwn}.
5584
5585 Note that switch @option{-gnatws} does not suppress
5586 warnings from the @command{gcc} back end.
5587 To suppress these back end warnings as well, use the switch @option{-w}
5588 in addition to @option{-gnatws}. Also this switch has no effect on the
5589 handling of style check messages.
5590
5591 @item -gnatw.s
5592 @emph{Activate warnings on overridden size clauses.}
5593 @cindex @option{-gnatw.s} (@command{gcc})
5594 @cindex Record Representation (component sizes)
5595 This switch activates warnings on component clauses in record
5596 representation clauses where the length given overrides that
5597 specified by an explicit size clause for the component type. A
5598 warning is similarly given in the array case if a specified
5599 component size overrides an explicit size clause for the array
5600 component type.
5601 Note that @option{-gnatwa} does not affect the setting of this warning option.
5602
5603 @item -gnatw.S
5604 @emph{Suppress warnings on overridden size clauses.}
5605 @cindex @option{-gnatw.S} (@command{gcc})
5606 This switch suppresses warnings on component clauses in record
5607 representation clauses that override size clauses, and similar
5608 warnings when an array component size overrides a size clause.
5609
5610 @item -gnatwt
5611 @emph{Activate warnings for tracking of deleted conditional code.}
5612 @cindex @option{-gnatwt} (@command{gcc})
5613 @cindex Deactivated code, warnings
5614 @cindex Deleted code, warnings
5615 This switch activates warnings for tracking of code in conditionals (IF and
5616 CASE statements) that is detected to be dead code which cannot be executed, and
5617 which is removed by the front end. This warning is off by default, and is not
5618 turned on by @option{-gnatwa}, it has to be turned on explicitly. This may be
5619 useful for detecting deactivated code in certified applications.
5620
5621 @item -gnatwT
5622 @emph{Suppress warnings for tracking of deleted conditional code.}
5623 @cindex @option{-gnatwT} (@command{gcc})
5624 This switch suppresses warnings for tracking of deleted conditional code.
5625
5626 @item -gnatw.t
5627 @emph{Activate warnings on suspicious contracts.}
5628 @cindex @option{-gnatw.t} (@command{gcc})
5629 This switch activates warnings on suspicious postconditions (whether a
5630 pragma @code{Postcondition} or a @code{Post} aspect in Ada 2012)
5631 and suspicious contract cases (pragma @code{Contract_Cases}). A
5632 function postcondition or contract case is suspicious when no postcondition
5633 or contract case for this function mentions the result of the function.
5634 A procedure postcondition or contract case is suspicious when it only
5635 refers to the pre-state of the procedure, because in that case it should
5636 rather be expressed as a precondition. The default is that such warnings
5637 are not generated. This warning can also be turned on using @option{-gnatwa}.
5638
5639 @item -gnatw.T
5640 @emph{Suppress warnings on suspicious contracts.}
5641 @cindex @option{-gnatw.T} (@command{gcc})
5642 This switch suppresses warnings on suspicious postconditions.
5643
5644 @item -gnatwu
5645 @emph{Activate warnings on unused entities.}
5646 @cindex @option{-gnatwu} (@command{gcc})
5647 This switch activates warnings to be generated for entities that
5648 are declared but not referenced, and for units that are @code{with}'ed
5649 and not
5650 referenced. In the case of packages, a warning is also generated if
5651 no entities in the package are referenced. This means that if a with'ed
5652 package is referenced but the only references are in @code{use}
5653 clauses or @code{renames}
5654 declarations, a warning is still generated. A warning is also generated
5655 for a generic package that is @code{with}'ed but never instantiated.
5656 In the case where a package or subprogram body is compiled, and there
5657 is a @code{with} on the corresponding spec
5658 that is only referenced in the body,
5659 a warning is also generated, noting that the
5660 @code{with} can be moved to the body. The default is that
5661 such warnings are not generated.
5662 This switch also activates warnings on unreferenced formals
5663 (it includes the effect of @option{-gnatwf}).
5664 This warning can also be turned on using @option{-gnatwa}.
5665
5666 @item -gnatwU
5667 @emph{Suppress warnings on unused entities.}
5668 @cindex @option{-gnatwU} (@command{gcc})
5669 This switch suppresses warnings for unused entities and packages.
5670 It also turns off warnings on unreferenced formals (and thus includes
5671 the effect of @option{-gnatwF}).
5672
5673 @item -gnatw.u
5674 @emph{Activate warnings on unordered enumeration types.}
5675 @cindex @option{-gnatw.u} (@command{gcc})
5676 This switch causes enumeration types to be considered as conceptually
5677 unordered, unless an explicit pragma @code{Ordered} is given for the type.
5678 The effect is to generate warnings in clients that use explicit comparisons
5679 or subranges, since these constructs both treat objects of the type as
5680 ordered. (A @emph{client} is defined as a unit that is other than the unit in
5681 which the type is declared, or its body or subunits.) Please refer to
5682 the description of pragma @code{Ordered} in the
5683 @cite{@value{EDITION} Reference Manual} for further details.
5684 The default is that such warnings are not generated.
5685 This warning is not automatically turned on by the use of @option{-gnatwa}.
5686
5687 @item -gnatw.U
5688 @emph{Deactivate warnings on unordered enumeration types.}
5689 @cindex @option{-gnatw.U} (@command{gcc})
5690 This switch causes all enumeration types to be considered as ordered, so
5691 that no warnings are given for comparisons or subranges for any type.
5692
5693 @item -gnatwv
5694 @emph{Activate warnings on unassigned variables.}
5695 @cindex @option{-gnatwv} (@command{gcc})
5696 @cindex Unassigned variable warnings
5697 This switch activates warnings for access to variables which
5698 may not be properly initialized. The default is that
5699 such warnings are generated.
5700 This warning can also be turned on using @option{-gnatwa}.
5701
5702 @item -gnatwV
5703 @emph{Suppress warnings on unassigned variables.}
5704 @cindex @option{-gnatwV} (@command{gcc})
5705 This switch suppresses warnings for access to variables which
5706 may not be properly initialized.
5707 For variables of a composite type, the warning can also be suppressed in
5708 Ada 2005 by using a default initialization with a box. For example, if
5709 Table is an array of records whose components are only partially uninitialized,
5710 then the following code:
5711
5712 @smallexample @c ada
5713 Tab : Table := (others => <>);
5714 @end smallexample
5715
5716 will suppress warnings on subsequent statements that access components
5717 of variable Tab.
5718
5719 @item -gnatw.v
5720 @emph{Activate info messages for non-default bit order.}
5721 @cindex @option{-gnatw.v} (@command{gcc})
5722 @cindex bit order warnings
5723 This switch activates messages (labeled "info", they are not warnings,
5724 just informational messages) about the effects of non-default bit-order
5725 on records to which a component clause is applied. The effect of specifying
5726 non-default bit ordering is a bit subtle (and changed with Ada 2005), so
5727 these messages, which are given by default, are useful in understanding the
5728 exact consequences of using this feature. These messages
5729 can also be turned on using @option{-gnatwa}
5730
5731 @item -gnatw.V
5732 @emph{Suppress info messages for non-default bit order.}
5733 @cindex @option{-gnatw.V} (@command{gcc})
5734 This switch suppresses information messages for the effects of specifying
5735 non-default bit order on record components with component clauses.
5736
5737 @item -gnatww
5738 @emph{Activate warnings on wrong low bound assumption.}
5739 @cindex @option{-gnatww} (@command{gcc})
5740 @cindex String indexing warnings
5741 This switch activates warnings for indexing an unconstrained string parameter
5742 with a literal or S'Length. This is a case where the code is assuming that the
5743 low bound is one, which is in general not true (for example when a slice is
5744 passed). The default is that such warnings are generated.
5745 This warning can also be turned on using @option{-gnatwa}.
5746
5747 @item -gnatwW
5748 @emph{Suppress warnings on wrong low bound assumption.}
5749 @cindex @option{-gnatwW} (@command{gcc})
5750 This switch suppresses warnings for indexing an unconstrained string parameter
5751 with a literal or S'Length. Note that this warning can also be suppressed
5752 in a particular case by adding an
5753 assertion that the lower bound is 1,
5754 as shown in the following example.
5755
5756 @smallexample @c ada
5757 procedure K (S : String) is
5758 pragma Assert (S'First = 1);
5759 @dots{}
5760 @end smallexample
5761
5762 @item -gnatw.w
5763 @emph{Activate warnings on Warnings Off pragmas}
5764 @cindex @option{-gnatw.w} (@command{gcc})
5765 @cindex Warnings Off control
5766 This switch activates warnings for use of @code{pragma Warnings (Off, entity)}
5767 where either the pragma is entirely useless (because it suppresses no
5768 warnings), or it could be replaced by @code{pragma Unreferenced} or
5769 @code{pragma Unmodified}. The default is that these warnings are not given.
5770 Note that this warning is not included in -gnatwa, it must be
5771 activated explicitly. Also activates warnings for the case of
5772 Warnings (Off, String), where either there is no matching
5773 Warnings (On, String), or the Warnings (Off) did not suppress any warning.
5774
5775 @item -gnatw.W
5776 @emph{Suppress warnings on unnecessary Warnings Off pragmas}
5777 @cindex @option{-gnatw.W} (@command{gcc})
5778 This switch suppresses warnings for use of @code{pragma Warnings (Off, ...)}.
5779
5780 @item -gnatwx
5781 @emph{Activate warnings on Export/Import pragmas.}
5782 @cindex @option{-gnatwx} (@command{gcc})
5783 @cindex Export/Import pragma warnings
5784 This switch activates warnings on Export/Import pragmas when
5785 the compiler detects a possible conflict between the Ada and
5786 foreign language calling sequences. For example, the use of
5787 default parameters in a convention C procedure is dubious
5788 because the C compiler cannot supply the proper default, so
5789 a warning is issued. The default is that such warnings are
5790 generated.
5791 This warning can also be turned on using @option{-gnatwa}.
5792
5793 @item -gnatwX
5794 @emph{Suppress warnings on Export/Import pragmas.}
5795 @cindex @option{-gnatwX} (@command{gcc})
5796 This switch suppresses warnings on Export/Import pragmas.
5797 The sense of this is that you are telling the compiler that
5798 you know what you are doing in writing the pragma, and it
5799 should not complain at you.
5800
5801 @item -gnatw.x
5802 @emph{Activate warnings for No_Exception_Propagation mode.}
5803 @cindex @option{-gnatwm} (@command{gcc})
5804 This switch activates warnings for exception usage when pragma Restrictions
5805 (No_Exception_Propagation) is in effect. Warnings are given for implicit or
5806 explicit exception raises which are not covered by a local handler, and for
5807 exception handlers which do not cover a local raise. The default is that these
5808 warnings are not given.
5809
5810 @item -gnatw.X
5811 @emph{Disable warnings for No_Exception_Propagation mode.}
5812 This switch disables warnings for exception usage when pragma Restrictions
5813 (No_Exception_Propagation) is in effect.
5814
5815 @item -gnatwy
5816 @emph{Activate warnings for Ada compatibility issues.}
5817 @cindex @option{-gnatwy} (@command{gcc})
5818 @cindex Ada compatibility issues warnings
5819 For the most part, newer versions of Ada are upwards compatible
5820 with older versions. For example, Ada 2005 programs will almost
5821 always work when compiled as Ada 2012.
5822 However there are some exceptions (for example the fact that
5823 @code{some} is now a reserved word in Ada 2012). This
5824 switch activates several warnings to help in identifying
5825 and correcting such incompatibilities. The default is that
5826 these warnings are generated. Note that at one point Ada 2005
5827 was called Ada 0Y, hence the choice of character.
5828 This warning can also be turned on using @option{-gnatwa}.
5829
5830 @item -gnatwY
5831 @emph{Disable warnings for Ada compatibility issues.}
5832 @cindex @option{-gnatwY} (@command{gcc})
5833 @cindex Ada compatibility issues warnings
5834 This switch suppresses the warnings intended to help in identifying
5835 incompatibilities between Ada language versions.
5836
5837 @item -gnatw.y
5838 @emph{Activate information messages for why package spec needs body}
5839 @cindex @option{-gnatw.y} (@command{gcc})
5840 @cindex Package spec needing body
5841 There are a number of cases in which a package spec needs a body.
5842 For example, the use of pragma Elaborate_Body, or the declaration
5843 of a procedure specification requiring a completion. This switch
5844 causes information messages to be output showing why a package
5845 specification requires a body. This can be useful in the case of
5846 a large package specification which is unexpectedly requiring a
5847 body. The default is that such information messages are not output.
5848
5849 @item -gnatw.Y
5850 @emph{Disable information messages for why package spec needs body}
5851 @cindex @option{-gnatw.Y} (@command{gcc})
5852 @cindex No information messages for why package spec needs body
5853 This switch suppresses the output of information messages showing why
5854 a package specification needs a body.
5855
5856 @item -gnatwz
5857 @emph{Activate warnings on unchecked conversions.}
5858 @cindex @option{-gnatwz} (@command{gcc})
5859 @cindex Unchecked_Conversion warnings
5860 This switch activates warnings for unchecked conversions
5861 where the types are known at compile time to have different
5862 sizes. The default
5863 is that such warnings are generated. Warnings are also
5864 generated for subprogram pointers with different conventions,
5865 and, on VMS only, for data pointers with different conventions.
5866 This warning can also be turned on using @option{-gnatwa}.
5867
5868 @item -gnatwZ
5869 @emph{Suppress warnings on unchecked conversions.}
5870 @cindex @option{-gnatwZ} (@command{gcc})
5871 This switch suppresses warnings for unchecked conversions
5872 where the types are known at compile time to have different
5873 sizes or conventions.
5874
5875 @item -gnatw.z
5876 @emph{Activate warnings for size not a multiple of alignment.}
5877 @cindex @option{-gnatw.z} (@command{gcc})
5878 @cindex Size/Alignment warnings
5879 This switch activates warnings for cases of record types with
5880 specified @code{Size} and @code{Alignment} attributes where the
5881 size is not a multiple of the alignment, resulting in an object
5882 size that is greater than the specified size. The default
5883 is that such warnings are generated.
5884 This warning can also be turned on using @option{-gnatwa}.
5885
5886 @item -gnatw.Z
5887 @emph{Suppress warnings for size not a multiple of alignment.}
5888 @cindex @option{-gnatw.Z} (@command{gcc})
5889 @cindex Size/Alignment warnings
5890 This switch suppresses warnings for cases of record types with
5891 specified @code{Size} and @code{Alignment} attributes where the
5892 size is not a multiple of the alignment, resulting in an object
5893 size that is greater than the specified size.
5894 The warning can also be
5895 suppressed by giving an explicit @code{Object_Size} value.
5896
5897 @item ^-Wunused^WARNINGS=UNUSED^
5898 @cindex @option{-Wunused}
5899 The warnings controlled by the @option{-gnatw} switch are generated by
5900 the front end of the compiler. The @option{GCC} back end can provide
5901 additional warnings and they are controlled by the @option{-W} switch.
5902 For example, @option{^-Wunused^WARNINGS=UNUSED^} activates back end
5903 warnings for entities that are declared but not referenced.
5904
5905 @item ^-Wuninitialized^WARNINGS=UNINITIALIZED^
5906 @cindex @option{-Wuninitialized}
5907 Similarly, @option{^-Wuninitialized^WARNINGS=UNINITIALIZED^} activates
5908 the back end warning for uninitialized variables. This switch must be
5909 used in conjunction with an optimization level greater than zero.
5910
5911 @item -Wstack-usage=@var{len}
5912 @cindex @option{-Wstack-usage}
5913 Warn if the stack usage of a subprogram might be larger than @var{len} bytes.
5914 See @ref{Static Stack Usage Analysis} for details.
5915
5916 @item ^-Wall^/ALL_BACK_END_WARNINGS^
5917 @cindex @option{-Wall}
5918 This switch enables most warnings from the @option{GCC} back end.
5919 The code generator detects a number of warning situations that are missed
5920 by the @option{GNAT} front end, and this switch can be used to activate them.
5921 The use of this switch also sets the default front end warning mode to
5922 @option{-gnatwa}, that is, most front end warnings activated as well.
5923
5924 @item ^-w^/NO_BACK_END_WARNINGS^
5925 @cindex @option{-w}
5926 Conversely, this switch suppresses warnings from the @option{GCC} back end.
5927 The use of this switch also sets the default front end warning mode to
5928 @option{-gnatws}, that is, front end warnings suppressed as well.
5929
5930 @item -Werror
5931 @cindex @option{-Werror}
5932 This switch causes warnings from the @option{GCC} back end to be treated as
5933 errors. The warning string still appears, but the warning messages are
5934 counted as errors, and prevent the generation of an object file.
5935
5936 @end table
5937
5938 @noindent
5939 @ifclear vms
5940 A string of warning parameters can be used in the same parameter. For example:
5941
5942 @smallexample
5943 -gnatwaGe
5944 @end smallexample
5945
5946 @noindent
5947 will turn on all optional warnings except for unrecognized pragma warnings,
5948 and also specify that warnings should be treated as errors.
5949 @end ifclear
5950
5951 When no switch @option{^-gnatw^/WARNINGS^} is used, this is equivalent to:
5952
5953 @table @option
5954 @c !sort!
5955 @item -gnatw.a
5956 @item -gnatwB
5957 @item -gnatw.b
5958 @item -gnatwC
5959 @item -gnatw.C
5960 @item -gnatwD
5961 @item -gnatwF
5962 @item -gnatwg
5963 @item -gnatwH
5964 @item -gnatwi
5965 @item -gnatw.I
5966 @item -gnatwJ
5967 @item -gnatwK
5968 @item -gnatwL
5969 @item -gnatw.L
5970 @item -gnatwM
5971 @item -gnatw.m
5972 @item -gnatwn
5973 @item -gnatwo
5974 @item -gnatw.O
5975 @item -gnatwP
5976 @item -gnatw.P
5977 @item -gnatwq
5978 @item -gnatwR
5979 @item -gnatw.R
5980 @item -gnatw.S
5981 @item -gnatwT
5982 @item -gnatw.T
5983 @item -gnatwU
5984 @item -gnatwv
5985 @item -gnatww
5986 @item -gnatw.W
5987 @item -gnatwx
5988 @item -gnatw.X
5989 @item -gnatwy
5990 @item -gnatwz
5991
5992 @end table
5993
5994 @node Debugging and Assertion Control
5995 @subsection Debugging and Assertion Control
5996
5997 @table @option
5998 @item -gnata
5999 @cindex @option{-gnata} (@command{gcc})
6000 @findex Assert
6001 @findex Debug
6002 @cindex Assertions
6003
6004 @noindent
6005 The pragmas @code{Assert} and @code{Debug} normally have no effect and
6006 are ignored. This switch, where @samp{a} stands for assert, causes
6007 @code{Assert} and @code{Debug} pragmas to be activated.
6008
6009 The pragmas have the form:
6010
6011 @smallexample
6012 @cartouche
6013 @b{pragma} Assert (@var{Boolean-expression} @r{[},
6014 @var{static-string-expression}@r{]})
6015 @b{pragma} Debug (@var{procedure call})
6016 @end cartouche
6017 @end smallexample
6018
6019 @noindent
6020 The @code{Assert} pragma causes @var{Boolean-expression} to be tested.
6021 If the result is @code{True}, the pragma has no effect (other than
6022 possible side effects from evaluating the expression). If the result is
6023 @code{False}, the exception @code{Assert_Failure} declared in the package
6024 @code{System.Assertions} is
6025 raised (passing @var{static-string-expression}, if present, as the
6026 message associated with the exception). If no string expression is
6027 given the default is a string giving the file name and line number
6028 of the pragma.
6029
6030 The @code{Debug} pragma causes @var{procedure} to be called. Note that
6031 @code{pragma Debug} may appear within a declaration sequence, allowing
6032 debugging procedures to be called between declarations.
6033
6034 @ifset vms
6035 @item /DEBUG@r{[}=debug-level@r{]}
6036 @itemx /NODEBUG
6037 Specifies how much debugging information is to be included in
6038 the resulting object file where 'debug-level' is one of the following:
6039 @table @code
6040 @item TRACEBACK
6041 Include both debugger symbol records and traceback
6042 the object file.
6043 This is the default setting.
6044 @item ALL
6045 Include both debugger symbol records and traceback in
6046 object file.
6047 @item NONE
6048 Excludes both debugger symbol records and traceback
6049 the object file. Same as /NODEBUG.
6050 @item SYMBOLS
6051 Includes only debugger symbol records in the object
6052 file. Note that this doesn't include traceback information.
6053 @end table
6054 @end ifset
6055 @end table
6056
6057 @node Validity Checking
6058 @subsection Validity Checking
6059 @findex Validity Checking
6060
6061 @noindent
6062 The Ada Reference Manual defines the concept of invalid values (see
6063 RM 13.9.1). The primary source of invalid values is uninitialized
6064 variables. A scalar variable that is left uninitialized may contain
6065 an invalid value; the concept of invalid does not apply to access or
6066 composite types.
6067
6068 It is an error to read an invalid value, but the RM does not require
6069 run-time checks to detect such errors, except for some minimal
6070 checking to prevent erroneous execution (i.e. unpredictable
6071 behavior). This corresponds to the @option{-gnatVd} switch below,
6072 which is the default. For example, by default, if the expression of a
6073 case statement is invalid, it will raise Constraint_Error rather than
6074 causing a wild jump, and if an array index on the left-hand side of an
6075 assignment is invalid, it will raise Constraint_Error rather than
6076 overwriting an arbitrary memory location.
6077
6078 The @option{-gnatVa} may be used to enable additional validity checks,
6079 which are not required by the RM. These checks are often very
6080 expensive (which is why the RM does not require them). These checks
6081 are useful in tracking down uninitialized variables, but they are
6082 not usually recommended for production builds, and in particular
6083 we do not recommend using these extra validity checking options in
6084 combination with optimization, since this can confuse the optimizer.
6085 If performance is a consideration, leading to the need to optimize,
6086 then the validity checking options should not be used.
6087
6088 The other @option{-gnatV^@var{x}^^} switches below allow finer-grained
6089 control; you can enable whichever validity checks you desire. However,
6090 for most debugging purposes, @option{-gnatVa} is sufficient, and the
6091 default @option{-gnatVd} (i.e. standard Ada behavior) is usually
6092 sufficient for non-debugging use.
6093
6094 The @option{-gnatB} switch tells the compiler to assume that all
6095 values are valid (that is, within their declared subtype range)
6096 except in the context of a use of the Valid attribute. This means
6097 the compiler can generate more efficient code, since the range
6098 of values is better known at compile time. However, an uninitialized
6099 variable can cause wild jumps and memory corruption in this mode.
6100
6101 The @option{-gnatV^@var{x}^^} switch allows control over the validity
6102 checking mode as described below.
6103 @ifclear vms
6104 The @code{x} argument is a string of letters that
6105 indicate validity checks that are performed or not performed in addition
6106 to the default checks required by Ada as described above.
6107 @end ifclear
6108 @ifset vms
6109 The options allowed for this qualifier
6110 indicate validity checks that are performed or not performed in addition
6111 to the default checks required by Ada as described above.
6112 @end ifset
6113
6114 @table @option
6115 @c !sort!
6116 @item -gnatVa
6117 @emph{All validity checks.}
6118 @cindex @option{-gnatVa} (@command{gcc})
6119 All validity checks are turned on.
6120 @ifclear vms
6121 That is, @option{-gnatVa} is
6122 equivalent to @option{gnatVcdfimorst}.
6123 @end ifclear
6124
6125 @item -gnatVc
6126 @emph{Validity checks for copies.}
6127 @cindex @option{-gnatVc} (@command{gcc})
6128 The right hand side of assignments, and the initializing values of
6129 object declarations are validity checked.
6130
6131 @item -gnatVd
6132 @emph{Default (RM) validity checks.}
6133 @cindex @option{-gnatVd} (@command{gcc})
6134 Some validity checks are done by default following normal Ada semantics
6135 (RM 13.9.1 (9-11)).
6136 A check is done in case statements that the expression is within the range
6137 of the subtype. If it is not, Constraint_Error is raised.
6138 For assignments to array components, a check is done that the expression used
6139 as index is within the range. If it is not, Constraint_Error is raised.
6140 Both these validity checks may be turned off using switch @option{-gnatVD}.
6141 They are turned on by default. If @option{-gnatVD} is specified, a subsequent
6142 switch @option{-gnatVd} will leave the checks turned on.
6143 Switch @option{-gnatVD} should be used only if you are sure that all such
6144 expressions have valid values. If you use this switch and invalid values
6145 are present, then the program is erroneous, and wild jumps or memory
6146 overwriting may occur.
6147
6148 @item -gnatVe
6149 @emph{Validity checks for elementary components.}
6150 @cindex @option{-gnatVe} (@command{gcc})
6151 In the absence of this switch, assignments to record or array components are
6152 not validity checked, even if validity checks for assignments generally
6153 (@option{-gnatVc}) are turned on. In Ada, assignment of composite values do not
6154 require valid data, but assignment of individual components does. So for
6155 example, there is a difference between copying the elements of an array with a
6156 slice assignment, compared to assigning element by element in a loop. This
6157 switch allows you to turn off validity checking for components, even when they
6158 are assigned component by component.
6159
6160 @item -gnatVf
6161 @emph{Validity checks for floating-point values.}
6162 @cindex @option{-gnatVf} (@command{gcc})
6163 In the absence of this switch, validity checking occurs only for discrete
6164 values. If @option{-gnatVf} is specified, then validity checking also applies
6165 for floating-point values, and NaNs and infinities are considered invalid,
6166 as well as out of range values for constrained types. Note that this means
6167 that standard IEEE infinity mode is not allowed. The exact contexts
6168 in which floating-point values are checked depends on the setting of other
6169 options. For example,
6170 @option{^-gnatVif^VALIDITY_CHECKING=(IN_PARAMS,FLOATS)^} or
6171 @option{^-gnatVfi^VALIDITY_CHECKING=(FLOATS,IN_PARAMS)^}
6172 (the order does not matter) specifies that floating-point parameters of mode
6173 @code{in} should be validity checked.
6174
6175 @item -gnatVi
6176 @emph{Validity checks for @code{in} mode parameters}
6177 @cindex @option{-gnatVi} (@command{gcc})
6178 Arguments for parameters of mode @code{in} are validity checked in function
6179 and procedure calls at the point of call.
6180
6181 @item -gnatVm
6182 @emph{Validity checks for @code{in out} mode parameters.}
6183 @cindex @option{-gnatVm} (@command{gcc})
6184 Arguments for parameters of mode @code{in out} are validity checked in
6185 procedure calls at the point of call. The @code{'m'} here stands for
6186 modify, since this concerns parameters that can be modified by the call.
6187 Note that there is no specific option to test @code{out} parameters,
6188 but any reference within the subprogram will be tested in the usual
6189 manner, and if an invalid value is copied back, any reference to it
6190 will be subject to validity checking.
6191
6192 @item -gnatVn
6193 @emph{No validity checks.}
6194 @cindex @option{-gnatVn} (@command{gcc})
6195 This switch turns off all validity checking, including the default checking
6196 for case statements and left hand side subscripts. Note that the use of
6197 the switch @option{-gnatp} suppresses all run-time checks, including
6198 validity checks, and thus implies @option{-gnatVn}. When this switch
6199 is used, it cancels any other @option{-gnatV} previously issued.
6200
6201 @item -gnatVo
6202 @emph{Validity checks for operator and attribute operands.}
6203 @cindex @option{-gnatVo} (@command{gcc})
6204 Arguments for predefined operators and attributes are validity checked.
6205 This includes all operators in package @code{Standard},
6206 the shift operators defined as intrinsic in package @code{Interfaces}
6207 and operands for attributes such as @code{Pos}. Checks are also made
6208 on individual component values for composite comparisons, and on the
6209 expressions in type conversions and qualified expressions. Checks are
6210 also made on explicit ranges using @samp{..} (e.g.@: slices, loops etc).
6211
6212 @item -gnatVp
6213 @emph{Validity checks for parameters.}
6214 @cindex @option{-gnatVp} (@command{gcc})
6215 This controls the treatment of parameters within a subprogram (as opposed
6216 to @option{-gnatVi} and @option{-gnatVm} which control validity testing
6217 of parameters on a call. If either of these call options is used, then
6218 normally an assumption is made within a subprogram that the input arguments
6219 have been validity checking at the point of call, and do not need checking
6220 again within a subprogram). If @option{-gnatVp} is set, then this assumption
6221 is not made, and parameters are not assumed to be valid, so their validity
6222 will be checked (or rechecked) within the subprogram.
6223
6224 @item -gnatVr
6225 @emph{Validity checks for function returns.}
6226 @cindex @option{-gnatVr} (@command{gcc})
6227 The expression in @code{return} statements in functions is validity
6228 checked.
6229
6230 @item -gnatVs
6231 @emph{Validity checks for subscripts.}
6232 @cindex @option{-gnatVs} (@command{gcc})
6233 All subscripts expressions are checked for validity, whether they appear
6234 on the right side or left side (in default mode only left side subscripts
6235 are validity checked).
6236
6237 @item -gnatVt
6238 @emph{Validity checks for tests.}
6239 @cindex @option{-gnatVt} (@command{gcc})
6240 Expressions used as conditions in @code{if}, @code{while} or @code{exit}
6241 statements are checked, as well as guard expressions in entry calls.
6242
6243 @end table
6244
6245 @noindent
6246 The @option{-gnatV} switch may be followed by
6247 ^a string of letters^a list of options^
6248 to turn on a series of validity checking options.
6249 For example,
6250 @option{^-gnatVcr^/VALIDITY_CHECKING=(COPIES, RETURNS)^}
6251 specifies that in addition to the default validity checking, copies and
6252 function return expressions are to be validity checked.
6253 In order to make it easier
6254 to specify the desired combination of effects,
6255 @ifclear vms
6256 the upper case letters @code{CDFIMORST} may
6257 be used to turn off the corresponding lower case option.
6258 @end ifclear
6259 @ifset vms
6260 the prefix @code{NO} on an option turns off the corresponding validity
6261 checking:
6262 @itemize @bullet
6263 @item @code{NOCOPIES}
6264 @item @code{NODEFAULT}
6265 @item @code{NOFLOATS}
6266 @item @code{NOIN_PARAMS}
6267 @item @code{NOMOD_PARAMS}
6268 @item @code{NOOPERANDS}
6269 @item @code{NORETURNS}
6270 @item @code{NOSUBSCRIPTS}
6271 @item @code{NOTESTS}
6272 @end itemize
6273 @end ifset
6274 Thus
6275 @option{^-gnatVaM^/VALIDITY_CHECKING=(ALL, NOMOD_PARAMS)^}
6276 turns on all validity checking options except for
6277 checking of @code{@b{in out}} procedure arguments.
6278
6279 The specification of additional validity checking generates extra code (and
6280 in the case of @option{-gnatVa} the code expansion can be substantial).
6281 However, these additional checks can be very useful in detecting
6282 uninitialized variables, incorrect use of unchecked conversion, and other
6283 errors leading to invalid values. The use of pragma @code{Initialize_Scalars}
6284 is useful in conjunction with the extra validity checking, since this
6285 ensures that wherever possible uninitialized variables have invalid values.
6286
6287 See also the pragma @code{Validity_Checks} which allows modification of
6288 the validity checking mode at the program source level, and also allows for
6289 temporary disabling of validity checks.
6290
6291 @node Style Checking
6292 @subsection Style Checking
6293 @findex Style checking
6294
6295 @noindent
6296 The @option{-gnaty^x^(option,option,@dots{})^} switch
6297 @cindex @option{-gnaty} (@command{gcc})
6298 causes the compiler to
6299 enforce specified style rules. A limited set of style rules has been used
6300 in writing the GNAT sources themselves. This switch allows user programs
6301 to activate all or some of these checks. If the source program fails a
6302 specified style check, an appropriate message is given, preceded by
6303 the character sequence ``(style)''. This message does not prevent
6304 successful compilation (unless the @option{-gnatwe} switch is used).
6305
6306 Note that this is by no means intended to be a general facility for
6307 checking arbitrary coding standards. It is simply an embedding of the
6308 style rules we have chosen for the GNAT sources. If you are starting
6309 a project which does not have established style standards, you may
6310 find it useful to adopt the entire set of GNAT coding standards, or
6311 some subset of them.
6312 @ifclear FSFEDITION
6313 If you already have an established set of coding
6314 standards, then the selected style checking options may
6315 indeed correspond to choices you have made, but for general checking
6316 of an existing set of coding rules, you should look to the gnatcheck
6317 tool, which is designed for that purpose.
6318 @end ifclear
6319
6320 @ifset vms
6321 @code{(option,option,@dots{})} is a sequence of keywords
6322 @end ifset
6323 @ifclear vms
6324 The string @var{x} is a sequence of letters or digits
6325 @end ifclear
6326 indicating the particular style
6327 checks to be performed. The following checks are defined:
6328
6329 @table @option
6330 @c !sort!
6331 @item 0-9
6332 @emph{Specify indentation level.}
6333 If a digit from 1-9 appears
6334 ^in the string after @option{-gnaty}^as an option for /STYLE_CHECKS^
6335 then proper indentation is checked, with the digit indicating the
6336 indentation level required. A value of zero turns off this style check.
6337 The general style of required indentation is as specified by
6338 the examples in the Ada Reference Manual. Full line comments must be
6339 aligned with the @code{--} starting on a column that is a multiple of
6340 the alignment level, or they may be aligned the same way as the following
6341 non-blank line (this is useful when full line comments appear in the middle
6342 of a statement, or they may be aligned with the source line on the previous
6343 non-blank line.
6344
6345 @item ^a^ATTRIBUTE^
6346 @emph{Check attribute casing.}
6347 Attribute names, including the case of keywords such as @code{digits}
6348 used as attributes names, must be written in mixed case, that is, the
6349 initial letter and any letter following an underscore must be uppercase.
6350 All other letters must be lowercase.
6351
6352 @item ^A^ARRAY_INDEXES^
6353 @emph{Use of array index numbers in array attributes.}
6354 When using the array attributes First, Last, Range,
6355 or Length, the index number must be omitted for one-dimensional arrays
6356 and is required for multi-dimensional arrays.
6357
6358 @item ^b^BLANKS^
6359 @emph{Blanks not allowed at statement end.}
6360 Trailing blanks are not allowed at the end of statements. The purpose of this
6361 rule, together with h (no horizontal tabs), is to enforce a canonical format
6362 for the use of blanks to separate source tokens.
6363
6364 @item ^B^BOOLEAN_OPERATORS^
6365 @emph{Check Boolean operators.}
6366 The use of AND/OR operators is not permitted except in the cases of modular
6367 operands, array operands, and simple stand-alone boolean variables or
6368 boolean constants. In all other cases @code{and then}/@code{or else} are
6369 required.
6370
6371 @item ^c^COMMENTS^
6372 @emph{Check comments, double space.}
6373 Comments must meet the following set of rules:
6374
6375 @itemize @bullet
6376
6377 @item
6378 The ``@code{--}'' that starts the column must either start in column one,
6379 or else at least one blank must precede this sequence.
6380
6381 @item
6382 Comments that follow other tokens on a line must have at least one blank
6383 following the ``@code{--}'' at the start of the comment.
6384
6385 @item
6386 Full line comments must have at least two blanks following the
6387 ``@code{--}'' that starts the comment, with the following exceptions.
6388
6389 @item
6390 A line consisting only of the ``@code{--}'' characters, possibly preceded
6391 by blanks is permitted.
6392
6393 @item
6394 A comment starting with ``@code{--x}'' where @code{x} is a special character
6395 is permitted.
6396 This allows proper processing of the output generated by specialized tools
6397 including @command{gnatprep} (where ``@code{--!}'' is used) and the SPARK
6398 annotation
6399 language (where ``@code{--#}'' is used). For the purposes of this rule, a
6400 special character is defined as being in one of the ASCII ranges
6401 @code{16#21#@dots{}16#2F#} or @code{16#3A#@dots{}16#3F#}.
6402 Note that this usage is not permitted
6403 in GNAT implementation units (i.e., when @option{-gnatg} is used).
6404
6405 @item
6406 A line consisting entirely of minus signs, possibly preceded by blanks, is
6407 permitted. This allows the construction of box comments where lines of minus
6408 signs are used to form the top and bottom of the box.
6409
6410 @item
6411 A comment that starts and ends with ``@code{--}'' is permitted as long as at
6412 least one blank follows the initial ``@code{--}''. Together with the preceding
6413 rule, this allows the construction of box comments, as shown in the following
6414 example:
6415 @smallexample
6416 ---------------------------
6417 -- This is a box comment --
6418 -- with two text lines. --
6419 ---------------------------
6420 @end smallexample
6421 @end itemize
6422
6423 @item ^C^COMMENTS1^
6424 @emph{Check comments, single space.}
6425 This is identical to @code{^c^COMMENTS^} except that only one space
6426 is required following the @code{--} of a comment instead of two.
6427
6428 @item ^d^DOS_LINE_ENDINGS^
6429 @emph{Check no DOS line terminators present.}
6430 All lines must be terminated by a single ASCII.LF
6431 character (in particular the DOS line terminator sequence CR/LF is not
6432 allowed).
6433
6434 @item ^e^END^
6435 @emph{Check end/exit labels.}
6436 Optional labels on @code{end} statements ending subprograms and on
6437 @code{exit} statements exiting named loops, are required to be present.
6438
6439 @item ^f^VTABS^
6440 @emph{No form feeds or vertical tabs.}
6441 Neither form feeds nor vertical tab characters are permitted
6442 in the source text.
6443
6444 @item ^g^GNAT^
6445 @emph{GNAT style mode.}
6446 The set of style check switches is set to match that used by the GNAT sources.
6447 This may be useful when developing code that is eventually intended to be
6448 incorporated into GNAT. Currently this is equivalent to @option{-gnatwydISux})
6449 but additional style switches may be added to this set in the future without
6450 advance notice.
6451
6452 @item ^h^HTABS^
6453 @emph{No horizontal tabs.}
6454 Horizontal tab characters are not permitted in the source text.
6455 Together with the b (no blanks at end of line) check, this
6456 enforces a canonical form for the use of blanks to separate
6457 source tokens.
6458
6459 @item ^i^IF_THEN^
6460 @emph{Check if-then layout.}
6461 The keyword @code{then} must appear either on the same
6462 line as corresponding @code{if}, or on a line on its own, lined
6463 up under the @code{if}.
6464
6465 @item ^I^IN_MODE^
6466 @emph{check mode IN keywords.}
6467 Mode @code{in} (the default mode) is not
6468 allowed to be given explicitly. @code{in out} is fine,
6469 but not @code{in} on its own.
6470
6471 @item ^k^KEYWORD^
6472 @emph{Check keyword casing.}
6473 All keywords must be in lower case (with the exception of keywords
6474 such as @code{digits} used as attribute names to which this check
6475 does not apply).
6476
6477 @item ^l^LAYOUT^
6478 @emph{Check layout.}
6479 Layout of statement and declaration constructs must follow the
6480 recommendations in the Ada Reference Manual, as indicated by the
6481 form of the syntax rules. For example an @code{else} keyword must
6482 be lined up with the corresponding @code{if} keyword.
6483
6484 There are two respects in which the style rule enforced by this check
6485 option are more liberal than those in the Ada Reference Manual. First
6486 in the case of record declarations, it is permissible to put the
6487 @code{record} keyword on the same line as the @code{type} keyword, and
6488 then the @code{end} in @code{end record} must line up under @code{type}.
6489 This is also permitted when the type declaration is split on two lines.
6490 For example, any of the following three layouts is acceptable:
6491
6492 @smallexample @c ada
6493 @cartouche
6494 type q is record
6495 a : integer;
6496 b : integer;
6497 end record;
6498
6499 type q is
6500 record
6501 a : integer;
6502 b : integer;
6503 end record;
6504
6505 type q is
6506 record
6507 a : integer;
6508 b : integer;
6509 end record;
6510
6511 @end cartouche
6512 @end smallexample
6513
6514 @noindent
6515 Second, in the case of a block statement, a permitted alternative
6516 is to put the block label on the same line as the @code{declare} or
6517 @code{begin} keyword, and then line the @code{end} keyword up under
6518 the block label. For example both the following are permitted:
6519
6520 @smallexample @c ada
6521 @cartouche
6522 Block : declare
6523 A : Integer := 3;
6524 begin
6525 Proc (A, A);
6526 end Block;
6527
6528 Block :
6529 declare
6530 A : Integer := 3;
6531 begin
6532 Proc (A, A);
6533 end Block;
6534 @end cartouche
6535 @end smallexample
6536
6537 @noindent
6538 The same alternative format is allowed for loops. For example, both of
6539 the following are permitted:
6540
6541 @smallexample @c ada
6542 @cartouche
6543 Clear : while J < 10 loop
6544 A (J) := 0;
6545 end loop Clear;
6546
6547 Clear :
6548 while J < 10 loop
6549 A (J) := 0;
6550 end loop Clear;
6551 @end cartouche
6552 @end smallexample
6553
6554 @item ^Lnnn^MAX_NESTING=nnn^
6555 @emph{Set maximum nesting level.}
6556 The maximum level of nesting of constructs (including subprograms, loops,
6557 blocks, packages, and conditionals) may not exceed the given value
6558 @option{nnn}. A value of zero disconnects this style check.
6559
6560 @item ^m^LINE_LENGTH^
6561 @emph{Check maximum line length.}
6562 The length of source lines must not exceed 79 characters, including
6563 any trailing blanks. The value of 79 allows convenient display on an
6564 80 character wide device or window, allowing for possible special
6565 treatment of 80 character lines. Note that this count is of
6566 characters in the source text. This means that a tab character counts
6567 as one character in this count and a wide character sequence counts as
6568 a single character (however many bytes are needed in the encoding).
6569
6570 @item ^Mnnn^MAX_LENGTH=nnn^
6571 @emph{Set maximum line length.}
6572 The length of lines must not exceed the
6573 given value @option{nnn}. The maximum value that can be specified is 32767.
6574 If neither style option for setting the line length is used, then the
6575 default is 255. This also controls the maximum length of lexical elements,
6576 where the only restriction is that they must fit on a single line.
6577
6578 @item ^n^STANDARD_CASING^
6579 @emph{Check casing of entities in Standard.}
6580 Any identifier from Standard must be cased
6581 to match the presentation in the Ada Reference Manual (for example,
6582 @code{Integer} and @code{ASCII.NUL}).
6583
6584 @item ^N^NONE^
6585 @emph{Turn off all style checks.}
6586 All style check options are turned off.
6587
6588 @item ^o^ORDERED_SUBPROGRAMS^
6589 @emph{Check order of subprogram bodies.}
6590 All subprogram bodies in a given scope
6591 (e.g.@: a package body) must be in alphabetical order. The ordering
6592 rule uses normal Ada rules for comparing strings, ignoring casing
6593 of letters, except that if there is a trailing numeric suffix, then
6594 the value of this suffix is used in the ordering (e.g.@: Junk2 comes
6595 before Junk10).
6596
6597 @item ^O^OVERRIDING_INDICATORS^
6598 @emph{Check that overriding subprograms are explicitly marked as such.}
6599 The declaration of a primitive operation of a type extension that overrides
6600 an inherited operation must carry an overriding indicator.
6601
6602 @item ^p^PRAGMA^
6603 @emph{Check pragma casing.}
6604 Pragma names must be written in mixed case, that is, the
6605 initial letter and any letter following an underscore must be uppercase.
6606 All other letters must be lowercase. An exception is that SPARK_Mode is
6607 allowed as an alternative for Spark_Mode.
6608
6609 @item ^r^REFERENCES^
6610 @emph{Check references.}
6611 All identifier references must be cased in the same way as the
6612 corresponding declaration. No specific casing style is imposed on
6613 identifiers. The only requirement is for consistency of references
6614 with declarations.
6615
6616 @item ^s^SPECS^
6617 @emph{Check separate specs.}
6618 Separate declarations (``specs'') are required for subprograms (a
6619 body is not allowed to serve as its own declaration). The only
6620 exception is that parameterless library level procedures are
6621 not required to have a separate declaration. This exception covers
6622 the most frequent form of main program procedures.
6623
6624 @item ^S^STATEMENTS_AFTER_THEN_ELSE^
6625 @emph{Check no statements after @code{then}/@code{else}.}
6626 No statements are allowed
6627 on the same line as a @code{then} or @code{else} keyword following the
6628 keyword in an @code{if} statement. @code{or else} and @code{and then} are not
6629 affected, and a special exception allows a pragma to appear after @code{else}.
6630
6631 @item ^t^TOKEN^
6632 @emph{Check token spacing.}
6633 The following token spacing rules are enforced:
6634
6635 @itemize @bullet
6636
6637 @item
6638 The keywords @code{abs} and @code{not} must be followed by a space.
6639
6640 @item
6641 The token @code{=>} must be surrounded by spaces.
6642
6643 @item
6644 The token @code{<>} must be preceded by a space or a left parenthesis.
6645
6646 @item
6647 Binary operators other than @code{**} must be surrounded by spaces.
6648 There is no restriction on the layout of the @code{**} binary operator.
6649
6650 @item
6651 Colon must be surrounded by spaces.
6652
6653 @item
6654 Colon-equal (assignment, initialization) must be surrounded by spaces.
6655
6656 @item
6657 Comma must be the first non-blank character on the line, or be
6658 immediately preceded by a non-blank character, and must be followed
6659 by a space.
6660
6661 @item
6662 If the token preceding a left parenthesis ends with a letter or digit, then
6663 a space must separate the two tokens.
6664
6665 @item
6666 if the token following a right parenthesis starts with a letter or digit, then
6667 a space must separate the two tokens.
6668
6669 @item
6670 A right parenthesis must either be the first non-blank character on
6671 a line, or it must be preceded by a non-blank character.
6672
6673 @item
6674 A semicolon must not be preceded by a space, and must not be followed by
6675 a non-blank character.
6676
6677 @item
6678 A unary plus or minus may not be followed by a space.
6679
6680 @item
6681 A vertical bar must be surrounded by spaces.
6682 @end itemize
6683
6684 @item
6685 Exactly one blank (and no other white space) must appear between
6686 a @code{not} token and a following @code{in} token.
6687
6688 @item ^u^UNNECESSARY_BLANK_LINES^
6689 @emph{Check unnecessary blank lines.}
6690 Unnecessary blank lines are not allowed. A blank line is considered
6691 unnecessary if it appears at the end of the file, or if more than
6692 one blank line occurs in sequence.
6693
6694 @item ^x^XTRA_PARENS^
6695 @emph{Check extra parentheses.}
6696 Unnecessary extra level of parentheses (C-style) are not allowed
6697 around conditions in @code{if} statements, @code{while} statements and
6698 @code{exit} statements.
6699
6700 @item ^y^ALL_BUILTIN^
6701 @emph{Set all standard style check options}
6702 This is equivalent to @code{gnaty3aAbcefhiklmnprst}, that is all checking
6703 options enabled with the exception of @option{-gnatyB}, @option{-gnatyd},
6704 @option{-gnatyI}, @option{-gnatyLnnn}, @option{-gnatyo}, @option{-gnatyO},
6705 @option{-gnatyS}, @option{-gnatyu}, and @option{-gnatyx}.
6706
6707 @ifclear vms
6708 @item -
6709 @emph{Remove style check options}
6710 This causes any subsequent options in the string to act as canceling the
6711 corresponding style check option. To cancel maximum nesting level control,
6712 use @option{L} parameter witout any integer value after that, because any
6713 digit following @option{-} in the parameter string of the @option{-gnaty}
6714 option will be threated as canceling indentation check. The same is true
6715 for @option{M} parameter. @option{y} and @option{N} parameters are not
6716 allowed after @option{-}.
6717
6718 @item +
6719 This causes any subsequent options in the string to enable the corresponding
6720 style check option. That is, it cancels the effect of a previous ^-^REMOVE^,
6721 if any.
6722 @end ifclear
6723
6724 @ifset vms
6725 @item NOxxx
6726 @emph{Removing style check options}
6727 If the name of a style check is preceded by @option{NO} then the corresponding
6728 style check is turned off. For example @option{NOCOMMENTS} turns off style
6729 checking for comments.
6730 @end ifset
6731 @end table
6732
6733 @noindent
6734 In the above rules, appearing in column one is always permitted, that is,
6735 counts as meeting either a requirement for a required preceding space,
6736 or as meeting a requirement for no preceding space.
6737
6738 Appearing at the end of a line is also always permitted, that is, counts
6739 as meeting either a requirement for a following space, or as meeting
6740 a requirement for no following space.
6741
6742 @noindent
6743 If any of these style rules is violated, a message is generated giving
6744 details on the violation. The initial characters of such messages are
6745 always ``@code{(style)}''. Note that these messages are treated as warning
6746 messages, so they normally do not prevent the generation of an object
6747 file. The @option{-gnatwe} switch can be used to treat warning messages,
6748 including style messages, as fatal errors.
6749
6750 The switch
6751 @ifclear vms
6752 @option{-gnaty} on its own (that is not
6753 followed by any letters or digits) is equivalent
6754 to the use of @option{-gnatyy} as described above, that is all
6755 built-in standard style check options are enabled.
6756
6757 @end ifclear
6758 @ifset vms
6759 /STYLE_CHECKS=ALL_BUILTIN enables all checking options with
6760 the exception of ORDERED_SUBPROGRAMS, UNNECESSARY_BLANK_LINES,
6761 XTRA_PARENS, and DOS_LINE_ENDINGS. In addition
6762 @end ifset
6763
6764 The switch
6765 @ifclear vms
6766 @option{-gnatyN}
6767 @end ifclear
6768 @ifset vms
6769 /STYLE_CHECKS=NONE
6770 @end ifset
6771 clears any previously set style checks.
6772
6773 @node Run-Time Checks
6774 @subsection Run-Time Checks
6775 @cindex Division by zero
6776 @cindex Access before elaboration
6777 @cindex Checks, division by zero
6778 @cindex Checks, access before elaboration
6779 @cindex Checks, stack overflow checking
6780
6781 @noindent
6782 By default, the following checks are suppressed: integer overflow
6783 checks, stack overflow checks, and checks for access before
6784 elaboration on subprogram calls. All other checks, including range
6785 checks and array bounds checks, are turned on by default. The
6786 following @command{gcc} switches refine this default behavior.
6787
6788 @table @option
6789 @c !sort!
6790 @item -gnatp
6791 @cindex @option{-gnatp} (@command{gcc})
6792 @cindex Suppressing checks
6793 @cindex Checks, suppressing
6794 @findex Suppress
6795 This switch causes the unit to be compiled
6796 as though @code{pragma Suppress (All_checks)}
6797 had been present in the source. Validity checks are also eliminated (in
6798 other words @option{-gnatp} also implies @option{-gnatVn}.
6799 Use this switch to improve the performance
6800 of the code at the expense of safety in the presence of invalid data or
6801 program bugs.
6802
6803 Note that when checks are suppressed, the compiler is allowed, but not
6804 required, to omit the checking code. If the run-time cost of the
6805 checking code is zero or near-zero, the compiler will generate it even
6806 if checks are suppressed. In particular, if the compiler can prove
6807 that a certain check will necessarily fail, it will generate code to
6808 do an unconditional ``raise'', even if checks are suppressed. The
6809 compiler warns in this case. Another case in which checks may not be
6810 eliminated is when they are embedded in certain run time routines such
6811 as math library routines.
6812
6813 Of course, run-time checks are omitted whenever the compiler can prove
6814 that they will not fail, whether or not checks are suppressed.
6815
6816 Note that if you suppress a check that would have failed, program
6817 execution is erroneous, which means the behavior is totally
6818 unpredictable. The program might crash, or print wrong answers, or
6819 do anything else. It might even do exactly what you wanted it to do
6820 (and then it might start failing mysteriously next week or next
6821 year). The compiler will generate code based on the assumption that
6822 the condition being checked is true, which can result in erroneous
6823 execution if that assumption is wrong.
6824
6825 The checks subject to suppression include all the checks defined by
6826 the Ada standard, the additional implementation defined checks
6827 @code{Alignment_Check},
6828 @code{Duplicated_Tag_Check}, @code{Predicate_Check}, and
6829 @code{Validity_Check}, as well as any checks introduced using
6830 @code{pragma Check_Name}. Note that @code{Atomic_Synchronization}
6831 is not automatically suppressed by use of this option.
6832
6833 If the code depends on certain checks being active, you can use
6834 pragma @code{Unsuppress} either as a configuration pragma or as
6835 a local pragma to make sure that a specified check is performed
6836 even if @option{gnatp} is specified.
6837
6838 The @option{-gnatp} switch has no effect if a subsequent
6839 @option{-gnat-p} switch appears.
6840
6841 @item -gnat-p
6842 @cindex @option{-gnat-p} (@command{gcc})
6843 @cindex Suppressing checks
6844 @cindex Checks, suppressing
6845 @findex Suppress
6846 This switch cancels the effect of a previous @option{gnatp} switch.
6847
6848 @item -gnato??
6849 @cindex @option{-gnato??} (@command{gcc})
6850 @cindex Overflow checks
6851 @cindex Overflow mode
6852 @cindex Check, overflow
6853 This switch controls the mode used for computing intermediate
6854 arithmetic integer operations, and also enables overflow checking.
6855 For a full description of overflow mode and checking control, see
6856 the ``Overflow Check Handling in GNAT'' appendix in this
6857 User's Guide.
6858
6859 Overflow checks are always enabled by this switch. The argument
6860 controls the mode, using the codes
6861
6862 @itemize
6863 @item 1 = STRICT
6864 In STRICT mode, intermediate operations are always done using the
6865 base type, and overflow checking ensures that the result is within
6866 the base type range.
6867
6868 @item 2 = MINIMIZED
6869 In MINIMIZED mode, overflows in intermediate operations are avoided
6870 where possible by using a larger integer type for the computation
6871 (typically @code{Long_Long_Integer}). Overflow checking ensures that
6872 the result fits in this larger integer type.
6873
6874 @item 3 = ELIMINATED
6875 In ELIMINATED mode, overflows in intermediate operations are avoided
6876 by using multi-precision arithmetic. In this case, overflow checking
6877 has no effect on intermediate operations (since overflow is impossible).
6878 @end itemize
6879
6880 If two digits are present after @option{-gnato} then the first digit
6881 sets the mode for expressions outside assertions, and the second digit
6882 sets the mode for expressions within assertions. Here assertions is used
6883 in the technical sense (which includes for example precondition and
6884 postcondition expressions).
6885
6886 If one digit is present, the corresponding mode is applicable to both
6887 expressions within and outside assertion expressions.
6888
6889 If no digits are present, the default is to enable overflow checks
6890 and set STRICT mode for both kinds of expressions. This is compatible
6891 with the use of @option{-gnato} in previous versions of GNAT.
6892
6893 @findex Machine_Overflows
6894 Note that the @option{-gnato??} switch does not affect the code generated
6895 for any floating-point operations; it applies only to integer semantics.
6896 For floating-point, @value{EDITION} has the @code{Machine_Overflows}
6897 attribute set to @code{False} and the normal mode of operation is to
6898 generate IEEE NaN and infinite values on overflow or invalid operations
6899 (such as dividing 0.0 by 0.0).
6900
6901 The reason that we distinguish overflow checking from other kinds of
6902 range constraint checking is that a failure of an overflow check, unlike
6903 for example the failure of a range check, can result in an incorrect
6904 value, but cannot cause random memory destruction (like an out of range
6905 subscript), or a wild jump (from an out of range case value). Overflow
6906 checking is also quite expensive in time and space, since in general it
6907 requires the use of double length arithmetic.
6908
6909 Note again that the default is @option{^-gnato00^/OVERFLOW_CHECKS=00^},
6910 so overflow checking is not performed in default mode. This means that out of
6911 the box, with the default settings, @value{EDITION} does not do all the checks
6912 expected from the language description in the Ada Reference Manual.
6913 If you want all constraint checks to be performed, as described in this Manual,
6914 then you must explicitly use the @option{-gnato??}
6915 switch either on the @command{gnatmake} or @command{gcc} command.
6916
6917 @item -gnatE
6918 @cindex @option{-gnatE} (@command{gcc})
6919 @cindex Elaboration checks
6920 @cindex Check, elaboration
6921 Enables dynamic checks for access-before-elaboration
6922 on subprogram calls and generic instantiations.
6923 Note that @option{-gnatE} is not necessary for safety, because in the
6924 default mode, GNAT ensures statically that the checks would not fail.
6925 For full details of the effect and use of this switch,
6926 @xref{Compiling with gcc}.
6927
6928 @item -fstack-check
6929 @cindex @option{-fstack-check} (@command{gcc})
6930 @cindex Stack Overflow Checking
6931 @cindex Checks, stack overflow checking
6932 Activates stack overflow checking. For full details of the effect and use of
6933 this switch see @ref{Stack Overflow Checking}.
6934 @end table
6935
6936 @findex Unsuppress
6937 @noindent
6938 The setting of these switches only controls the default setting of the
6939 checks. You may modify them using either @code{Suppress} (to remove
6940 checks) or @code{Unsuppress} (to add back suppressed checks) pragmas in
6941 the program source.
6942
6943 @node Using gcc for Syntax Checking
6944 @subsection Using @command{gcc} for Syntax Checking
6945 @table @option
6946 @item -gnats
6947 @cindex @option{-gnats} (@command{gcc})
6948 @ifclear vms
6949
6950 @noindent
6951 The @code{s} stands for ``syntax''.
6952 @end ifclear
6953
6954 Run GNAT in syntax checking only mode. For
6955 example, the command
6956
6957 @smallexample
6958 $ gcc -c -gnats x.adb
6959 @end smallexample
6960
6961 @noindent
6962 compiles file @file{x.adb} in syntax-check-only mode. You can check a
6963 series of files in a single command
6964 @ifclear vms
6965 , and can use wild cards to specify such a group of files.
6966 Note that you must specify the @option{-c} (compile
6967 only) flag in addition to the @option{-gnats} flag.
6968 @end ifclear
6969 .
6970 You may use other switches in conjunction with @option{-gnats}. In
6971 particular, @option{-gnatl} and @option{-gnatv} are useful to control the
6972 format of any generated error messages.
6973
6974 When the source file is empty or contains only empty lines and/or comments,
6975 the output is a warning:
6976
6977 @smallexample
6978 $ gcc -c -gnats -x ada toto.txt
6979 toto.txt:1:01: warning: empty file, contains no compilation units
6980 $
6981 @end smallexample
6982
6983 Otherwise, the output is simply the error messages, if any. No object file or
6984 ALI file is generated by a syntax-only compilation. Also, no units other
6985 than the one specified are accessed. For example, if a unit @code{X}
6986 @code{with}'s a unit @code{Y}, compiling unit @code{X} in syntax
6987 check only mode does not access the source file containing unit
6988 @code{Y}.
6989
6990 @cindex Multiple units, syntax checking
6991 Normally, GNAT allows only a single unit in a source file. However, this
6992 restriction does not apply in syntax-check-only mode, and it is possible
6993 to check a file containing multiple compilation units concatenated
6994 together. This is primarily used by the @code{gnatchop} utility
6995 (@pxref{Renaming Files with gnatchop}).
6996 @end table
6997
6998 @node Using gcc for Semantic Checking
6999 @subsection Using @command{gcc} for Semantic Checking
7000 @table @option
7001 @item -gnatc
7002 @cindex @option{-gnatc} (@command{gcc})
7003
7004 @ifclear vms
7005 @noindent
7006 The @code{c} stands for ``check''.
7007 @end ifclear
7008 Causes the compiler to operate in semantic check mode,
7009 with full checking for all illegalities specified in the
7010 Ada Reference Manual, but without generation of any object code
7011 (no object file is generated).
7012
7013 Because dependent files must be accessed, you must follow the GNAT
7014 semantic restrictions on file structuring to operate in this mode:
7015
7016 @itemize @bullet
7017 @item
7018 The needed source files must be accessible
7019 (@pxref{Search Paths and the Run-Time Library (RTL)}).
7020
7021 @item
7022 Each file must contain only one compilation unit.
7023
7024 @item
7025 The file name and unit name must match (@pxref{File Naming Rules}).
7026 @end itemize
7027
7028 The output consists of error messages as appropriate. No object file is
7029 generated. An @file{ALI} file is generated for use in the context of
7030 cross-reference tools, but this file is marked as not being suitable
7031 for binding (since no object file is generated).
7032 The checking corresponds exactly to the notion of
7033 legality in the Ada Reference Manual.
7034
7035 Any unit can be compiled in semantics-checking-only mode, including
7036 units that would not normally be compiled (subunits,
7037 and specifications where a separate body is present).
7038 @end table
7039
7040 @node Compiling Different Versions of Ada
7041 @subsection Compiling Different Versions of Ada
7042
7043 @noindent
7044 The switches described in this section allow you to explicitly specify
7045 the version of the Ada language that your programs are written in.
7046 The default mode is Ada 2012,
7047 but you can also specify Ada 95, Ada 2005 mode, or
7048 indicate Ada 83 compatibility mode.
7049
7050 @table @option
7051 @cindex Compatibility with Ada 83
7052
7053 @item -gnat83 (Ada 83 Compatibility Mode)
7054 @cindex @option{-gnat83} (@command{gcc})
7055 @cindex ACVC, Ada 83 tests
7056 @cindex Ada 83 mode
7057
7058 @noindent
7059 Although GNAT is primarily an Ada 95 / Ada 2005 compiler, this switch
7060 specifies that the program is to be compiled in Ada 83 mode. With
7061 @option{-gnat83}, GNAT rejects most post-Ada 83 extensions and applies Ada 83
7062 semantics where this can be done easily.
7063 It is not possible to guarantee this switch does a perfect
7064 job; some subtle tests, such as are
7065 found in earlier ACVC tests (and that have been removed from the ACATS suite
7066 for Ada 95), might not compile correctly.
7067 Nevertheless, this switch may be useful in some circumstances, for example
7068 where, due to contractual reasons, existing code needs to be maintained
7069 using only Ada 83 features.
7070
7071 With few exceptions (most notably the need to use @code{<>} on
7072 @cindex Generic formal parameters
7073 unconstrained generic formal parameters, the use of the new Ada 95 / Ada 2005
7074 reserved words, and the use of packages
7075 with optional bodies), it is not necessary to specify the
7076 @option{-gnat83} switch when compiling Ada 83 programs, because, with rare
7077 exceptions, Ada 95 and Ada 2005 are upwardly compatible with Ada 83. Thus
7078 a correct Ada 83 program is usually also a correct program
7079 in these later versions of the language standard.
7080 For further information, please refer to @ref{Compatibility and Porting Guide}.
7081
7082 @item -gnat95 (Ada 95 mode)
7083 @cindex @option{-gnat95} (@command{gcc})
7084 @cindex Ada 95 mode
7085
7086 @noindent
7087 This switch directs the compiler to implement the Ada 95 version of the
7088 language.
7089 Since Ada 95 is almost completely upwards
7090 compatible with Ada 83, Ada 83 programs may generally be compiled using
7091 this switch (see the description of the @option{-gnat83} switch for further
7092 information about Ada 83 mode).
7093 If an Ada 2005 program is compiled in Ada 95 mode,
7094 uses of the new Ada 2005 features will cause error
7095 messages or warnings.
7096
7097 This switch also can be used to cancel the effect of a previous
7098 @option{-gnat83}, @option{-gnat05/2005}, or @option{-gnat12/2012}
7099 switch earlier in the command line.
7100
7101 @item -gnat05 or -gnat2005 (Ada 2005 mode)
7102 @cindex @option{-gnat05} (@command{gcc})
7103 @cindex @option{-gnat2005} (@command{gcc})
7104 @cindex Ada 2005 mode
7105
7106 @noindent
7107 This switch directs the compiler to implement the Ada 2005 version of the
7108 language, as documented in the official Ada standards document.
7109 Since Ada 2005 is almost completely upwards
7110 compatible with Ada 95 (and thus also with Ada 83), Ada 83 and Ada 95 programs
7111 may generally be compiled using this switch (see the description of the
7112 @option{-gnat83} and @option{-gnat95} switches for further
7113 information).
7114
7115 @item -gnat12 or -gnat2012 (Ada 2012 mode)
7116 @cindex @option{-gnat12} (@command{gcc})
7117 @cindex @option{-gnat2012} (@command{gcc})
7118 @cindex Ada 2012 mode
7119
7120 @noindent
7121 This switch directs the compiler to implement the Ada 2012 version of the
7122 language (also the default).
7123 Since Ada 2012 is almost completely upwards
7124 compatible with Ada 2005 (and thus also with Ada 83, and Ada 95),
7125 Ada 83 and Ada 95 programs
7126 may generally be compiled using this switch (see the description of the
7127 @option{-gnat83}, @option{-gnat95}, and @option{-gnat05/2005} switches
7128 for further information).
7129
7130 @item -gnatX (Enable GNAT Extensions)
7131 @cindex @option{-gnatX} (@command{gcc})
7132 @cindex Ada language extensions
7133 @cindex GNAT extensions
7134
7135 @noindent
7136 This switch directs the compiler to implement the latest version of the
7137 language (currently Ada 2012) and also to enable certain GNAT implementation
7138 extensions that are not part of any Ada standard. For a full list of these
7139 extensions, see the GNAT reference manual.
7140
7141 @end table
7142
7143 @node Character Set Control
7144 @subsection Character Set Control
7145 @table @option
7146 @item ^-gnati^/IDENTIFIER_CHARACTER_SET=^@var{c}
7147 @cindex @option{^-gnati^/IDENTIFIER_CHARACTER_SET^} (@command{gcc})
7148
7149 @noindent
7150 Normally GNAT recognizes the Latin-1 character set in source program
7151 identifiers, as described in the Ada Reference Manual.
7152 This switch causes
7153 GNAT to recognize alternate character sets in identifiers. @var{c} is a
7154 single character ^^or word^ indicating the character set, as follows:
7155
7156 @table @code
7157 @item 1
7158 ISO 8859-1 (Latin-1) identifiers
7159
7160 @item 2
7161 ISO 8859-2 (Latin-2) letters allowed in identifiers
7162
7163 @item 3
7164 ISO 8859-3 (Latin-3) letters allowed in identifiers
7165
7166 @item 4
7167 ISO 8859-4 (Latin-4) letters allowed in identifiers
7168
7169 @item 5
7170 ISO 8859-5 (Cyrillic) letters allowed in identifiers
7171
7172 @item 9
7173 ISO 8859-15 (Latin-9) letters allowed in identifiers
7174
7175 @item ^p^PC^
7176 IBM PC letters (code page 437) allowed in identifiers
7177
7178 @item ^8^PC850^
7179 IBM PC letters (code page 850) allowed in identifiers
7180
7181 @item ^f^FULL_UPPER^
7182 Full upper-half codes allowed in identifiers
7183
7184 @item ^n^NO_UPPER^
7185 No upper-half codes allowed in identifiers
7186
7187 @item ^w^WIDE^
7188 Wide-character codes (that is, codes greater than 255)
7189 allowed in identifiers
7190 @end table
7191
7192 @xref{Foreign Language Representation}, for full details on the
7193 implementation of these character sets.
7194
7195 @item ^-gnatW^/WIDE_CHARACTER_ENCODING=^@var{e}
7196 @cindex @option{^-gnatW^/WIDE_CHARACTER_ENCODING^} (@command{gcc})
7197 Specify the method of encoding for wide characters.
7198 @var{e} is one of the following:
7199
7200 @table @code
7201
7202 @item ^h^HEX^
7203 Hex encoding (brackets coding also recognized)
7204
7205 @item ^u^UPPER^
7206 Upper half encoding (brackets encoding also recognized)
7207
7208 @item ^s^SHIFT_JIS^
7209 Shift/JIS encoding (brackets encoding also recognized)
7210
7211 @item ^e^EUC^
7212 EUC encoding (brackets encoding also recognized)
7213
7214 @item ^8^UTF8^
7215 UTF-8 encoding (brackets encoding also recognized)
7216
7217 @item ^b^BRACKETS^
7218 Brackets encoding only (default value)
7219 @end table
7220 For full details on these encoding
7221 methods see @ref{Wide Character Encodings}.
7222 Note that brackets coding is always accepted, even if one of the other
7223 options is specified, so for example @option{-gnatW8} specifies that both
7224 brackets and UTF-8 encodings will be recognized. The units that are
7225 with'ed directly or indirectly will be scanned using the specified
7226 representation scheme, and so if one of the non-brackets scheme is
7227 used, it must be used consistently throughout the program. However,
7228 since brackets encoding is always recognized, it may be conveniently
7229 used in standard libraries, allowing these libraries to be used with
7230 any of the available coding schemes.
7231
7232 Note that brackets encoding only applies to program text. Within comments,
7233 brackets are considered to be normal graphic characters, and bracket sequences
7234 are never recognized as wide characters.
7235
7236 If no @option{-gnatW?} parameter is present, then the default
7237 representation is normally Brackets encoding only. However, if the
7238 first three characters of the file are 16#EF# 16#BB# 16#BF# (the standard
7239 byte order mark or BOM for UTF-8), then these three characters are
7240 skipped and the default representation for the file is set to UTF-8.
7241
7242 Note that the wide character representation that is specified (explicitly
7243 or by default) for the main program also acts as the default encoding used
7244 for Wide_Text_IO files if not specifically overridden by a WCEM form
7245 parameter.
7246
7247 @end table
7248
7249 When no @option{-gnatW?} is specified, then characters (other than wide
7250 characters represented using brackets notation) are treated as 8-bit
7251 Latin-1 codes. The codes recognized are the Latin-1 graphic characters,
7252 and ASCII format effectors (CR, LF, HT, VT). Other lower half control
7253 characters in the range 16#00#..16#1F# are not accepted in program text
7254 or in comments. Upper half control characters (16#80#..16#9F#) are rejected
7255 in program text, but allowed and ignored in comments. Note in particular
7256 that the Next Line (NEL) character whose encoding is 16#85# is not recognized
7257 as an end of line in this default mode. If your source program contains
7258 instances of the NEL character used as a line terminator,
7259 you must use UTF-8 encoding for the whole
7260 source program. In default mode, all lines must be ended by a standard
7261 end of line sequence (CR, CR/LF, or LF).
7262
7263 Note that the convention of simply accepting all upper half characters in
7264 comments means that programs that use standard ASCII for program text, but
7265 UTF-8 encoding for comments are accepted in default mode, providing that the
7266 comments are ended by an appropriate (CR, or CR/LF, or LF) line terminator.
7267 This is a common mode for many programs with foreign language comments.
7268
7269 @node File Naming Control
7270 @subsection File Naming Control
7271
7272 @table @option
7273 @item ^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{n}
7274 @cindex @option{-gnatk} (@command{gcc})
7275 Activates file name ``krunching''. @var{n}, a decimal integer in the range
7276 1-999, indicates the maximum allowable length of a file name (not
7277 including the @file{.ads} or @file{.adb} extension). The default is not
7278 to enable file name krunching.
7279
7280 For the source file naming rules, @xref{File Naming Rules}.
7281 @end table
7282
7283 @node Subprogram Inlining Control
7284 @subsection Subprogram Inlining Control
7285
7286 @table @option
7287 @c !sort!
7288 @item -gnatn[12]
7289 @cindex @option{-gnatn} (@command{gcc})
7290 @ifclear vms
7291 The @code{n} here is intended to suggest the first syllable of the
7292 word ``inline''.
7293 @end ifclear
7294 GNAT recognizes and processes @code{Inline} pragmas. However, for the
7295 inlining to actually occur, optimization must be enabled and, in order
7296 to enable inlining of subprograms specified by pragma @code{Inline},
7297 you must also specify this switch.
7298 In the absence of this switch, GNAT does not attempt
7299 inlining and does not need to access the bodies of
7300 subprograms for which @code{pragma Inline} is specified if they are not
7301 in the current unit.
7302
7303 You can optionally specify the inlining level: 1 for moderate inlining across
7304 modules, which is a good compromise between compilation times and performances
7305 at run time, or 2 for full inlining across modules, which may bring about
7306 longer compilation times. If no inlining level is specified, the compiler will
7307 pick it based on the optimization level: 1 for @option{-O1}, @option{-O2} or
7308 @option{-Os} and 2 for @option{-O3}.
7309
7310 If you specify this switch the compiler will access these bodies,
7311 creating an extra source dependency for the resulting object file, and
7312 where possible, the call will be inlined.
7313 For further details on when inlining is possible
7314 see @ref{Inlining of Subprograms}.
7315
7316 @item -gnatN
7317 @cindex @option{-gnatN} (@command{gcc})
7318 This switch activates front-end inlining which also
7319 generates additional dependencies.
7320
7321 When using a gcc-based back end (in practice this means using any version
7322 of GNAT other than the JGNAT, .NET or GNAAMP versions), then the use of
7323 @option{-gnatN} is deprecated, and the use of @option{-gnatn} is preferred.
7324 Historically front end inlining was more extensive than the gcc back end
7325 inlining, but that is no longer the case.
7326 @end table
7327
7328 @node Auxiliary Output Control
7329 @subsection Auxiliary Output Control
7330
7331 @table @option
7332 @item -gnatt
7333 @cindex @option{-gnatt} (@command{gcc})
7334 @cindex Writing internal trees
7335 @cindex Internal trees, writing to file
7336 Causes GNAT to write the internal tree for a unit to a file (with the
7337 extension @file{.adt}.
7338 This not normally required, but is used by separate analysis tools.
7339 Typically
7340 these tools do the necessary compilations automatically, so you should
7341 not have to specify this switch in normal operation.
7342 Note that the combination of switches @option{-gnatct}
7343 generates a tree in the form required by ASIS applications.
7344
7345 @item -gnatu
7346 @cindex @option{-gnatu} (@command{gcc})
7347 Print a list of units required by this compilation on @file{stdout}.
7348 The listing includes all units on which the unit being compiled depends
7349 either directly or indirectly.
7350
7351 @ifclear vms
7352 @item -pass-exit-codes
7353 @cindex @option{-pass-exit-codes} (@command{gcc})
7354 If this switch is not used, the exit code returned by @command{gcc} when
7355 compiling multiple files indicates whether all source files have
7356 been successfully used to generate object files or not.
7357
7358 When @option{-pass-exit-codes} is used, @command{gcc} exits with an extended
7359 exit status and allows an integrated development environment to better
7360 react to a compilation failure. Those exit status are:
7361
7362 @table @asis
7363 @item 5
7364 There was an error in at least one source file.
7365 @item 3
7366 At least one source file did not generate an object file.
7367 @item 2
7368 The compiler died unexpectedly (internal error for example).
7369 @item 0
7370 An object file has been generated for every source file.
7371 @end table
7372 @end ifclear
7373 @end table
7374
7375 @node Debugging Control
7376 @subsection Debugging Control
7377
7378 @table @option
7379 @c !sort!
7380 @cindex Debugging options
7381 @ifclear vms
7382 @item -gnatd@var{x}
7383 @cindex @option{-gnatd} (@command{gcc})
7384 Activate internal debugging switches. @var{x} is a letter or digit, or
7385 string of letters or digits, which specifies the type of debugging
7386 outputs desired. Normally these are used only for internal development
7387 or system debugging purposes. You can find full documentation for these
7388 switches in the body of the @code{Debug} unit in the compiler source
7389 file @file{debug.adb}.
7390 @end ifclear
7391
7392 @item -gnatG[=nn]
7393 @cindex @option{-gnatG} (@command{gcc})
7394 This switch causes the compiler to generate auxiliary output containing
7395 a pseudo-source listing of the generated expanded code. Like most Ada
7396 compilers, GNAT works by first transforming the high level Ada code into
7397 lower level constructs. For example, tasking operations are transformed
7398 into calls to the tasking run-time routines. A unique capability of GNAT
7399 is to list this expanded code in a form very close to normal Ada source.
7400 This is very useful in understanding the implications of various Ada
7401 usage on the efficiency of the generated code. There are many cases in
7402 Ada (e.g.@: the use of controlled types), where simple Ada statements can
7403 generate a lot of run-time code. By using @option{-gnatG} you can identify
7404 these cases, and consider whether it may be desirable to modify the coding
7405 approach to improve efficiency.
7406
7407 The optional parameter @code{nn} if present after -gnatG specifies an
7408 alternative maximum line length that overrides the normal default of 72.
7409 This value is in the range 40-999999, values less than 40 being silently
7410 reset to 40. The equal sign is optional.
7411
7412 The format of the output is very similar to standard Ada source, and is
7413 easily understood by an Ada programmer. The following special syntactic
7414 additions correspond to low level features used in the generated code that
7415 do not have any exact analogies in pure Ada source form. The following
7416 is a partial list of these special constructions. See the spec
7417 of package @code{Sprint} in file @file{sprint.ads} for a full list.
7418
7419 If the switch @option{-gnatL} is used in conjunction with
7420 @cindex @option{-gnatL} (@command{gcc})
7421 @option{-gnatG}, then the original source lines are interspersed
7422 in the expanded source (as comment lines with the original line number).
7423
7424 @table @code
7425 @item new @var{xxx} @r{[}storage_pool = @var{yyy}@r{]}
7426 Shows the storage pool being used for an allocator.
7427
7428 @item at end @var{procedure-name};
7429 Shows the finalization (cleanup) procedure for a scope.
7430
7431 @item (if @var{expr} then @var{expr} else @var{expr})
7432 Conditional expression equivalent to the @code{x?y:z} construction in C.
7433
7434 @item @var{target}^^^(@var{source})
7435 A conversion with floating-point truncation instead of rounding.
7436
7437 @item @var{target}?(@var{source})
7438 A conversion that bypasses normal Ada semantic checking. In particular
7439 enumeration types and fixed-point types are treated simply as integers.
7440
7441 @item @var{target}?^^^(@var{source})
7442 Combines the above two cases.
7443
7444 @item @var{x} #/ @var{y}
7445 @itemx @var{x} #mod @var{y}
7446 @itemx @var{x} #* @var{y}
7447 @itemx @var{x} #rem @var{y}
7448 A division or multiplication of fixed-point values which are treated as
7449 integers without any kind of scaling.
7450
7451 @item free @var{expr} @r{[}storage_pool = @var{xxx}@r{]}
7452 Shows the storage pool associated with a @code{free} statement.
7453
7454 @item [subtype or type declaration]
7455 Used to list an equivalent declaration for an internally generated
7456 type that is referenced elsewhere in the listing.
7457
7458 @c @item freeze @var{type-name} @ovar{actions}
7459 @c Expanding @ovar macro inline (explanation in macro def comments)
7460 @item freeze @var{type-name} @r{[}@var{actions}@r{]}
7461 Shows the point at which @var{type-name} is frozen, with possible
7462 associated actions to be performed at the freeze point.
7463
7464 @item reference @var{itype}
7465 Reference (and hence definition) to internal type @var{itype}.
7466
7467 @item @var{function-name}! (@var{arg}, @var{arg}, @var{arg})
7468 Intrinsic function call.
7469
7470 @item @var{label-name} : label
7471 Declaration of label @var{labelname}.
7472
7473 @item #$ @var{subprogram-name}
7474 An implicit call to a run-time support routine
7475 (to meet the requirement of H.3.1(9) in a
7476 convenient manner).
7477
7478 @item @var{expr} && @var{expr} && @var{expr} @dots{} && @var{expr}
7479 A multiple concatenation (same effect as @var{expr} & @var{expr} &
7480 @var{expr}, but handled more efficiently).
7481
7482 @item [constraint_error]
7483 Raise the @code{Constraint_Error} exception.
7484
7485 @item @var{expression}'reference
7486 A pointer to the result of evaluating @var{expression}.
7487
7488 @item @var{target-type}!(@var{source-expression})
7489 An unchecked conversion of @var{source-expression} to @var{target-type}.
7490
7491 @item [@var{numerator}/@var{denominator}]
7492 Used to represent internal real literals (that) have no exact
7493 representation in base 2-16 (for example, the result of compile time
7494 evaluation of the expression 1.0/27.0).
7495 @end table
7496
7497 @item -gnatD[=nn]
7498 @cindex @option{-gnatD} (@command{gcc})
7499 When used in conjunction with @option{-gnatG}, this switch causes
7500 the expanded source, as described above for
7501 @option{-gnatG} to be written to files with names
7502 @file{^xxx.dg^XXX_DG^}, where @file{xxx} is the normal file name,
7503 instead of to the standard output file. For
7504 example, if the source file name is @file{hello.adb}, then a file
7505 @file{^hello.adb.dg^HELLO.ADB_DG^} will be written. The debugging
7506 information generated by the @command{gcc} @option{^-g^/DEBUG^} switch
7507 will refer to the generated @file{^xxx.dg^XXX_DG^} file. This allows
7508 you to do source level debugging using the generated code which is
7509 sometimes useful for complex code, for example to find out exactly
7510 which part of a complex construction raised an exception. This switch
7511 also suppress generation of cross-reference information (see
7512 @option{-gnatx}) since otherwise the cross-reference information
7513 would refer to the @file{^.dg^.DG^} file, which would cause
7514 confusion since this is not the original source file.
7515
7516 Note that @option{-gnatD} actually implies @option{-gnatG}
7517 automatically, so it is not necessary to give both options.
7518 In other words @option{-gnatD} is equivalent to @option{-gnatDG}).
7519
7520 If the switch @option{-gnatL} is used in conjunction with
7521 @cindex @option{-gnatL} (@command{gcc})
7522 @option{-gnatDG}, then the original source lines are interspersed
7523 in the expanded source (as comment lines with the original line number).
7524
7525 The optional parameter @code{nn} if present after -gnatD specifies an
7526 alternative maximum line length that overrides the normal default of 72.
7527 This value is in the range 40-999999, values less than 40 being silently
7528 reset to 40. The equal sign is optional.
7529
7530 @item -gnatr
7531 @cindex @option{-gnatr} (@command{gcc})
7532 @cindex pragma Restrictions
7533 This switch causes pragma Restrictions to be treated as Restriction_Warnings
7534 so that violation of restrictions causes warnings rather than illegalities.
7535 This is useful during the development process when new restrictions are added
7536 or investigated. The switch also causes pragma Profile to be treated as
7537 Profile_Warnings, and pragma Restricted_Run_Time and pragma Ravenscar set
7538 restriction warnings rather than restrictions.
7539
7540 @ifclear vms
7541 @item -gnatR@r{[}0@r{|}1@r{|}2@r{|}3@r{[}s@r{]]}
7542 @cindex @option{-gnatR} (@command{gcc})
7543 This switch controls output from the compiler of a listing showing
7544 representation information for declared types and objects. For
7545 @option{-gnatR0}, no information is output (equivalent to omitting
7546 the @option{-gnatR} switch). For @option{-gnatR1} (which is the default,
7547 so @option{-gnatR} with no parameter has the same effect), size and alignment
7548 information is listed for declared array and record types. For
7549 @option{-gnatR2}, size and alignment information is listed for all
7550 declared types and objects. The @code{Linker_Section} is also listed for any
7551 entity for which the @code{Linker_Section} is set explicitly or implicitly (the
7552 latter case occurs for objects of a type for which a @code{Linker_Section}
7553 is set).
7554
7555 Finally @option{-gnatR3} includes symbolic
7556 expressions for values that are computed at run time for
7557 variant records. These symbolic expressions have a mostly obvious
7558 format with #n being used to represent the value of the n'th
7559 discriminant. See source files @file{repinfo.ads/adb} in the
7560 @code{GNAT} sources for full details on the format of @option{-gnatR3}
7561 output. If the switch is followed by an s (e.g.@: @option{-gnatR2s}), then
7562 the output is to a file with the name @file{^file.rep^file_REP^} where
7563 file is the name of the corresponding source file.
7564
7565 @item -gnatRm[s]
7566 This form of the switch controls output of subprogram conventions
7567 and parameter passing mechanisms for all subprograms. A following
7568 @code{s} means output to a file as described above.
7569 @end ifclear
7570 @ifset vms
7571 @item /REPRESENTATION_INFO
7572 @cindex @option{/REPRESENTATION_INFO} (@command{gcc})
7573 This qualifier controls output from the compiler of a listing showing
7574 representation information for declared types and objects. For
7575 @option{/REPRESENTATION_INFO=NONE}, no information is output
7576 (equivalent to omitting the @option{/REPRESENTATION_INFO} qualifier).
7577 @option{/REPRESENTATION_INFO} without option is equivalent to
7578 @option{/REPRESENTATION_INFO=ARRAYS}.
7579 For @option{/REPRESENTATION_INFO=ARRAYS}, size and alignment
7580 information is listed for declared array and record types. For
7581 @option{/REPRESENTATION_INFO=OBJECTS}, size and alignment information
7582 is listed for all expression information for values that are computed
7583 at run time for variant records. These symbolic expressions have a mostly
7584 obvious format with #n being used to represent the value of the n'th
7585 discriminant. See source files @file{REPINFO.ADS/ADB} in the
7586 @code{GNAT} sources for full details on the format of
7587 @option{/REPRESENTATION_INFO=SYMBOLIC} output.
7588 If _FILE is added at the end of an option
7589 (e.g.@: @option{/REPRESENTATION_INFO=ARRAYS_FILE}),
7590 then the output is to a file with the name @file{file_REP} where
7591 file is the name of the corresponding source file.
7592
7593 @item /REPRESENTATION_INFO=MECHANISMS
7594 This qualifier form controls output of subprogram conventions
7595 and parameter passing mechanisms for all subprograms. It is
7596 possible to append _FILE as described above to cause information
7597 to be written to a file.
7598 @end ifset
7599
7600 Note that it is possible for record components to have zero size. In
7601 this case, the component clause uses an obvious extension of permitted
7602 Ada syntax, for example @code{at 0 range 0 .. -1}.
7603
7604 Representation information requires that code be generated (since it is the
7605 code generator that lays out complex data structures). If an attempt is made
7606 to output representation information when no code is generated, for example
7607 when a subunit is compiled on its own, then no information can be generated
7608 and the compiler outputs a message to this effect.
7609
7610 @item -gnatS
7611 @cindex @option{-gnatS} (@command{gcc})
7612 The use of the switch @option{-gnatS} for an
7613 Ada compilation will cause the compiler to output a
7614 representation of package Standard in a form very
7615 close to standard Ada. It is not quite possible to
7616 do this entirely in standard Ada (since new
7617 numeric base types cannot be created in standard
7618 Ada), but the output is easily
7619 readable to any Ada programmer, and is useful to
7620 determine the characteristics of target dependent
7621 types in package Standard.
7622
7623 @item -gnatx
7624 @cindex @option{-gnatx} (@command{gcc})
7625 Normally the compiler generates full cross-referencing information in
7626 the @file{ALI} file. This information is used by a number of tools,
7627 including @code{gnatfind} and @code{gnatxref}. The @option{-gnatx} switch
7628 suppresses this information. This saves some space and may slightly
7629 speed up compilation, but means that these tools cannot be used.
7630 @end table
7631
7632 @node Exception Handling Control
7633 @subsection Exception Handling Control
7634
7635 @noindent
7636 GNAT uses two methods for handling exceptions at run-time. The
7637 @code{setjmp/longjmp} method saves the context when entering
7638 a frame with an exception handler. Then when an exception is
7639 raised, the context can be restored immediately, without the
7640 need for tracing stack frames. This method provides very fast
7641 exception propagation, but introduces significant overhead for
7642 the use of exception handlers, even if no exception is raised.
7643
7644 The other approach is called ``zero cost'' exception handling.
7645 With this method, the compiler builds static tables to describe
7646 the exception ranges. No dynamic code is required when entering
7647 a frame containing an exception handler. When an exception is
7648 raised, the tables are used to control a back trace of the
7649 subprogram invocation stack to locate the required exception
7650 handler. This method has considerably poorer performance for
7651 the propagation of exceptions, but there is no overhead for
7652 exception handlers if no exception is raised. Note that in this
7653 mode and in the context of mixed Ada and C/C++ programming,
7654 to propagate an exception through a C/C++ code, the C/C++ code
7655 must be compiled with the @option{-funwind-tables} GCC's
7656 option.
7657
7658 The following switches may be used to control which of the
7659 two exception handling methods is used.
7660
7661 @table @option
7662 @c !sort!
7663
7664 @item --RTS=sjlj
7665 @cindex @option{--RTS=sjlj} (@command{gnatmake})
7666 This switch causes the setjmp/longjmp run-time (when available) to be used
7667 for exception handling. If the default
7668 mechanism for the target is zero cost exceptions, then
7669 this switch can be used to modify this default, and must be
7670 used for all units in the partition.
7671 This option is rarely used. One case in which it may be
7672 advantageous is if you have an application where exception
7673 raising is common and the overall performance of the
7674 application is improved by favoring exception propagation.
7675
7676 @item --RTS=zcx
7677 @cindex @option{--RTS=zcx} (@command{gnatmake})
7678 @cindex Zero Cost Exceptions
7679 This switch causes the zero cost approach to be used
7680 for exception handling. If this is the default mechanism for the
7681 target (see below), then this switch is unneeded. If the default
7682 mechanism for the target is setjmp/longjmp exceptions, then
7683 this switch can be used to modify this default, and must be
7684 used for all units in the partition.
7685 This option can only be used if the zero cost approach
7686 is available for the target in use, otherwise it will generate an error.
7687 @end table
7688
7689 @noindent
7690 The same option @option{--RTS} must be used both for @command{gcc}
7691 and @command{gnatbind}. Passing this option to @command{gnatmake}
7692 (@pxref{Switches for gnatmake}) will ensure the required consistency
7693 through the compilation and binding steps.
7694
7695 @node Units to Sources Mapping Files
7696 @subsection Units to Sources Mapping Files
7697
7698 @table @option
7699
7700 @item -gnatem=@var{path}
7701 @cindex @option{-gnatem} (@command{gcc})
7702 A mapping file is a way to communicate to the compiler two mappings:
7703 from unit names to file names (without any directory information) and from
7704 file names to path names (with full directory information). These mappings
7705 are used by the compiler to short-circuit the path search.
7706
7707 The use of mapping files is not required for correct operation of the
7708 compiler, but mapping files can improve efficiency, particularly when
7709 sources are read over a slow network connection. In normal operation,
7710 you need not be concerned with the format or use of mapping files,
7711 and the @option{-gnatem} switch is not a switch that you would use
7712 explicitly. It is intended primarily for use by automatic tools such as
7713 @command{gnatmake} running under the project file facility. The
7714 description here of the format of mapping files is provided
7715 for completeness and for possible use by other tools.
7716
7717 A mapping file is a sequence of sets of three lines. In each set, the
7718 first line is the unit name, in lower case, with @code{%s} appended
7719 for specs and @code{%b} appended for bodies; the second line is the
7720 file name; and the third line is the path name.
7721
7722 Example:
7723 @smallexample
7724 main%b
7725 main.2.ada
7726 /gnat/project1/sources/main.2.ada
7727 @end smallexample
7728
7729 When the switch @option{-gnatem} is specified, the compiler will
7730 create in memory the two mappings from the specified file. If there is
7731 any problem (nonexistent file, truncated file or duplicate entries),
7732 no mapping will be created.
7733
7734 Several @option{-gnatem} switches may be specified; however, only the
7735 last one on the command line will be taken into account.
7736
7737 When using a project file, @command{gnatmake} creates a temporary
7738 mapping file and communicates it to the compiler using this switch.
7739
7740 @end table
7741
7742 @node Integrated Preprocessing
7743 @subsection Integrated Preprocessing
7744
7745 @noindent
7746 GNAT sources may be preprocessed immediately before compilation.
7747 In this case, the actual
7748 text of the source is not the text of the source file, but is derived from it
7749 through a process called preprocessing. Integrated preprocessing is specified
7750 through switches @option{-gnatep} and/or @option{-gnateD}. @option{-gnatep}
7751 indicates, through a text file, the preprocessing data to be used.
7752 @option{-gnateD} specifies or modifies the values of preprocessing symbol.
7753 Note that integrated preprocessing applies only to Ada source files, it is
7754 not available for configuration pragma files.
7755
7756 @noindent
7757 Note that when integrated preprocessing is used, the output from the
7758 preprocessor is not written to any external file. Instead it is passed
7759 internally to the compiler. If you need to preserve the result of
7760 preprocessing in a file, then you should use @command{gnatprep}
7761 to perform the desired preprocessing in stand-alone mode.
7762
7763 @noindent
7764 It is recommended that @command{gnatmake} switch ^-s^/SWITCH_CHECK^ should be
7765 used when Integrated Preprocessing is used. The reason is that preprocessing
7766 with another Preprocessing Data file without changing the sources will
7767 not trigger recompilation without this switch.
7768
7769 @noindent
7770 Note that @command{gnatmake} switch ^-m^/MINIMAL_RECOMPILATION^ will almost
7771 always trigger recompilation for sources that are preprocessed,
7772 because @command{gnatmake} cannot compute the checksum of the source after
7773 preprocessing.
7774
7775 @noindent
7776 The actual preprocessing function is described in details in section
7777 @ref{Preprocessing with gnatprep}. This section only describes how integrated
7778 preprocessing is triggered and parameterized.
7779
7780 @table @code
7781
7782 @item -gnatep=@var{file}
7783 @cindex @option{-gnatep} (@command{gcc})
7784 This switch indicates to the compiler the file name (without directory
7785 information) of the preprocessor data file to use. The preprocessor data file
7786 should be found in the source directories. Note that when the compiler is
7787 called by a builder such as (@command{gnatmake} with a project
7788 file, if the object directory is not also a source directory, the builder needs
7789 to be called with @option{-x}.
7790
7791 @noindent
7792 A preprocessing data file is a text file with significant lines indicating
7793 how should be preprocessed either a specific source or all sources not
7794 mentioned in other lines. A significant line is a nonempty, non-comment line.
7795 Comments are similar to Ada comments.
7796
7797 @noindent
7798 Each significant line starts with either a literal string or the character '*'.
7799 A literal string is the file name (without directory information) of the source
7800 to preprocess. A character '*' indicates the preprocessing for all the sources
7801 that are not specified explicitly on other lines (order of the lines is not
7802 significant). It is an error to have two lines with the same file name or two
7803 lines starting with the character '*'.
7804
7805 @noindent
7806 After the file name or the character '*', another optional literal string
7807 indicating the file name of the definition file to be used for preprocessing
7808 (@pxref{Form of Definitions File}). The definition files are found by the
7809 compiler in one of the source directories. In some cases, when compiling
7810 a source in a directory other than the current directory, if the definition
7811 file is in the current directory, it may be necessary to add the current
7812 directory as a source directory through switch ^-I.^/SEARCH=[]^, otherwise
7813 the compiler would not find the definition file.
7814
7815 @noindent
7816 Then, optionally, ^switches^switches^ similar to those of @code{gnatprep} may
7817 be found. Those ^switches^switches^ are:
7818
7819 @table @code
7820
7821 @item -b
7822 Causes both preprocessor lines and the lines deleted by
7823 preprocessing to be replaced by blank lines, preserving the line number.
7824 This ^switch^switch^ is always implied; however, if specified after @option{-c}
7825 it cancels the effect of @option{-c}.
7826
7827 @item -c
7828 Causes both preprocessor lines and the lines deleted
7829 by preprocessing to be retained as comments marked
7830 with the special string ``@code{--! }''.
7831
7832 @item -Dsymbol=value
7833 Define or redefine a symbol, associated with value. A symbol is an Ada
7834 identifier, or an Ada reserved word, with the exception of @code{if},
7835 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7836 @code{value} is either a literal string, an Ada identifier or any Ada reserved
7837 word. A symbol declared with this ^switch^switch^ replaces a symbol with the
7838 same name defined in a definition file.
7839
7840 @item -s
7841 Causes a sorted list of symbol names and values to be
7842 listed on the standard output file.
7843
7844 @item -u
7845 Causes undefined symbols to be treated as having the value @code{FALSE}
7846 in the context
7847 of a preprocessor test. In the absence of this option, an undefined symbol in
7848 a @code{#if} or @code{#elsif} test will be treated as an error.
7849
7850 @end table
7851
7852 @noindent
7853 Examples of valid lines in a preprocessor data file:
7854
7855 @smallexample
7856 "toto.adb" "prep.def" -u
7857 -- preprocess "toto.adb", using definition file "prep.def",
7858 -- undefined symbol are False.
7859
7860 * -c -DVERSION=V101
7861 -- preprocess all other sources without a definition file;
7862 -- suppressed lined are commented; symbol VERSION has the value V101.
7863
7864 "titi.adb" "prep2.def" -s
7865 -- preprocess "titi.adb", using definition file "prep2.def";
7866 -- list all symbols with their values.
7867 @end smallexample
7868
7869 @item ^-gnateD^/DATA_PREPROCESSING=^symbol@r{[}=value@r{]}
7870 @cindex @option{-gnateD} (@command{gcc})
7871 Define or redefine a preprocessing symbol, associated with value. If no value
7872 is given on the command line, then the value of the symbol is @code{True}.
7873 A symbol is an identifier, following normal Ada (case-insensitive)
7874 rules for its syntax, and value is either an arbitrary string between double
7875 quotes or any sequence (including an empty sequence) of characters from the
7876 set (letters, digits, period, underline).
7877 Ada reserved words may be used as symbols, with the exceptions of @code{if},
7878 @code{else}, @code{elsif}, @code{end}, @code{and}, @code{or} and @code{then}.
7879
7880 @ifclear vms
7881 @noindent
7882 Examples:
7883
7884 @smallexample
7885 -gnateDToto=Titi
7886 -gnateDFoo
7887 -gnateDFoo=\"Foo-Bar\"
7888 @end smallexample
7889 @end ifclear
7890
7891 @noindent
7892 A symbol declared with this ^switch^switch^ on the command line replaces a
7893 symbol with the same name either in a definition file or specified with a
7894 ^switch^switch^ -D in the preprocessor data file.
7895
7896 @noindent
7897 This switch is similar to switch @option{^-D^/ASSOCIATE^} of @code{gnatprep}.
7898
7899 @item -gnateG
7900 When integrated preprocessing is performed and the preprocessor modifies
7901 the source text, write the result of this preprocessing into a file
7902 <source>^.prep^_prep^.
7903
7904 @end table
7905
7906 @node Code Generation Control
7907 @subsection Code Generation Control
7908
7909 @noindent
7910
7911 The GCC technology provides a wide range of target dependent
7912 @option{-m} switches for controlling
7913 details of code generation with respect to different versions of
7914 architectures. This includes variations in instruction sets (e.g.@:
7915 different members of the power pc family), and different requirements
7916 for optimal arrangement of instructions (e.g.@: different members of
7917 the x86 family). The list of available @option{-m} switches may be
7918 found in the GCC documentation.
7919
7920 Use of these @option{-m} switches may in some cases result in improved
7921 code performance.
7922
7923 The @value{EDITION} technology is tested and qualified without any
7924 @option{-m} switches,
7925 so generally the most reliable approach is to avoid the use of these
7926 switches. However, we generally expect most of these switches to work
7927 successfully with @value{EDITION}, and many customers have reported successful
7928 use of these options.
7929
7930 Our general advice is to avoid the use of @option{-m} switches unless
7931 special needs lead to requirements in this area. In particular,
7932 there is no point in using @option{-m} switches to improve performance
7933 unless you actually see a performance improvement.
7934
7935 @ifset vms
7936 @node Return Codes
7937 @subsection Return Codes
7938 @cindex Return Codes
7939 @cindex @option{/RETURN_CODES=VMS}
7940
7941 @noindent
7942 On VMS, GNAT compiled programs return POSIX-style codes by default,
7943 e.g.@: @option{/RETURN_CODES=POSIX}.
7944
7945 To enable VMS style return codes, use GNAT BIND and LINK with the option
7946 @option{/RETURN_CODES=VMS}. For example:
7947
7948 @smallexample
7949 GNAT BIND MYMAIN.ALI /RETURN_CODES=VMS
7950 GNAT LINK MYMAIN.ALI /RETURN_CODES=VMS
7951 @end smallexample
7952
7953 @noindent
7954 Programs built with /RETURN_CODES=VMS are suitable to be called in
7955 VMS DCL scripts. Programs compiled with the default /RETURN_CODES=POSIX
7956 are suitable for spawning with appropriate GNAT RTL routines.
7957
7958 @end ifset
7959
7960 @node Search Paths and the Run-Time Library (RTL)
7961 @section Search Paths and the Run-Time Library (RTL)
7962
7963 @noindent
7964 With the GNAT source-based library system, the compiler must be able to
7965 find source files for units that are needed by the unit being compiled.
7966 Search paths are used to guide this process.
7967
7968 The compiler compiles one source file whose name must be given
7969 explicitly on the command line. In other words, no searching is done
7970 for this file. To find all other source files that are needed (the most
7971 common being the specs of units), the compiler examines the following
7972 directories, in the following order:
7973
7974 @enumerate
7975 @item
7976 The directory containing the source file of the main unit being compiled
7977 (the file name on the command line).
7978
7979 @item
7980 Each directory named by an @option{^-I^/SOURCE_SEARCH^} switch given on the
7981 @command{gcc} command line, in the order given.
7982
7983 @item
7984 @findex ADA_PRJ_INCLUDE_FILE
7985 Each of the directories listed in the text file whose name is given
7986 by the @env{ADA_PRJ_INCLUDE_FILE} ^environment variable^logical name^.
7987
7988 @noindent
7989 @env{ADA_PRJ_INCLUDE_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
7990 driver when project files are used. It should not normally be set
7991 by other means.
7992
7993 @item
7994 @findex ADA_INCLUDE_PATH
7995 Each of the directories listed in the value of the
7996 @env{ADA_INCLUDE_PATH} ^environment variable^logical name^.
7997 @ifclear vms
7998 Construct this value
7999 exactly as the @env{PATH} environment variable: a list of directory
8000 names separated by colons (semicolons when working with the NT version).
8001 @end ifclear
8002 @ifset vms
8003 Normally, define this value as a logical name containing a comma separated
8004 list of directory names.
8005
8006 This variable can also be defined by means of an environment string
8007 (an argument to the HP C exec* set of functions).
8008
8009 Logical Name:
8010 @smallexample
8011 DEFINE ANOTHER_PATH FOO:[BAG]
8012 DEFINE ADA_INCLUDE_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
8013 @end smallexample
8014
8015 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
8016 first, followed by the standard Ada
8017 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADAINCLUDE].
8018 If this is not redefined, the user will obtain the HP Ada 83 IO packages
8019 (Text_IO, Sequential_IO, etc)
8020 instead of the standard Ada packages. Thus, in order to get the standard Ada
8021 packages by default, ADA_INCLUDE_PATH must be redefined.
8022 @end ifset
8023
8024 @item
8025 The content of the @file{ada_source_path} file which is part of the GNAT
8026 installation tree and is used to store standard libraries such as the
8027 GNAT Run Time Library (RTL) source files.
8028 @ifclear vms
8029 @ref{Installing a library}
8030 @end ifclear
8031 @end enumerate
8032
8033 @noindent
8034 Specifying the switch @option{^-I-^/NOCURRENT_DIRECTORY^}
8035 inhibits the use of the directory
8036 containing the source file named in the command line. You can still
8037 have this directory on your search path, but in this case it must be
8038 explicitly requested with a @option{^-I^/SOURCE_SEARCH^} switch.
8039
8040 Specifying the switch @option{-nostdinc}
8041 inhibits the search of the default location for the GNAT Run Time
8042 Library (RTL) source files.
8043
8044 The compiler outputs its object files and ALI files in the current
8045 working directory.
8046 @ifclear vms
8047 Caution: The object file can be redirected with the @option{-o} switch;
8048 however, @command{gcc} and @code{gnat1} have not been coordinated on this
8049 so the @file{ALI} file will not go to the right place. Therefore, you should
8050 avoid using the @option{-o} switch.
8051 @end ifclear
8052
8053 @findex System.IO
8054 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
8055 children make up the GNAT RTL, together with the simple @code{System.IO}
8056 package used in the @code{"Hello World"} example. The sources for these units
8057 are needed by the compiler and are kept together in one directory. Not
8058 all of the bodies are needed, but all of the sources are kept together
8059 anyway. In a normal installation, you need not specify these directory
8060 names when compiling or binding. Either the environment variables or
8061 the built-in defaults cause these files to be found.
8062
8063 In addition to the language-defined hierarchies (@code{System}, @code{Ada} and
8064 @code{Interfaces}), the GNAT distribution provides a fourth hierarchy,
8065 consisting of child units of @code{GNAT}. This is a collection of generally
8066 useful types, subprograms, etc. @xref{Top, GNAT Reference Manual, About
8067 This Guid, gnat_rm, GNAT Reference Manual}, for further details.
8068
8069 Besides simplifying access to the RTL, a major use of search paths is
8070 in compiling sources from multiple directories. This can make
8071 development environments much more flexible.
8072
8073 @node Order of Compilation Issues
8074 @section Order of Compilation Issues
8075
8076 @noindent
8077 If, in our earlier example, there was a spec for the @code{hello}
8078 procedure, it would be contained in the file @file{hello.ads}; yet this
8079 file would not have to be explicitly compiled. This is the result of the
8080 model we chose to implement library management. Some of the consequences
8081 of this model are as follows:
8082
8083 @itemize @bullet
8084 @item
8085 There is no point in compiling specs (except for package
8086 specs with no bodies) because these are compiled as needed by clients. If
8087 you attempt a useless compilation, you will receive an error message.
8088 It is also useless to compile subunits because they are compiled as needed
8089 by the parent.
8090
8091 @item
8092 There are no order of compilation requirements: performing a
8093 compilation never obsoletes anything. The only way you can obsolete
8094 something and require recompilations is to modify one of the
8095 source files on which it depends.
8096
8097 @item
8098 There is no library as such, apart from the ALI files
8099 (@pxref{The Ada Library Information Files}, for information on the format
8100 of these files). For now we find it convenient to create separate ALI files,
8101 but eventually the information therein may be incorporated into the object
8102 file directly.
8103
8104 @item
8105 When you compile a unit, the source files for the specs of all units
8106 that it @code{with}'s, all its subunits, and the bodies of any generics it
8107 instantiates must be available (reachable by the search-paths mechanism
8108 described above), or you will receive a fatal error message.
8109 @end itemize
8110
8111 @node Examples
8112 @section Examples
8113
8114 @noindent
8115 The following are some typical Ada compilation command line examples:
8116
8117 @table @code
8118 @item $ gcc -c xyz.adb
8119 Compile body in file @file{xyz.adb} with all default options.
8120
8121 @ifclear vms
8122 @item $ gcc -c -O2 -gnata xyz-def.adb
8123 @end ifclear
8124 @ifset vms
8125 @item $ GNAT COMPILE /OPTIMIZE=ALL -gnata xyz-def.adb
8126 @end ifset
8127
8128 Compile the child unit package in file @file{xyz-def.adb} with extensive
8129 optimizations, and pragma @code{Assert}/@code{Debug} statements
8130 enabled.
8131
8132 @item $ gcc -c -gnatc abc-def.adb
8133 Compile the subunit in file @file{abc-def.adb} in semantic-checking-only
8134 mode.
8135 @end table
8136
8137 @node Binding with gnatbind
8138 @chapter Binding with @code{gnatbind}
8139 @findex gnatbind
8140
8141 @menu
8142 * Running gnatbind::
8143 * Switches for gnatbind::
8144 * Command-Line Access::
8145 * Search Paths for gnatbind::
8146 * Examples of gnatbind Usage::
8147 @end menu
8148
8149 @noindent
8150 This chapter describes the GNAT binder, @code{gnatbind}, which is used
8151 to bind compiled GNAT objects.
8152
8153 Note: to invoke @code{gnatbind} with a project file, use the @code{gnat}
8154 driver (see @ref{The GNAT Driver and Project Files}).
8155
8156 The @code{gnatbind} program performs four separate functions:
8157
8158 @enumerate
8159 @item
8160 Checks that a program is consistent, in accordance with the rules in
8161 Chapter 10 of the Ada Reference Manual. In particular, error
8162 messages are generated if a program uses inconsistent versions of a
8163 given unit.
8164
8165 @item
8166 Checks that an acceptable order of elaboration exists for the program
8167 and issues an error message if it cannot find an order of elaboration
8168 that satisfies the rules in Chapter 10 of the Ada Language Manual.
8169
8170 @item
8171 Generates a main program incorporating the given elaboration order.
8172 This program is a small Ada package (body and spec) that
8173 must be subsequently compiled
8174 using the GNAT compiler. The necessary compilation step is usually
8175 performed automatically by @command{gnatlink}. The two most important
8176 functions of this program
8177 are to call the elaboration routines of units in an appropriate order
8178 and to call the main program.
8179
8180 @item
8181 Determines the set of object files required by the given main program.
8182 This information is output in the forms of comments in the generated program,
8183 to be read by the @command{gnatlink} utility used to link the Ada application.
8184 @end enumerate
8185
8186 @node Running gnatbind
8187 @section Running @code{gnatbind}
8188
8189 @noindent
8190 The form of the @code{gnatbind} command is
8191
8192 @smallexample
8193 @c $ gnatbind @ovar{switches} @var{mainprog}@r{[}.ali@r{]} @ovar{switches}
8194 @c Expanding @ovar macro inline (explanation in macro def comments)
8195 $ gnatbind @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]} @r{[}@var{switches}@r{]}
8196 @end smallexample
8197
8198 @noindent
8199 where @file{@var{mainprog}.adb} is the Ada file containing the main program
8200 unit body. @code{gnatbind} constructs an Ada
8201 package in two files whose names are
8202 @file{b~@var{mainprog}.ads}, and @file{b~@var{mainprog}.adb}.
8203 For example, if given the
8204 parameter @file{hello.ali}, for a main program contained in file
8205 @file{hello.adb}, the binder output files would be @file{b~hello.ads}
8206 and @file{b~hello.adb}.
8207
8208 When doing consistency checking, the binder takes into consideration
8209 any source files it can locate. For example, if the binder determines
8210 that the given main program requires the package @code{Pack}, whose
8211 @file{.ALI}
8212 file is @file{pack.ali} and whose corresponding source spec file is
8213 @file{pack.ads}, it attempts to locate the source file @file{pack.ads}
8214 (using the same search path conventions as previously described for the
8215 @command{gcc} command). If it can locate this source file, it checks that
8216 the time stamps
8217 or source checksums of the source and its references to in @file{ALI} files
8218 match. In other words, any @file{ALI} files that mentions this spec must have
8219 resulted from compiling this version of the source file (or in the case
8220 where the source checksums match, a version close enough that the
8221 difference does not matter).
8222
8223 @cindex Source files, use by binder
8224 The effect of this consistency checking, which includes source files, is
8225 that the binder ensures that the program is consistent with the latest
8226 version of the source files that can be located at bind time. Editing a
8227 source file without compiling files that depend on the source file cause
8228 error messages to be generated by the binder.
8229
8230 For example, suppose you have a main program @file{hello.adb} and a
8231 package @code{P}, from file @file{p.ads} and you perform the following
8232 steps:
8233
8234 @enumerate
8235 @item
8236 Enter @code{gcc -c hello.adb} to compile the main program.
8237
8238 @item
8239 Enter @code{gcc -c p.ads} to compile package @code{P}.
8240
8241 @item
8242 Edit file @file{p.ads}.
8243
8244 @item
8245 Enter @code{gnatbind hello}.
8246 @end enumerate
8247
8248 @noindent
8249 At this point, the file @file{p.ali} contains an out-of-date time stamp
8250 because the file @file{p.ads} has been edited. The attempt at binding
8251 fails, and the binder generates the following error messages:
8252
8253 @smallexample
8254 error: "hello.adb" must be recompiled ("p.ads" has been modified)
8255 error: "p.ads" has been modified and must be recompiled
8256 @end smallexample
8257
8258 @noindent
8259 Now both files must be recompiled as indicated, and then the bind can
8260 succeed, generating a main program. You need not normally be concerned
8261 with the contents of this file, but for reference purposes a sample
8262 binder output file is given in @ref{Example of Binder Output File}.
8263
8264 In most normal usage, the default mode of @command{gnatbind} which is to
8265 generate the main package in Ada, as described in the previous section.
8266 In particular, this means that any Ada programmer can read and understand
8267 the generated main program. It can also be debugged just like any other
8268 Ada code provided the @option{^-g^/DEBUG^} switch is used for
8269 @command{gnatbind} and @command{gnatlink}.
8270
8271 @node Switches for gnatbind
8272 @section Switches for @command{gnatbind}
8273
8274 @noindent
8275 The following switches are available with @code{gnatbind}; details will
8276 be presented in subsequent sections.
8277
8278 @menu
8279 * Consistency-Checking Modes::
8280 * Binder Error Message Control::
8281 * Elaboration Control::
8282 * Output Control::
8283 * Dynamic Allocation Control::
8284 * Binding with Non-Ada Main Programs::
8285 * Binding Programs with No Main Subprogram::
8286 @end menu
8287
8288 @table @option
8289 @c !sort!
8290
8291 @item --version
8292 @cindex @option{--version} @command{gnatbind}
8293 Display Copyright and version, then exit disregarding all other options.
8294
8295 @item --help
8296 @cindex @option{--help} @command{gnatbind}
8297 If @option{--version} was not used, display usage, then exit disregarding
8298 all other options.
8299
8300 @item -a
8301 @cindex @option{-a} @command{gnatbind}
8302 Indicates that, if supported by the platform, the adainit procedure should
8303 be treated as an initialisation routine by the linker (a constructor). This
8304 is intended to be used by the Project Manager to automatically initialize
8305 shared Stand-Alone Libraries.
8306
8307 @item ^-aO^/OBJECT_SEARCH^
8308 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatbind})
8309 Specify directory to be searched for ALI files.
8310
8311 @item ^-aI^/SOURCE_SEARCH^
8312 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
8313 Specify directory to be searched for source file.
8314
8315 @item ^-A^/ALI_LIST^@r{[=}@var{filename}@r{]}
8316 @cindex @option{^-A^/ALI_LIST^} (@command{gnatbind})
8317 Output ALI list (to standard output or to the named file).
8318
8319 @item ^-b^/REPORT_ERRORS=BRIEF^
8320 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@command{gnatbind})
8321 Generate brief messages to @file{stderr} even if verbose mode set.
8322
8323 @item ^-c^/NOOUTPUT^
8324 @cindex @option{^-c^/NOOUTPUT^} (@command{gnatbind})
8325 Check only, no generation of binder output file.
8326
8327 @item ^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8328 @cindex @option{^-d^/DEFAULT_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}} (@command{gnatbind})
8329 This switch can be used to change the default task stack size value
8330 to a specified size @var{nn}, which is expressed in bytes by default, or
8331 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8332 with @var{m}.
8333 In the absence of a @samp{@r{[}k@r{|}m@r{]}} suffix, this switch is equivalent,
8334 in effect, to completing all task specs with
8335 @smallexample @c ada
8336 pragma Storage_Size (nn);
8337 @end smallexample
8338 When they do not already have such a pragma.
8339
8340 @item ^-D^/DEFAULT_SECONDARY_STACK_SIZE=^@var{nn}@r{[}k@r{|}m@r{]}
8341 @cindex @option{^-D^/DEFAULT_SECONDARY_STACK_SIZE=nnnnn^} (@command{gnatbind})
8342 This switch can be used to change the default secondary stack size value
8343 to a specified size @var{nn}, which is expressed in bytes by default, or
8344 in kilobytes when suffixed with @var{k} or in megabytes when suffixed
8345 with @var{m}.
8346
8347 The secondary stack is used to deal with functions that return a variable
8348 sized result, for example a function returning an unconstrained
8349 String. There are two ways in which this secondary stack is allocated.
8350
8351 For most targets, the secondary stack is growing on demand and is allocated
8352 as a chain of blocks in the heap. The -D option is not very
8353 relevant. It only give some control over the size of the allocated
8354 blocks (whose size is the minimum of the default secondary stack size value,
8355 and the actual size needed for the current allocation request).
8356
8357 For certain targets, notably VxWorks 653,
8358 the secondary stack is allocated by carving off a fixed ratio chunk of the
8359 primary task stack. The -D option is used to define the
8360 size of the environment task's secondary stack.
8361
8362 @item ^-e^/ELABORATION_DEPENDENCIES^
8363 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@command{gnatbind})
8364 Output complete list of elaboration-order dependencies.
8365
8366 @item ^-E^/STORE_TRACEBACKS^
8367 @cindex @option{^-E^/STORE_TRACEBACKS^} (@command{gnatbind})
8368 Store tracebacks in exception occurrences when the target supports it.
8369 @ignore
8370 @c The following may get moved to an appendix
8371 This option is currently supported on the following targets:
8372 all x86 ports, Solaris, Windows, HP-UX, AIX, PowerPC VxWorks and Alpha VxWorks.
8373 @end ignore
8374 See also the packages @code{GNAT.Traceback} and
8375 @code{GNAT.Traceback.Symbolic} for more information.
8376 @ifclear vms
8377 Note that on x86 ports, you must not use @option{-fomit-frame-pointer}
8378 @command{gcc} option.
8379 @end ifclear
8380
8381 @item ^-F^/FORCE_ELABS_FLAGS^
8382 @cindex @option{^-F^/FORCE_ELABS_FLAGS^} (@command{gnatbind})
8383 Force the checks of elaboration flags. @command{gnatbind} does not normally
8384 generate checks of elaboration flags for the main executable, except when
8385 a Stand-Alone Library is used. However, there are cases when this cannot be
8386 detected by gnatbind. An example is importing an interface of a Stand-Alone
8387 Library through a pragma Import and only specifying through a linker switch
8388 this Stand-Alone Library. This switch is used to guarantee that elaboration
8389 flag checks are generated.
8390
8391 @item ^-h^/HELP^
8392 @cindex @option{^-h^/HELP^} (@command{gnatbind})
8393 Output usage (help) information
8394
8395 @item ^-H32^/32_MALLOC^
8396 @cindex @option{^-H32^/32_MALLOC^} (@command{gnatbind})
8397 Use 32-bit allocations for @code{__gnat_malloc} (and thus for access types).
8398 For further details see @ref{Dynamic Allocation Control}.
8399
8400 @item ^-H64^/64_MALLOC^
8401 @cindex @option{^-H64^/64_MALLOC^} (@command{gnatbind})
8402 Use 64-bit allocations for @code{__gnat_malloc} (and thus for access types).
8403 @cindex @code{__gnat_malloc}
8404 For further details see @ref{Dynamic Allocation Control}.
8405
8406 @item ^-I^/SEARCH^
8407 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
8408 Specify directory to be searched for source and ALI files.
8409
8410 @item ^-I-^/NOCURRENT_DIRECTORY^
8411 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatbind})
8412 Do not look for sources in the current directory where @code{gnatbind} was
8413 invoked, and do not look for ALI files in the directory containing the
8414 ALI file named in the @code{gnatbind} command line.
8415
8416 @item ^-l^/ORDER_OF_ELABORATION^
8417 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@command{gnatbind})
8418 Output chosen elaboration order.
8419
8420 @item ^-L@var{xxx}^/BUILD_LIBRARY=@var{xxx}^
8421 @cindex @option{^-L^/BUILD_LIBRARY^} (@command{gnatbind})
8422 Bind the units for library building. In this case the adainit and
8423 adafinal procedures (@pxref{Binding with Non-Ada Main Programs})
8424 are renamed to ^@var{xxx}init^@var{XXX}INIT^ and
8425 ^@var{xxx}final^@var{XXX}FINAL^.
8426 Implies ^-n^/NOCOMPILE^.
8427 @ifclear vms
8428 (@xref{GNAT and Libraries}, for more details.)
8429 @end ifclear
8430 @ifset vms
8431 On OpenVMS, these init and final procedures are exported in uppercase
8432 letters. For example if /BUILD_LIBRARY=toto is used, the exported name of
8433 the init procedure will be "TOTOINIT" and the exported name of the final
8434 procedure will be "TOTOFINAL".
8435 @end ifset
8436
8437 @item ^-Mxyz^/RENAME_MAIN=xyz^
8438 @cindex @option{^-M^/RENAME_MAIN^} (@command{gnatbind})
8439 Rename generated main program from main to xyz. This option is
8440 supported on cross environments only.
8441
8442 @item ^-m^/ERROR_LIMIT=^@var{n}
8443 @cindex @option{^-m^/ERROR_LIMIT^} (@command{gnatbind})
8444 Limit number of detected errors or warnings to @var{n}, where @var{n} is
8445 in the range 1..999999. The default value if no switch is
8446 given is 9999. If the number of warnings reaches this limit, then a
8447 message is output and further warnings are suppressed, the bind
8448 continues in this case. If the number of errors reaches this
8449 limit, then a message is output and the bind is abandoned.
8450 A value of zero means that no limit is enforced. The equal
8451 sign is optional.
8452
8453 @item ^-n^/NOMAIN^
8454 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8455 No main program.
8456
8457 @item -nostdinc
8458 @cindex @option{-nostdinc} (@command{gnatbind})
8459 Do not look for sources in the system default directory.
8460
8461 @item -nostdlib
8462 @cindex @option{-nostdlib} (@command{gnatbind})
8463 Do not look for library files in the system default directory.
8464
8465 @item --RTS=@var{rts-path}
8466 @cindex @option{--RTS} (@code{gnatbind})
8467 Specifies the default location of the runtime library. Same meaning as the
8468 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
8469
8470 @item ^-o ^/OUTPUT=^@var{file}
8471 @cindex @option{^-o ^/OUTPUT^} (@command{gnatbind})
8472 Name the output file @var{file} (default is @file{b~@var{xxx}.adb}).
8473 Note that if this option is used, then linking must be done manually,
8474 gnatlink cannot be used.
8475
8476 @item ^-O^/OBJECT_LIST^@r{[=}@var{filename}@r{]}
8477 @cindex @option{^-O^/OBJECT_LIST^} (@command{gnatbind})
8478 Output object list (to standard output or to the named file).
8479
8480 @item ^-p^/PESSIMISTIC_ELABORATION^
8481 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@command{gnatbind})
8482 Pessimistic (worst-case) elaboration order
8483
8484 @item ^-P^-P^
8485 @cindex @option{^-P^/CODEPEER^} (@command{gnatbind})
8486 Generate binder file suitable for CodePeer.
8487
8488 @item ^-R^-R^
8489 @cindex @option{^-R^-R^} (@command{gnatbind})
8490 Output closure source list, which includes all non-time-units that are
8491 included in the bind.
8492
8493 @item ^-Ra^-Ra^
8494 @cindex @option{^-Ra^-Ra^} (@command{gnatbind})
8495 Like @option{-R} but the list includes run-time units.
8496
8497 @item ^-s^/READ_SOURCES=ALL^
8498 @cindex @option{^-s^/READ_SOURCES=ALL^} (@command{gnatbind})
8499 Require all source files to be present.
8500
8501 @item ^-S@var{xxx}^/INITIALIZE_SCALARS=@var{xxx}^
8502 @cindex @option{^-S^/INITIALIZE_SCALARS^} (@command{gnatbind})
8503 Specifies the value to be used when detecting uninitialized scalar
8504 objects with pragma Initialize_Scalars.
8505 The @var{xxx} ^string specified with the switch^option^ may be either
8506 @itemize @bullet
8507 @item ``@option{^in^INVALID^}'' requesting an invalid value where possible
8508 @item ``@option{^lo^LOW^}'' for the lowest possible value
8509 @item ``@option{^hi^HIGH^}'' for the highest possible value
8510 @item ``@option{@var{xx}}'' for a value consisting of repeated bytes with the
8511 value @code{16#@var{xx}#} (i.e., @var{xx} is a string of two hexadecimal digits).
8512 @end itemize
8513
8514 In addition, you can specify @option{-Sev} to indicate that the value is
8515 to be set at run time. In this case, the program will look for an environment
8516 @cindex GNAT_INIT_SCALARS
8517 variable of the form @env{GNAT_INIT_SCALARS=@var{xx}}, where @var{xx} is one
8518 of @option{in/lo/hi/@var{xx}} with the same meanings as above.
8519 If no environment variable is found, or if it does not have a valid value,
8520 then the default is @option{in} (invalid values).
8521
8522 @ifclear vms
8523 @item -static
8524 @cindex @option{-static} (@code{gnatbind})
8525 Link against a static GNAT run time.
8526
8527 @item -shared
8528 @cindex @option{-shared} (@code{gnatbind})
8529 Link against a shared GNAT run time when available.
8530 @end ifclear
8531
8532 @item ^-t^/NOTIME_STAMP_CHECK^
8533 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8534 Tolerate time stamp and other consistency errors
8535
8536 @item ^-T@var{n}^/TIME_SLICE=@var{n}^
8537 @cindex @option{^-T^/TIME_SLICE^} (@code{gnatbind})
8538 Set the time slice value to @var{n} milliseconds. If the system supports
8539 the specification of a specific time slice value, then the indicated value
8540 is used. If the system does not support specific time slice values, but
8541 does support some general notion of round-robin scheduling, then any
8542 nonzero value will activate round-robin scheduling.
8543
8544 A value of zero is treated specially. It turns off time
8545 slicing, and in addition, indicates to the tasking run time that the
8546 semantics should match as closely as possible the Annex D
8547 requirements of the Ada RM, and in particular sets the default
8548 scheduling policy to @code{FIFO_Within_Priorities}.
8549
8550 @item ^-u@var{n}^/DYNAMIC_STACK_USAGE=@var{n}^
8551 @cindex @option{^-u^/DYNAMIC_STACK_USAGE^} (@code{gnatbind})
8552 Enable dynamic stack usage, with @var{n} results stored and displayed
8553 at program termination. A result is generated when a task
8554 terminates. Results that can't be stored are displayed on the fly, at
8555 task termination. This option is currently not supported on Itanium
8556 platforms. (See @ref{Dynamic Stack Usage Analysis} for details.)
8557
8558 @item ^-v^/REPORT_ERRORS=VERBOSE^
8559 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8560 Verbose mode. Write error messages, header, summary output to
8561 @file{stdout}.
8562
8563 @ifclear vms
8564 @item -w@var{x}
8565 @cindex @option{-w} (@code{gnatbind})
8566 Warning mode (@var{x}=s/e for suppress/treat as error)
8567 @end ifclear
8568
8569 @ifset vms
8570 @item /WARNINGS=NORMAL
8571 @cindex @option{/WARNINGS} (@code{gnatbind})
8572 Normal warnings mode. Warnings are issued but ignored
8573
8574 @item /WARNINGS=SUPPRESS
8575 @cindex @option{/WARNINGS} (@code{gnatbind})
8576 All warning messages are suppressed
8577
8578 @item /WARNINGS=ERROR
8579 @cindex @option{/WARNINGS} (@code{gnatbind})
8580 Warning messages are treated as fatal errors
8581 @end ifset
8582
8583 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8584 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8585 Override default wide character encoding for standard Text_IO files.
8586
8587 @item ^-x^/READ_SOURCES=NONE^
8588 @cindex @option{^-x^/READ_SOURCES^} (@code{gnatbind})
8589 Exclude source files (check object consistency only).
8590
8591 @ifset vms
8592 @item /READ_SOURCES=AVAILABLE
8593 @cindex @option{/READ_SOURCES} (@code{gnatbind})
8594 Default mode, in which sources are checked for consistency only if
8595 they are available.
8596 @end ifset
8597
8598 @item ^-X@var{nnn}^/RETURN_CODES=POSIX^
8599 @cindex @option{^-X@var{nnn}^/RETURN_CODES=POSIX^} (@code{gnatbind})
8600 Set default exit status value, normally 0 for POSIX compliance.
8601
8602 @ifset vms
8603 @item /RETURN_CODES=VMS
8604 @cindex @option{/RETURN_CODES=VMS} (@code{gnatbind})
8605 VMS default normal successful return value is 1.
8606 @end ifset
8607
8608 @item ^-y^/ENABLE_LEAP_SECONDS^
8609 @cindex @option{^-y^/ENABLE_LEAP_SECONDS^} (@code{gnatbind})
8610 Enable leap seconds support in @code{Ada.Calendar} and its children.
8611
8612 @item ^-z^/ZERO_MAIN^
8613 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8614 No main subprogram.
8615 @end table
8616
8617 @ifclear vms
8618 @noindent
8619 You may obtain this listing of switches by running @code{gnatbind} with
8620 no arguments.
8621 @end ifclear
8622
8623 @node Consistency-Checking Modes
8624 @subsection Consistency-Checking Modes
8625
8626 @noindent
8627 As described earlier, by default @code{gnatbind} checks
8628 that object files are consistent with one another and are consistent
8629 with any source files it can locate. The following switches control binder
8630 access to sources.
8631
8632 @table @option
8633 @c !sort!
8634 @item ^-s^/READ_SOURCES=ALL^
8635 @cindex @option{^-s^/READ_SOURCES=ALL^} (@code{gnatbind})
8636 Require source files to be present. In this mode, the binder must be
8637 able to locate all source files that are referenced, in order to check
8638 their consistency. In normal mode, if a source file cannot be located it
8639 is simply ignored. If you specify this switch, a missing source
8640 file is an error.
8641
8642 @item ^-Wx^/WIDE_CHARACTER_ENCODING=^@var{e}
8643 @cindex @option{^-Wx^/WIDE_CHARACTER_ENCODING^} (@code{gnatbind})
8644 Override default wide character encoding for standard Text_IO files.
8645 Normally the default wide character encoding method used for standard
8646 [Wide_[Wide_]]Text_IO files is taken from the encoding specified for
8647 the main source input (see description of switch
8648 @option{^-gnatWx^/WIDE_CHARACTER_ENCODING^} for the compiler). The
8649 use of this switch for the binder (which has the same set of
8650 possible arguments) overrides this default as specified.
8651
8652 @item ^-x^/READ_SOURCES=NONE^
8653 @cindex @option{^-x^/READ_SOURCES=NONE^} (@code{gnatbind})
8654 Exclude source files. In this mode, the binder only checks that ALI
8655 files are consistent with one another. Source files are not accessed.
8656 The binder runs faster in this mode, and there is still a guarantee that
8657 the resulting program is self-consistent.
8658 If a source file has been edited since it was last compiled, and you
8659 specify this switch, the binder will not detect that the object
8660 file is out of date with respect to the source file. Note that this is the
8661 mode that is automatically used by @command{gnatmake} because in this
8662 case the checking against sources has already been performed by
8663 @command{gnatmake} in the course of compilation (i.e.@: before binding).
8664
8665 @ifset vms
8666 @item /READ_SOURCES=AVAILABLE
8667 @cindex @code{/READ_SOURCES=AVAILABLE} (@code{gnatbind})
8668 This is the default mode in which source files are checked if they are
8669 available, and ignored if they are not available.
8670 @end ifset
8671 @end table
8672
8673 @node Binder Error Message Control
8674 @subsection Binder Error Message Control
8675
8676 @noindent
8677 The following switches provide control over the generation of error
8678 messages from the binder:
8679
8680 @table @option
8681 @c !sort!
8682 @item ^-v^/REPORT_ERRORS=VERBOSE^
8683 @cindex @option{^-v^/REPORT_ERRORS=VERBOSE^} (@code{gnatbind})
8684 Verbose mode. In the normal mode, brief error messages are generated to
8685 @file{stderr}. If this switch is present, a header is written
8686 to @file{stdout} and any error messages are directed to @file{stdout}.
8687 All that is written to @file{stderr} is a brief summary message.
8688
8689 @item ^-b^/REPORT_ERRORS=BRIEF^
8690 @cindex @option{^-b^/REPORT_ERRORS=BRIEF^} (@code{gnatbind})
8691 Generate brief error messages to @file{stderr} even if verbose mode is
8692 specified. This is relevant only when used with the
8693 @option{^-v^/REPORT_ERRORS=VERBOSE^} switch.
8694
8695 @ifclear vms
8696 @item -m@var{n}
8697 @cindex @option{-m} (@code{gnatbind})
8698 Limits the number of error messages to @var{n}, a decimal integer in the
8699 range 1-999. The binder terminates immediately if this limit is reached.
8700
8701 @item -M@var{xxx}
8702 @cindex @option{-M} (@code{gnatbind})
8703 Renames the generated main program from @code{main} to @code{xxx}.
8704 This is useful in the case of some cross-building environments, where
8705 the actual main program is separate from the one generated
8706 by @code{gnatbind}.
8707 @end ifclear
8708
8709 @item ^-ws^/WARNINGS=SUPPRESS^
8710 @cindex @option{^-ws^/WARNINGS=SUPPRESS^} (@code{gnatbind})
8711 @cindex Warnings
8712 Suppress all warning messages.
8713
8714 @item ^-we^/WARNINGS=ERROR^
8715 @cindex @option{^-we^/WARNINGS=ERROR^} (@code{gnatbind})
8716 Treat any warning messages as fatal errors.
8717
8718 @ifset vms
8719 @item /WARNINGS=NORMAL
8720 Standard mode with warnings generated, but warnings do not get treated
8721 as errors.
8722 @end ifset
8723
8724 @item ^-t^/NOTIME_STAMP_CHECK^
8725 @cindex @option{^-t^/NOTIME_STAMP_CHECK^} (@code{gnatbind})
8726 @cindex Time stamp checks, in binder
8727 @cindex Binder consistency checks
8728 @cindex Consistency checks, in binder
8729 The binder performs a number of consistency checks including:
8730
8731 @itemize @bullet
8732 @item
8733 Check that time stamps of a given source unit are consistent
8734 @item
8735 Check that checksums of a given source unit are consistent
8736 @item
8737 Check that consistent versions of @code{GNAT} were used for compilation
8738 @item
8739 Check consistency of configuration pragmas as required
8740 @end itemize
8741
8742 @noindent
8743 Normally failure of such checks, in accordance with the consistency
8744 requirements of the Ada Reference Manual, causes error messages to be
8745 generated which abort the binder and prevent the output of a binder
8746 file and subsequent link to obtain an executable.
8747
8748 The @option{^-t^/NOTIME_STAMP_CHECK^} switch converts these error messages
8749 into warnings, so that
8750 binding and linking can continue to completion even in the presence of such
8751 errors. The result may be a failed link (due to missing symbols), or a
8752 non-functional executable which has undefined semantics.
8753 @emph{This means that
8754 @option{^-t^/NOTIME_STAMP_CHECK^} should be used only in unusual situations,
8755 with extreme care.}
8756 @end table
8757
8758 @node Elaboration Control
8759 @subsection Elaboration Control
8760
8761 @noindent
8762 The following switches provide additional control over the elaboration
8763 order. For full details see @ref{Elaboration Order Handling in GNAT}.
8764
8765 @table @option
8766 @item ^-p^/PESSIMISTIC_ELABORATION^
8767 @cindex @option{^-p^/PESSIMISTIC_ELABORATION^} (@code{gnatbind})
8768 Normally the binder attempts to choose an elaboration order that is
8769 likely to minimize the likelihood of an elaboration order error resulting
8770 in raising a @code{Program_Error} exception. This switch reverses the
8771 action of the binder, and requests that it deliberately choose an order
8772 that is likely to maximize the likelihood of an elaboration error.
8773 This is useful in ensuring portability and avoiding dependence on
8774 accidental fortuitous elaboration ordering.
8775
8776 Normally it only makes sense to use the @option{^-p^/PESSIMISTIC_ELABORATION^}
8777 switch if dynamic
8778 elaboration checking is used (@option{-gnatE} switch used for compilation).
8779 This is because in the default static elaboration mode, all necessary
8780 @code{Elaborate} and @code{Elaborate_All} pragmas are implicitly inserted.
8781 These implicit pragmas are still respected by the binder in
8782 @option{^-p^/PESSIMISTIC_ELABORATION^} mode, so a
8783 safe elaboration order is assured.
8784
8785 Note that @option{^-p^/PESSIMISTIC_ELABORATION^} is not intended for
8786 production use; it is more for debugging/experimental use.
8787 @end table
8788
8789 @node Output Control
8790 @subsection Output Control
8791
8792 @noindent
8793 The following switches allow additional control over the output
8794 generated by the binder.
8795
8796 @table @option
8797 @c !sort!
8798
8799 @item ^-c^/NOOUTPUT^
8800 @cindex @option{^-c^/NOOUTPUT^} (@code{gnatbind})
8801 Check only. Do not generate the binder output file. In this mode the
8802 binder performs all error checks but does not generate an output file.
8803
8804 @item ^-e^/ELABORATION_DEPENDENCIES^
8805 @cindex @option{^-e^/ELABORATION_DEPENDENCIES^} (@code{gnatbind})
8806 Output complete list of elaboration-order dependencies, showing the
8807 reason for each dependency. This output can be rather extensive but may
8808 be useful in diagnosing problems with elaboration order. The output is
8809 written to @file{stdout}.
8810
8811 @item ^-h^/HELP^
8812 @cindex @option{^-h^/HELP^} (@code{gnatbind})
8813 Output usage information. The output is written to @file{stdout}.
8814
8815 @item ^-K^/LINKER_OPTION_LIST^
8816 @cindex @option{^-K^/LINKER_OPTION_LIST^} (@code{gnatbind})
8817 Output linker options to @file{stdout}. Includes library search paths,
8818 contents of pragmas Ident and Linker_Options, and libraries added
8819 by @code{gnatbind}.
8820
8821 @item ^-l^/ORDER_OF_ELABORATION^
8822 @cindex @option{^-l^/ORDER_OF_ELABORATION^} (@code{gnatbind})
8823 Output chosen elaboration order. The output is written to @file{stdout}.
8824
8825 @item ^-O^/OBJECT_LIST^
8826 @cindex @option{^-O^/OBJECT_LIST^} (@code{gnatbind})
8827 Output full names of all the object files that must be linked to provide
8828 the Ada component of the program. The output is written to @file{stdout}.
8829 This list includes the files explicitly supplied and referenced by the user
8830 as well as implicitly referenced run-time unit files. The latter are
8831 omitted if the corresponding units reside in shared libraries. The
8832 directory names for the run-time units depend on the system configuration.
8833
8834 @item ^-o ^/OUTPUT=^@var{file}
8835 @cindex @option{^-o^/OUTPUT^} (@code{gnatbind})
8836 Set name of output file to @var{file} instead of the normal
8837 @file{b~@var{mainprog}.adb} default. Note that @var{file} denote the Ada
8838 binder generated body filename.
8839 Note that if this option is used, then linking must be done manually.
8840 It is not possible to use gnatlink in this case, since it cannot locate
8841 the binder file.
8842
8843 @item ^-r^/RESTRICTION_LIST^
8844 @cindex @option{^-r^/RESTRICTION_LIST^} (@code{gnatbind})
8845 Generate list of @code{pragma Restrictions} that could be applied to
8846 the current unit. This is useful for code audit purposes, and also may
8847 be used to improve code generation in some cases.
8848
8849 @end table
8850
8851 @node Dynamic Allocation Control
8852 @subsection Dynamic Allocation Control
8853
8854 @noindent
8855 The heap control switches -- @option{-H32} and @option{-H64} --
8856 determine whether dynamic allocation uses 32-bit or 64-bit memory.
8857 They only affect compiler-generated allocations via @code{__gnat_malloc};
8858 explicit calls to @code{malloc} and related functions from the C
8859 run-time library are unaffected.
8860
8861 @table @option
8862 @item -H32
8863 Allocate memory on 32-bit heap
8864
8865 @item -H64
8866 Allocate memory on 64-bit heap. This is the default
8867 unless explicitly overridden by a @code{'Size} clause on the access type.
8868 @end table
8869
8870 @ifset vms
8871 @noindent
8872 See also @ref{Access types and 32/64-bit allocation}.
8873 @end ifset
8874 @ifclear vms
8875 @noindent
8876 These switches are only effective on VMS platforms.
8877 @end ifclear
8878
8879
8880 @node Binding with Non-Ada Main Programs
8881 @subsection Binding with Non-Ada Main Programs
8882
8883 @noindent
8884 In our description so far we have assumed that the main
8885 program is in Ada, and that the task of the binder is to generate a
8886 corresponding function @code{main} that invokes this Ada main
8887 program. GNAT also supports the building of executable programs where
8888 the main program is not in Ada, but some of the called routines are
8889 written in Ada and compiled using GNAT (@pxref{Mixed Language Programming}).
8890 The following switch is used in this situation:
8891
8892 @table @option
8893 @item ^-n^/NOMAIN^
8894 @cindex @option{^-n^/NOMAIN^} (@code{gnatbind})
8895 No main program. The main program is not in Ada.
8896 @end table
8897
8898 @noindent
8899 In this case, most of the functions of the binder are still required,
8900 but instead of generating a main program, the binder generates a file
8901 containing the following callable routines:
8902
8903 @table @code
8904 @item adainit
8905 @findex adainit
8906 You must call this routine to initialize the Ada part of the program by
8907 calling the necessary elaboration routines. A call to @code{adainit} is
8908 required before the first call to an Ada subprogram.
8909
8910 Note that it is assumed that the basic execution environment must be setup
8911 to be appropriate for Ada execution at the point where the first Ada
8912 subprogram is called. In particular, if the Ada code will do any
8913 floating-point operations, then the FPU must be setup in an appropriate
8914 manner. For the case of the x86, for example, full precision mode is
8915 required. The procedure GNAT.Float_Control.Reset may be used to ensure
8916 that the FPU is in the right state.
8917
8918 @item adafinal
8919 @findex adafinal
8920 You must call this routine to perform any library-level finalization
8921 required by the Ada subprograms. A call to @code{adafinal} is required
8922 after the last call to an Ada subprogram, and before the program
8923 terminates.
8924 @end table
8925
8926 @noindent
8927 If the @option{^-n^/NOMAIN^} switch
8928 @cindex @option{^-n^/NOMAIN^} (@command{gnatbind})
8929 @cindex Binder, multiple input files
8930 is given, more than one ALI file may appear on
8931 the command line for @code{gnatbind}. The normal @dfn{closure}
8932 calculation is performed for each of the specified units. Calculating
8933 the closure means finding out the set of units involved by tracing
8934 @code{with} references. The reason it is necessary to be able to
8935 specify more than one ALI file is that a given program may invoke two or
8936 more quite separate groups of Ada units.
8937
8938 The binder takes the name of its output file from the last specified ALI
8939 file, unless overridden by the use of the @option{^-o file^/OUTPUT=file^}.
8940 @cindex @option{^-o^/OUTPUT^} (@command{gnatbind})
8941 The output is an Ada unit in source form that can be compiled with GNAT.
8942 This compilation occurs automatically as part of the @command{gnatlink}
8943 processing.
8944
8945 Currently the GNAT run time requires a FPU using 80 bits mode
8946 precision. Under targets where this is not the default it is required to
8947 call GNAT.Float_Control.Reset before using floating point numbers (this
8948 include float computation, float input and output) in the Ada code. A
8949 side effect is that this could be the wrong mode for the foreign code
8950 where floating point computation could be broken after this call.
8951
8952 @node Binding Programs with No Main Subprogram
8953 @subsection Binding Programs with No Main Subprogram
8954
8955 @noindent
8956 It is possible to have an Ada program which does not have a main
8957 subprogram. This program will call the elaboration routines of all the
8958 packages, then the finalization routines.
8959
8960 The following switch is used to bind programs organized in this manner:
8961
8962 @table @option
8963 @item ^-z^/ZERO_MAIN^
8964 @cindex @option{^-z^/ZERO_MAIN^} (@code{gnatbind})
8965 Normally the binder checks that the unit name given on the command line
8966 corresponds to a suitable main subprogram. When this switch is used,
8967 a list of ALI files can be given, and the execution of the program
8968 consists of elaboration of these units in an appropriate order. Note
8969 that the default wide character encoding method for standard Text_IO
8970 files is always set to Brackets if this switch is set (you can use
8971 the binder switch
8972 @option{^-Wx^WIDE_CHARACTER_ENCODING^} to override this default).
8973 @end table
8974
8975 @node Command-Line Access
8976 @section Command-Line Access
8977
8978 @noindent
8979 The package @code{Ada.Command_Line} provides access to the command-line
8980 arguments and program name. In order for this interface to operate
8981 correctly, the two variables
8982
8983 @smallexample
8984 @group
8985 int gnat_argc;
8986 char **gnat_argv;
8987 @end group
8988 @end smallexample
8989
8990 @noindent
8991 @findex gnat_argv
8992 @findex gnat_argc
8993 are declared in one of the GNAT library routines. These variables must
8994 be set from the actual @code{argc} and @code{argv} values passed to the
8995 main program. With no @option{^n^/NOMAIN^} present, @code{gnatbind}
8996 generates the C main program to automatically set these variables.
8997 If the @option{^n^/NOMAIN^} switch is used, there is no automatic way to
8998 set these variables. If they are not set, the procedures in
8999 @code{Ada.Command_Line} will not be available, and any attempt to use
9000 them will raise @code{Constraint_Error}. If command line access is
9001 required, your main program must set @code{gnat_argc} and
9002 @code{gnat_argv} from the @code{argc} and @code{argv} values passed to
9003 it.
9004
9005 @node Search Paths for gnatbind
9006 @section Search Paths for @code{gnatbind}
9007
9008 @noindent
9009 The binder takes the name of an ALI file as its argument and needs to
9010 locate source files as well as other ALI files to verify object consistency.
9011
9012 For source files, it follows exactly the same search rules as @command{gcc}
9013 (@pxref{Search Paths and the Run-Time Library (RTL)}). For ALI files the
9014 directories searched are:
9015
9016 @enumerate
9017 @item
9018 The directory containing the ALI file named in the command line, unless
9019 the switch @option{^-I-^/NOCURRENT_DIRECTORY^} is specified.
9020
9021 @item
9022 All directories specified by @option{^-I^/SEARCH^}
9023 switches on the @code{gnatbind}
9024 command line, in the order given.
9025
9026 @item
9027 @findex ADA_PRJ_OBJECTS_FILE
9028 Each of the directories listed in the text file whose name is given
9029 by the @env{ADA_PRJ_OBJECTS_FILE} ^environment variable^logical name^.
9030
9031 @noindent
9032 @env{ADA_PRJ_OBJECTS_FILE} is normally set by gnatmake or by the ^gnat^GNAT^
9033 driver when project files are used. It should not normally be set
9034 by other means.
9035
9036 @item
9037 @findex ADA_OBJECTS_PATH
9038 Each of the directories listed in the value of the
9039 @env{ADA_OBJECTS_PATH} ^environment variable^logical name^.
9040 @ifset unw
9041 Construct this value
9042 exactly as the @env{PATH} environment variable: a list of directory
9043 names separated by colons (semicolons when working with the NT version
9044 of GNAT).
9045 @end ifset
9046 @ifset vms
9047 Normally, define this value as a logical name containing a comma separated
9048 list of directory names.
9049
9050 This variable can also be defined by means of an environment string
9051 (an argument to the HP C exec* set of functions).
9052
9053 Logical Name:
9054 @smallexample
9055 DEFINE ANOTHER_PATH FOO:[BAG]
9056 DEFINE ADA_OBJECTS_PATH ANOTHER_PATH,FOO:[BAM],FOO:[BAR]
9057 @end smallexample
9058
9059 By default, the path includes GNU:[LIB.OPENVMS7_x.2_8_x.DECLIB]
9060 first, followed by the standard Ada
9061 libraries in GNU:[LIB.OPENVMS7_x.2_8_x.ADALIB].
9062 If this is not redefined, the user will obtain the HP Ada 83 IO packages
9063 (Text_IO, Sequential_IO, etc)
9064 instead of the standard Ada packages. Thus, in order to get the standard Ada
9065 packages by default, ADA_OBJECTS_PATH must be redefined.
9066 @end ifset
9067
9068 @item
9069 The content of the @file{ada_object_path} file which is part of the GNAT
9070 installation tree and is used to store standard libraries such as the
9071 GNAT Run Time Library (RTL) unless the switch @option{-nostdlib} is
9072 specified.
9073 @ifclear vms
9074 @ref{Installing a library}
9075 @end ifclear
9076 @end enumerate
9077
9078 @noindent
9079 In the binder the switch @option{^-I^/SEARCH^}
9080 @cindex @option{^-I^/SEARCH^} (@command{gnatbind})
9081 is used to specify both source and
9082 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
9083 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatbind})
9084 instead if you want to specify
9085 source paths only, and @option{^-aO^/LIBRARY_SEARCH^}
9086 @cindex @option{^-aO^/LIBRARY_SEARCH^} (@command{gnatbind})
9087 if you want to specify library paths
9088 only. This means that for the binder
9089 @option{^-I^/SEARCH=^}@var{dir} is equivalent to
9090 @option{^-aI^/SOURCE_SEARCH=^}@var{dir}
9091 @option{^-aO^/OBJECT_SEARCH=^}@var{dir}.
9092 The binder generates the bind file (a C language source file) in the
9093 current working directory.
9094
9095 @findex Ada
9096 @findex System
9097 @findex Interfaces
9098 @findex GNAT
9099 The packages @code{Ada}, @code{System}, and @code{Interfaces} and their
9100 children make up the GNAT Run-Time Library, together with the package
9101 GNAT and its children, which contain a set of useful additional
9102 library functions provided by GNAT. The sources for these units are
9103 needed by the compiler and are kept together in one directory. The ALI
9104 files and object files generated by compiling the RTL are needed by the
9105 binder and the linker and are kept together in one directory, typically
9106 different from the directory containing the sources. In a normal
9107 installation, you need not specify these directory names when compiling
9108 or binding. Either the environment variables or the built-in defaults
9109 cause these files to be found.
9110
9111 Besides simplifying access to the RTL, a major use of search paths is
9112 in compiling sources from multiple directories. This can make
9113 development environments much more flexible.
9114
9115 @node Examples of gnatbind Usage
9116 @section Examples of @code{gnatbind} Usage
9117
9118 @noindent
9119 This section contains a number of examples of using the GNAT binding
9120 utility @code{gnatbind}.
9121
9122 @table @code
9123 @item gnatbind hello
9124 The main program @code{Hello} (source program in @file{hello.adb}) is
9125 bound using the standard switch settings. The generated main program is
9126 @file{b~hello.adb}. This is the normal, default use of the binder.
9127
9128 @ifclear vms
9129 @item gnatbind hello -o mainprog.adb
9130 @end ifclear
9131 @ifset vms
9132 @item gnatbind HELLO.ALI /OUTPUT=Mainprog.ADB
9133 @end ifset
9134 The main program @code{Hello} (source program in @file{hello.adb}) is
9135 bound using the standard switch settings. The generated main program is
9136 @file{mainprog.adb} with the associated spec in
9137 @file{mainprog.ads}. Note that you must specify the body here not the
9138 spec. Note that if this option is used, then linking must be done manually,
9139 since gnatlink will not be able to find the generated file.
9140 @end table
9141
9142 @c ------------------------------------
9143 @node Linking with gnatlink
9144 @chapter Linking with @command{gnatlink}
9145 @c ------------------------------------
9146 @findex gnatlink
9147
9148 @noindent
9149 This chapter discusses @command{gnatlink}, a tool that links
9150 an Ada program and builds an executable file. This utility
9151 invokes the system linker ^(via the @command{gcc} command)^^
9152 with a correct list of object files and library references.
9153 @command{gnatlink} automatically determines the list of files and
9154 references for the Ada part of a program. It uses the binder file
9155 generated by the @command{gnatbind} to determine this list.
9156
9157 Note: to invoke @code{gnatlink} with a project file, use the @code{gnat}
9158 driver (see @ref{The GNAT Driver and Project Files}).
9159
9160 @menu
9161 * Running gnatlink::
9162 * Switches for gnatlink::
9163 @end menu
9164
9165 @node Running gnatlink
9166 @section Running @command{gnatlink}
9167
9168 @noindent
9169 The form of the @command{gnatlink} command is
9170
9171 @smallexample
9172 @c $ gnatlink @ovar{switches} @var{mainprog}@r{[}.ali@r{]}
9173 @c @ovar{non-Ada objects} @ovar{linker options}
9174 @c Expanding @ovar macro inline (explanation in macro def comments)
9175 $ gnatlink @r{[}@var{switches}@r{]} @var{mainprog}@r{[}.ali@r{]}
9176 @r{[}@var{non-Ada objects}@r{]} @r{[}@var{linker options}@r{]}
9177
9178 @end smallexample
9179
9180 @noindent
9181 The arguments of @command{gnatlink} (switches, main @file{ALI} file,
9182 non-Ada objects
9183 or linker options) may be in any order, provided that no non-Ada object may
9184 be mistaken for a main @file{ALI} file.
9185 Any file name @file{F} without the @file{.ali}
9186 extension will be taken as the main @file{ALI} file if a file exists
9187 whose name is the concatenation of @file{F} and @file{.ali}.
9188
9189 @noindent
9190 @file{@var{mainprog}.ali} references the ALI file of the main program.
9191 The @file{.ali} extension of this file can be omitted. From this
9192 reference, @command{gnatlink} locates the corresponding binder file
9193 @file{b~@var{mainprog}.adb} and, using the information in this file along
9194 with the list of non-Ada objects and linker options, constructs a
9195 linker command file to create the executable.
9196
9197 The arguments other than the @command{gnatlink} switches and the main
9198 @file{ALI} file are passed to the linker uninterpreted.
9199 They typically include the names of
9200 object files for units written in other languages than Ada and any library
9201 references required to resolve references in any of these foreign language
9202 units, or in @code{Import} pragmas in any Ada units.
9203
9204 @var{linker options} is an optional list of linker specific
9205 switches.
9206 The default linker called by gnatlink is @command{gcc} which in
9207 turn calls the appropriate system linker.
9208
9209 One useful option for the linker is @option{-s}: it reduces the size of the
9210 executable by removing all symbol table and relocation information from the
9211 executable.
9212
9213 Standard options for the linker such as @option{-lmy_lib} or
9214 @option{-Ldir} can be added as is.
9215 For options that are not recognized by
9216 @command{gcc} as linker options, use the @command{gcc} switches
9217 @option{-Xlinker} or @option{-Wl,}.
9218
9219 Refer to the GCC documentation for
9220 details.
9221
9222 Here is an example showing how to generate a linker map:
9223
9224 @smallexample
9225 $ ^gnatlink my_prog -Wl,-Map,MAPFILE^GNAT LINK my_prog.ali /MAP^
9226 @end smallexample
9227
9228 Using @var{linker options} it is possible to set the program stack and
9229 heap size.
9230 @ifset unw
9231 See @ref{Setting Stack Size from gnatlink} and
9232 @ref{Setting Heap Size from gnatlink}.
9233 @end ifset
9234
9235 @command{gnatlink} determines the list of objects required by the Ada
9236 program and prepends them to the list of objects passed to the linker.
9237 @command{gnatlink} also gathers any arguments set by the use of
9238 @code{pragma Linker_Options} and adds them to the list of arguments
9239 presented to the linker.
9240
9241 @ifset vms
9242 @command{gnatlink} accepts the following types of extra files on the command
9243 line: objects (@file{.OBJ}), libraries (@file{.OLB}), sharable images
9244 (@file{.EXE}), and options files (@file{.OPT}). These are recognized and
9245 handled according to their extension.
9246 @end ifset
9247
9248 @node Switches for gnatlink
9249 @section Switches for @command{gnatlink}
9250
9251 @noindent
9252 The following switches are available with the @command{gnatlink} utility:
9253
9254 @table @option
9255 @c !sort!
9256
9257 @item --version
9258 @cindex @option{--version} @command{gnatlink}
9259 Display Copyright and version, then exit disregarding all other options.
9260
9261 @item --help
9262 @cindex @option{--help} @command{gnatlink}
9263 If @option{--version} was not used, display usage, then exit disregarding
9264 all other options.
9265
9266 @item ^-f^/FORCE_OBJECT_FILE_LIST^
9267 @cindex Command line length
9268 @cindex @option{^-f^/FORCE_OBJECT_FILE_LIST^} (@command{gnatlink})
9269 On some targets, the command line length is limited, and @command{gnatlink}
9270 will generate a separate file for the linker if the list of object files
9271 is too long.
9272 The @option{^-f^/FORCE_OBJECT_FILE_LIST^} switch forces this file
9273 to be generated even if
9274 the limit is not exceeded. This is useful in some cases to deal with
9275 special situations where the command line length is exceeded.
9276
9277 @item ^-g^/DEBUG^
9278 @cindex Debugging information, including
9279 @cindex @option{^-g^/DEBUG^} (@command{gnatlink})
9280 The option to include debugging information causes the Ada bind file (in
9281 other words, @file{b~@var{mainprog}.adb}) to be compiled with
9282 @option{^-g^/DEBUG^}.
9283 In addition, the binder does not delete the @file{b~@var{mainprog}.adb},
9284 @file{b~@var{mainprog}.o} and @file{b~@var{mainprog}.ali} files.
9285 Without @option{^-g^/DEBUG^}, the binder removes these files by
9286 default. The same procedure apply if a C bind file was generated using
9287 @option{^-C^/BIND_FILE=C^} @code{gnatbind} option, in this case the filenames
9288 are @file{b_@var{mainprog}.c} and @file{b_@var{mainprog}.o}.
9289
9290 @item ^-n^/NOCOMPILE^
9291 @cindex @option{^-n^/NOCOMPILE^} (@command{gnatlink})
9292 Do not compile the file generated by the binder. This may be used when
9293 a link is rerun with different options, but there is no need to recompile
9294 the binder file.
9295
9296 @item ^-v^/VERBOSE^
9297 @cindex @option{^-v^/VERBOSE^} (@command{gnatlink})
9298 Causes additional information to be output, including a full list of the
9299 included object files. This switch option is most useful when you want
9300 to see what set of object files are being used in the link step.
9301
9302 @item ^-v -v^/VERBOSE/VERBOSE^
9303 @cindex @option{^-v -v^/VERBOSE/VERBOSE^} (@command{gnatlink})
9304 Very verbose mode. Requests that the compiler operate in verbose mode when
9305 it compiles the binder file, and that the system linker run in verbose mode.
9306
9307 @item ^-o ^/EXECUTABLE=^@var{exec-name}
9308 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatlink})
9309 @var{exec-name} specifies an alternate name for the generated
9310 executable program. If this switch is omitted, the executable has the same
9311 name as the main unit. For example, @code{gnatlink try.ali} creates
9312 an executable called @file{^try^TRY.EXE^}.
9313
9314 @ifclear vms
9315 @item -b @var{target}
9316 @cindex @option{-b} (@command{gnatlink})
9317 Compile your program to run on @var{target}, which is the name of a
9318 system configuration. You must have a GNAT cross-compiler built if
9319 @var{target} is not the same as your host system.
9320
9321 @item -B@var{dir}
9322 @cindex @option{-B} (@command{gnatlink})
9323 Load compiler executables (for example, @code{gnat1}, the Ada compiler)
9324 from @var{dir} instead of the default location. Only use this switch
9325 when multiple versions of the GNAT compiler are available.
9326 @xref{Directory Options,,, gcc, The GNU Compiler Collection},
9327 for further details. You would normally use the @option{-b} or
9328 @option{-V} switch instead.
9329
9330 @item -M
9331 When linking an executable, create a map file. The name of the map file
9332 has the same name as the executable with extension ".map".
9333
9334 @item -M=mapfile
9335 When linking an executable, create a map file. The name of the map file is
9336 "mapfile".
9337
9338 @item --GCC=@var{compiler_name}
9339 @cindex @option{--GCC=compiler_name} (@command{gnatlink})
9340 Program used for compiling the binder file. The default is
9341 @command{gcc}. You need to use quotes around @var{compiler_name} if
9342 @code{compiler_name} contains spaces or other separator characters.
9343 As an example @option{--GCC="foo -x -y"} will instruct @command{gnatlink} to
9344 use @code{foo -x -y} as your compiler. Note that switch @option{-c} is always
9345 inserted after your command name. Thus in the above example the compiler
9346 command that will be used by @command{gnatlink} will be @code{foo -c -x -y}.
9347 A limitation of this syntax is that the name and path name of the executable
9348 itself must not include any embedded spaces. If the compiler executable is
9349 different from the default one (gcc or <prefix>-gcc), then the back-end
9350 switches in the ALI file are not used to compile the binder generated source.
9351 For example, this is the case with @option{--GCC="foo -x -y"}. But the back end
9352 switches will be used for @option{--GCC="gcc -gnatv"}. If several
9353 @option{--GCC=compiler_name} are used, only the last @var{compiler_name}
9354 is taken into account. However, all the additional switches are also taken
9355 into account. Thus,
9356 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9357 @option{--GCC="bar -x -y -z -t"}.
9358
9359 @item --LINK=@var{name}
9360 @cindex @option{--LINK=} (@command{gnatlink})
9361 @var{name} is the name of the linker to be invoked. This is especially
9362 useful in mixed language programs since languages such as C++ require
9363 their own linker to be used. When this switch is omitted, the default
9364 name for the linker is @command{gcc}. When this switch is used, the
9365 specified linker is called instead of @command{gcc} with exactly the same
9366 parameters that would have been passed to @command{gcc} so if the desired
9367 linker requires different parameters it is necessary to use a wrapper
9368 script that massages the parameters before invoking the real linker. It
9369 may be useful to control the exact invocation by using the verbose
9370 switch.
9371
9372 @end ifclear
9373
9374 @ifset vms
9375 @item /DEBUG=TRACEBACK
9376 @cindex @code{/DEBUG=TRACEBACK} (@command{gnatlink})
9377 This qualifier causes sufficient information to be included in the
9378 executable file to allow a traceback, but does not include the full
9379 symbol information needed by the debugger.
9380
9381 @item /IDENTIFICATION="<string>"
9382 @code{"<string>"} specifies the string to be stored in the image file
9383 identification field in the image header.
9384 It overrides any pragma @code{Ident} specified string.
9385
9386 @item /NOINHIBIT-EXEC
9387 Generate the executable file even if there are linker warnings.
9388
9389 @item /NOSTART_FILES
9390 Don't link in the object file containing the ``main'' transfer address.
9391 Used when linking with a foreign language main program compiled with an
9392 HP compiler.
9393
9394 @item /STATIC
9395 Prefer linking with object libraries over sharable images, even without
9396 /DEBUG.
9397 @end ifset
9398
9399 @end table
9400
9401 @node The GNAT Make Program gnatmake
9402 @chapter The GNAT Make Program @command{gnatmake}
9403 @findex gnatmake
9404
9405 @menu
9406 * Running gnatmake::
9407 * Switches for gnatmake::
9408 * Mode Switches for gnatmake::
9409 * Notes on the Command Line::
9410 * How gnatmake Works::
9411 * Examples of gnatmake Usage::
9412 @end menu
9413 @noindent
9414 A typical development cycle when working on an Ada program consists of
9415 the following steps:
9416
9417 @enumerate
9418 @item
9419 Edit some sources to fix bugs.
9420
9421 @item
9422 Add enhancements.
9423
9424 @item
9425 Compile all sources affected.
9426
9427 @item
9428 Rebind and relink.
9429
9430 @item
9431 Test.
9432 @end enumerate
9433
9434 @noindent
9435 The third step can be tricky, because not only do the modified files
9436 @cindex Dependency rules
9437 have to be compiled, but any files depending on these files must also be
9438 recompiled. The dependency rules in Ada can be quite complex, especially
9439 in the presence of overloading, @code{use} clauses, generics and inlined
9440 subprograms.
9441
9442 @command{gnatmake} automatically takes care of the third and fourth steps
9443 of this process. It determines which sources need to be compiled,
9444 compiles them, and binds and links the resulting object files.
9445
9446 Unlike some other Ada make programs, the dependencies are always
9447 accurately recomputed from the new sources. The source based approach of
9448 the GNAT compilation model makes this possible. This means that if
9449 changes to the source program cause corresponding changes in
9450 dependencies, they will always be tracked exactly correctly by
9451 @command{gnatmake}.
9452
9453 @node Running gnatmake
9454 @section Running @command{gnatmake}
9455
9456 @noindent
9457 The usual form of the @command{gnatmake} command is
9458
9459 @smallexample
9460 @c $ gnatmake @ovar{switches} @var{file_name}
9461 @c @ovar{file_names} @ovar{mode_switches}
9462 @c Expanding @ovar macro inline (explanation in macro def comments)
9463 $ gnatmake @r{[}@var{switches}@r{]} @var{file_name}
9464 @r{[}@var{file_names}@r{]} @r{[}@var{mode_switches}@r{]}
9465 @end smallexample
9466
9467 @noindent
9468 The only required argument is one @var{file_name}, which specifies
9469 a compilation unit that is a main program. Several @var{file_names} can be
9470 specified: this will result in several executables being built.
9471 If @code{switches} are present, they can be placed before the first
9472 @var{file_name}, between @var{file_names} or after the last @var{file_name}.
9473 If @var{mode_switches} are present, they must always be placed after
9474 the last @var{file_name} and all @code{switches}.
9475
9476 If you are using standard file extensions (@file{.adb} and @file{.ads}), then the
9477 extension may be omitted from the @var{file_name} arguments. However, if
9478 you are using non-standard extensions, then it is required that the
9479 extension be given. A relative or absolute directory path can be
9480 specified in a @var{file_name}, in which case, the input source file will
9481 be searched for in the specified directory only. Otherwise, the input
9482 source file will first be searched in the directory where
9483 @command{gnatmake} was invoked and if it is not found, it will be search on
9484 the source path of the compiler as described in
9485 @ref{Search Paths and the Run-Time Library (RTL)}.
9486
9487 All @command{gnatmake} output (except when you specify
9488 @option{^-M^/DEPENDENCIES_LIST^}) is to
9489 @file{stderr}. The output produced by the
9490 @option{^-M^/DEPENDENCIES_LIST^} switch is send to
9491 @file{stdout}.
9492
9493 @node Switches for gnatmake
9494 @section Switches for @command{gnatmake}
9495
9496 @noindent
9497 You may specify any of the following switches to @command{gnatmake}:
9498
9499 @table @option
9500 @c !sort!
9501
9502 @item --version
9503 @cindex @option{--version} @command{gnatmake}
9504 Display Copyright and version, then exit disregarding all other options.
9505
9506 @item --help
9507 @cindex @option{--help} @command{gnatmake}
9508 If @option{--version} was not used, display usage, then exit disregarding
9509 all other options.
9510
9511 @ifclear vms
9512 @item --GCC=@var{compiler_name}
9513 @cindex @option{--GCC=compiler_name} (@command{gnatmake})
9514 Program used for compiling. The default is `@command{gcc}'. You need to use
9515 quotes around @var{compiler_name} if @code{compiler_name} contains
9516 spaces or other separator characters. As an example @option{--GCC="foo -x
9517 -y"} will instruct @command{gnatmake} to use @code{foo -x -y} as your
9518 compiler. A limitation of this syntax is that the name and path name of
9519 the executable itself must not include any embedded spaces. Note that
9520 switch @option{-c} is always inserted after your command name. Thus in the
9521 above example the compiler command that will be used by @command{gnatmake}
9522 will be @code{foo -c -x -y}. If several @option{--GCC=compiler_name} are
9523 used, only the last @var{compiler_name} is taken into account. However,
9524 all the additional switches are also taken into account. Thus,
9525 @option{--GCC="foo -x -y" --GCC="bar -z -t"} is equivalent to
9526 @option{--GCC="bar -x -y -z -t"}.
9527
9528 @item --GNATBIND=@var{binder_name}
9529 @cindex @option{--GNATBIND=binder_name} (@command{gnatmake})
9530 Program used for binding. The default is `@code{gnatbind}'. You need to
9531 use quotes around @var{binder_name} if @var{binder_name} contains spaces
9532 or other separator characters. As an example @option{--GNATBIND="bar -x
9533 -y"} will instruct @command{gnatmake} to use @code{bar -x -y} as your
9534 binder. Binder switches that are normally appended by @command{gnatmake}
9535 to `@code{gnatbind}' are now appended to the end of @code{bar -x -y}.
9536 A limitation of this syntax is that the name and path name of the executable
9537 itself must not include any embedded spaces.
9538
9539 @item --GNATLINK=@var{linker_name}
9540 @cindex @option{--GNATLINK=linker_name} (@command{gnatmake})
9541 Program used for linking. The default is `@command{gnatlink}'. You need to
9542 use quotes around @var{linker_name} if @var{linker_name} contains spaces
9543 or other separator characters. As an example @option{--GNATLINK="lan -x
9544 -y"} will instruct @command{gnatmake} to use @code{lan -x -y} as your
9545 linker. Linker switches that are normally appended by @command{gnatmake} to
9546 `@command{gnatlink}' are now appended to the end of @code{lan -x -y}.
9547 A limitation of this syntax is that the name and path name of the executable
9548 itself must not include any embedded spaces.
9549
9550 @end ifclear
9551
9552 @item ^--subdirs^/SUBDIRS^=subdir
9553 Actual object directory of each project file is the subdirectory subdir of the
9554 object directory specified or defaulted in the project file.
9555
9556 @item ^--single-compile-per-obj-dir^/SINGLE_COMPILE_PER_OBJ_DIR^
9557 Disallow simultaneous compilations in the same object directory when
9558 project files are used.
9559
9560 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
9561 By default, shared library projects are not allowed to import static library
9562 projects. When this switch is used on the command line, this restriction is
9563 relaxed.
9564
9565 @item ^--source-info=<source info file>^/SRC_INFO=source-info-file^
9566 Specify a source info file. This switch is active only when project files
9567 are used. If the source info file is specified as a relative path, then it is
9568 relative to the object directory of the main project. If the source info file
9569 does not exist, then after the Project Manager has successfully parsed and
9570 processed the project files and found the sources, it creates the source info
9571 file. If the source info file already exists and can be read successfully,
9572 then the Project Manager will get all the needed information about the sources
9573 from the source info file and will not look for them. This reduces the time
9574 to process the project files, especially when looking for sources that take a
9575 long time. If the source info file exists but cannot be parsed successfully,
9576 the Project Manager will attempt to recreate it. If the Project Manager fails
9577 to create the source info file, a message is issued, but gnatmake does not
9578 fail. @command{gnatmake} "trusts" the source info file. This means that
9579 if the source files have changed (addition, deletion, moving to a different
9580 source directory), then the source info file need to be deleted and recreated.
9581
9582 @ifclear vms
9583 @item --create-map-file
9584 When linking an executable, create a map file. The name of the map file
9585 has the same name as the executable with extension ".map".
9586
9587 @item --create-map-file=mapfile
9588 When linking an executable, create a map file. The name of the map file is
9589 "mapfile".
9590
9591 @end ifclear
9592
9593 @item ^-a^/ALL_FILES^
9594 @cindex @option{^-a^/ALL_FILES^} (@command{gnatmake})
9595 Consider all files in the make process, even the GNAT internal system
9596 files (for example, the predefined Ada library files), as well as any
9597 locked files. Locked files are files whose ALI file is write-protected.
9598 By default,
9599 @command{gnatmake} does not check these files,
9600 because the assumption is that the GNAT internal files are properly up
9601 to date, and also that any write protected ALI files have been properly
9602 installed. Note that if there is an installation problem, such that one
9603 of these files is not up to date, it will be properly caught by the
9604 binder.
9605 You may have to specify this switch if you are working on GNAT
9606 itself. The switch @option{^-a^/ALL_FILES^} is also useful
9607 in conjunction with @option{^-f^/FORCE_COMPILE^}
9608 if you need to recompile an entire application,
9609 including run-time files, using special configuration pragmas,
9610 such as a @code{Normalize_Scalars} pragma.
9611
9612 By default
9613 @code{gnatmake ^-a^/ALL_FILES^} compiles all GNAT
9614 internal files with
9615 @ifclear vms
9616 @code{gcc -c -gnatpg} rather than @code{gcc -c}.
9617 @end ifclear
9618 @ifset vms
9619 the @code{/CHECKS=SUPPRESS_ALL /STYLE_CHECKS=GNAT} switch.
9620 @end ifset
9621
9622 @item ^-b^/ACTIONS=BIND^
9623 @cindex @option{^-b^/ACTIONS=BIND^} (@command{gnatmake})
9624 Bind only. Can be combined with @option{^-c^/ACTIONS=COMPILE^} to do
9625 compilation and binding, but no link.
9626 Can be combined with @option{^-l^/ACTIONS=LINK^}
9627 to do binding and linking. When not combined with
9628 @option{^-c^/ACTIONS=COMPILE^}
9629 all the units in the closure of the main program must have been previously
9630 compiled and must be up to date. The root unit specified by @var{file_name}
9631 may be given without extension, with the source extension or, if no GNAT
9632 Project File is specified, with the ALI file extension.
9633
9634 @item ^-c^/ACTIONS=COMPILE^
9635 @cindex @option{^-c^/ACTIONS=COMPILE^} (@command{gnatmake})
9636 Compile only. Do not perform binding, except when @option{^-b^/ACTIONS=BIND^}
9637 is also specified. Do not perform linking, except if both
9638 @option{^-b^/ACTIONS=BIND^} and
9639 @option{^-l^/ACTIONS=LINK^} are also specified.
9640 If the root unit specified by @var{file_name} is not a main unit, this is the
9641 default. Otherwise @command{gnatmake} will attempt binding and linking
9642 unless all objects are up to date and the executable is more recent than
9643 the objects.
9644
9645 @item ^-C^/MAPPING^
9646 @cindex @option{^-C^/MAPPING^} (@command{gnatmake})
9647 Use a temporary mapping file. A mapping file is a way to communicate
9648 to the compiler two mappings: from unit names to file names (without
9649 any directory information) and from file names to path names (with
9650 full directory information). A mapping file can make the compiler's
9651 file searches faster, especially if there are many source directories,
9652 or the sources are read over a slow network connection. If
9653 @option{^-P^/PROJECT_FILE^} is used, a mapping file is always used, so
9654 @option{^-C^/MAPPING^} is unnecessary; in this case the mapping file
9655 is initially populated based on the project file. If
9656 @option{^-C^/MAPPING^} is used without
9657 @option{^-P^/PROJECT_FILE^},
9658 the mapping file is initially empty. Each invocation of the compiler
9659 will add any newly accessed sources to the mapping file.
9660
9661 @item ^-C=^/USE_MAPPING_FILE=^@var{file}
9662 @cindex @option{^-C=^/USE_MAPPING^} (@command{gnatmake})
9663 Use a specific mapping file. The file, specified as a path name (absolute or
9664 relative) by this switch, should already exist, otherwise the switch is
9665 ineffective. The specified mapping file will be communicated to the compiler.
9666 This switch is not compatible with a project file
9667 (^-P^/PROJECT_FILE=^@var{file}) or with multiple compiling processes
9668 (^-j^/PROCESSES=^nnn, when nnn is greater than 1).
9669
9670 @item ^-d^/DISPLAY_PROGRESS^
9671 @cindex @option{^-d^/DISPLAY_PROGRESS^} (@command{gnatmake})
9672 Display progress for each source, up to date or not, as a single line
9673
9674 @smallexample
9675 completed x out of y (zz%)
9676 @end smallexample
9677
9678 If the file needs to be compiled this is displayed after the invocation of
9679 the compiler. These lines are displayed even in quiet output mode.
9680
9681 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
9682 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@command{gnatmake})
9683 Put all object files and ALI file in directory @var{dir}.
9684 If the @option{^-D^/DIRECTORY_OBJECTS^} switch is not used, all object files
9685 and ALI files go in the current working directory.
9686
9687 This switch cannot be used when using a project file.
9688
9689 @item -eInnn
9690 @cindex @option{-eI} (@command{gnatmake})
9691 Indicates that the main source is a multi-unit source and the rank of the unit
9692 in the source file is nnn. nnn needs to be a positive number and a valid
9693 index in the source. This switch cannot be used when @command{gnatmake} is
9694 invoked for several mains.
9695
9696 @ifclear vms
9697 @item -eL
9698 @cindex @option{-eL} (@command{gnatmake})
9699 @cindex symbolic links
9700 Follow all symbolic links when processing project files.
9701 This should be used if your project uses symbolic links for files or
9702 directories, but is not needed in other cases.
9703
9704 @cindex naming scheme
9705 This also assumes that no directory matches the naming scheme for files (for
9706 instance that you do not have a directory called "sources.ads" when using the
9707 default GNAT naming scheme).
9708
9709 When you do not have to use this switch (i.e.@: by default), gnatmake is able to
9710 save a lot of system calls (several per source file and object file), which
9711 can result in a significant speed up to load and manipulate a project file,
9712 especially when using source files from a remote system.
9713
9714 @end ifclear
9715
9716 @item ^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^
9717 @cindex @option{^-eS^/STANDARD_OUTPUT_FOR_COMMANDS^} (@command{gnatmake})
9718 Output the commands for the compiler, the binder and the linker
9719 on ^standard output^SYS$OUTPUT^,
9720 instead of ^standard error^SYS$ERROR^.
9721
9722 @item ^-f^/FORCE_COMPILE^
9723 @cindex @option{^-f^/FORCE_COMPILE^} (@command{gnatmake})
9724 Force recompilations. Recompile all sources, even though some object
9725 files may be up to date, but don't recompile predefined or GNAT internal
9726 files or locked files (files with a write-protected ALI file),
9727 unless the @option{^-a^/ALL_FILES^} switch is also specified.
9728
9729 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
9730 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@command{gnatmake})
9731 When using project files, if some errors or warnings are detected during
9732 parsing and verbose mode is not in effect (no use of switch
9733 ^-v^/VERBOSE^), then error lines start with the full path name of the project
9734 file, rather than its simple file name.
9735
9736 @item ^-g^/DEBUG^
9737 @cindex @option{^-g^/DEBUG^} (@command{gnatmake})
9738 Enable debugging. This switch is simply passed to the compiler and to the
9739 linker.
9740
9741 @item ^-i^/IN_PLACE^
9742 @cindex @option{^-i^/IN_PLACE^} (@command{gnatmake})
9743 In normal mode, @command{gnatmake} compiles all object files and ALI files
9744 into the current directory. If the @option{^-i^/IN_PLACE^} switch is used,
9745 then instead object files and ALI files that already exist are overwritten
9746 in place. This means that once a large project is organized into separate
9747 directories in the desired manner, then @command{gnatmake} will automatically
9748 maintain and update this organization. If no ALI files are found on the
9749 Ada object path (@ref{Search Paths and the Run-Time Library (RTL)}),
9750 the new object and ALI files are created in the
9751 directory containing the source being compiled. If another organization
9752 is desired, where objects and sources are kept in different directories,
9753 a useful technique is to create dummy ALI files in the desired directories.
9754 When detecting such a dummy file, @command{gnatmake} will be forced to
9755 recompile the corresponding source file, and it will be put the resulting
9756 object and ALI files in the directory where it found the dummy file.
9757
9758 @item ^-j^/PROCESSES=^@var{n}
9759 @cindex @option{^-j^/PROCESSES^} (@command{gnatmake})
9760 @cindex Parallel make
9761 Use @var{n} processes to carry out the (re)compilations. On a multiprocessor
9762 machine compilations will occur in parallel. If @var{n} is 0, then the
9763 maximum number of parallel compilations is the number of core processors
9764 on the platform. In the event of compilation errors, messages from various
9765 compilations might get interspersed (but @command{gnatmake} will give you the
9766 full ordered list of failing compiles at the end). If this is problematic,
9767 rerun the make process with n set to 1 to get a clean list of messages.
9768
9769 @item ^-k^/CONTINUE_ON_ERROR^
9770 @cindex @option{^-k^/CONTINUE_ON_ERROR^} (@command{gnatmake})
9771 Keep going. Continue as much as possible after a compilation error. To
9772 ease the programmer's task in case of compilation errors, the list of
9773 sources for which the compile fails is given when @command{gnatmake}
9774 terminates.
9775
9776 If @command{gnatmake} is invoked with several @file{file_names} and with this
9777 switch, if there are compilation errors when building an executable,
9778 @command{gnatmake} will not attempt to build the following executables.
9779
9780 @item ^-l^/ACTIONS=LINK^
9781 @cindex @option{^-l^/ACTIONS=LINK^} (@command{gnatmake})
9782 Link only. Can be combined with @option{^-b^/ACTIONS=BIND^} to binding
9783 and linking. Linking will not be performed if combined with
9784 @option{^-c^/ACTIONS=COMPILE^}
9785 but not with @option{^-b^/ACTIONS=BIND^}.
9786 When not combined with @option{^-b^/ACTIONS=BIND^}
9787 all the units in the closure of the main program must have been previously
9788 compiled and must be up to date, and the main program needs to have been bound.
9789 The root unit specified by @var{file_name}
9790 may be given without extension, with the source extension or, if no GNAT
9791 Project File is specified, with the ALI file extension.
9792
9793 @item ^-m^/MINIMAL_RECOMPILATION^
9794 @cindex @option{^-m^/MINIMAL_RECOMPILATION^} (@command{gnatmake})
9795 Specify that the minimum necessary amount of recompilations
9796 be performed. In this mode @command{gnatmake} ignores time
9797 stamp differences when the only
9798 modifications to a source file consist in adding/removing comments,
9799 empty lines, spaces or tabs. This means that if you have changed the
9800 comments in a source file or have simply reformatted it, using this
9801 switch will tell @command{gnatmake} not to recompile files that depend on it
9802 (provided other sources on which these files depend have undergone no
9803 semantic modifications). Note that the debugging information may be
9804 out of date with respect to the sources if the @option{-m} switch causes
9805 a compilation to be switched, so the use of this switch represents a
9806 trade-off between compilation time and accurate debugging information.
9807
9808 @item ^-M^/DEPENDENCIES_LIST^
9809 @cindex Dependencies, producing list
9810 @cindex @option{^-M^/DEPENDENCIES_LIST^} (@command{gnatmake})
9811 Check if all objects are up to date. If they are, output the object
9812 dependences to @file{stdout} in a form that can be directly exploited in
9813 a @file{Makefile}. By default, each source file is prefixed with its
9814 (relative or absolute) directory name. This name is whatever you
9815 specified in the various @option{^-aI^/SOURCE_SEARCH^}
9816 and @option{^-I^/SEARCH^} switches. If you use
9817 @code{gnatmake ^-M^/DEPENDENCIES_LIST^}
9818 @option{^-q^/QUIET^}
9819 (see below), only the source file names,
9820 without relative paths, are output. If you just specify the
9821 @option{^-M^/DEPENDENCIES_LIST^}
9822 switch, dependencies of the GNAT internal system files are omitted. This
9823 is typically what you want. If you also specify
9824 the @option{^-a^/ALL_FILES^} switch,
9825 dependencies of the GNAT internal files are also listed. Note that
9826 dependencies of the objects in external Ada libraries (see switch
9827 @option{^-aL^/SKIP_MISSING=^}@var{dir} in the following list)
9828 are never reported.
9829
9830 @item ^-n^/DO_OBJECT_CHECK^
9831 @cindex @option{^-n^/DO_OBJECT_CHECK^} (@command{gnatmake})
9832 Don't compile, bind, or link. Checks if all objects are up to date.
9833 If they are not, the full name of the first file that needs to be
9834 recompiled is printed.
9835 Repeated use of this option, followed by compiling the indicated source
9836 file, will eventually result in recompiling all required units.
9837
9838 @item ^-o ^/EXECUTABLE=^@var{exec_name}
9839 @cindex @option{^-o^/EXECUTABLE^} (@command{gnatmake})
9840 Output executable name. The name of the final executable program will be
9841 @var{exec_name}. If the @option{^-o^/EXECUTABLE^} switch is omitted the default
9842 name for the executable will be the name of the input file in appropriate form
9843 for an executable file on the host system.
9844
9845 This switch cannot be used when invoking @command{gnatmake} with several
9846 @file{file_names}.
9847
9848 @item ^-p or --create-missing-dirs^/CREATE_MISSING_DIRS^
9849 @cindex @option{^-p^/CREATE_MISSING_DIRS^} (@command{gnatmake})
9850 When using project files (^-P^/PROJECT_FILE=^@var{project}), create
9851 automatically missing object directories, library directories and exec
9852 directories.
9853
9854 @item ^-P^/PROJECT_FILE=^@var{project}
9855 @cindex @option{^-P^/PROJECT_FILE^} (@command{gnatmake})
9856 Use project file @var{project}. Only one such switch can be used.
9857 @xref{gnatmake and Project Files}.
9858
9859 @item ^-q^/QUIET^
9860 @cindex @option{^-q^/QUIET^} (@command{gnatmake})
9861 Quiet. When this flag is not set, the commands carried out by
9862 @command{gnatmake} are displayed.
9863
9864 @item ^-s^/SWITCH_CHECK/^
9865 @cindex @option{^-s^/SWITCH_CHECK^} (@command{gnatmake})
9866 Recompile if compiler switches have changed since last compilation.
9867 All compiler switches but -I and -o are taken into account in the
9868 following way:
9869 orders between different ``first letter'' switches are ignored, but
9870 orders between same switches are taken into account. For example,
9871 @option{-O -O2} is different than @option{-O2 -O}, but @option{-g -O}
9872 is equivalent to @option{-O -g}.
9873
9874 This switch is recommended when Integrated Preprocessing is used.
9875
9876 @item ^-u^/UNIQUE^
9877 @cindex @option{^-u^/UNIQUE^} (@command{gnatmake})
9878 Unique. Recompile at most the main files. It implies -c. Combined with
9879 -f, it is equivalent to calling the compiler directly. Note that using
9880 ^-u^/UNIQUE^ with a project file and no main has a special meaning
9881 (@pxref{Project Files and Main Subprograms}).
9882
9883 @item ^-U^/ALL_PROJECTS^
9884 @cindex @option{^-U^/ALL_PROJECTS^} (@command{gnatmake})
9885 When used without a project file or with one or several mains on the command
9886 line, is equivalent to ^-u^/UNIQUE^. When used with a project file and no main
9887 on the command line, all sources of all project files are checked and compiled
9888 if not up to date, and libraries are rebuilt, if necessary.
9889
9890 @item ^-v^/REASONS^
9891 @cindex @option{^-v^/REASONS^} (@command{gnatmake})
9892 Verbose. Display the reason for all recompilations @command{gnatmake}
9893 decides are necessary, with the highest verbosity level.
9894
9895 @item ^-vl^/LOW_VERBOSITY^
9896 @cindex @option{^-vl^/LOW_VERBOSITY^} (@command{gnatmake})
9897 Verbosity level Low. Display fewer lines than in verbosity Medium.
9898
9899 @item ^-vm^/MEDIUM_VERBOSITY^
9900 @cindex @option{^-vm^/MEDIUM_VERBOSITY^} (@command{gnatmake})
9901 Verbosity level Medium. Potentially display fewer lines than in verbosity High.
9902
9903 @item ^-vh^/HIGH_VERBOSITY^
9904 @cindex @option{^-vm^/HIGH_VERBOSITY^} (@command{gnatmake})
9905 Verbosity level High. Equivalent to ^-v^/REASONS^.
9906
9907 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
9908 Indicate the verbosity of the parsing of GNAT project files.
9909 @xref{Switches Related to Project Files}.
9910
9911 @item ^-x^/NON_PROJECT_UNIT_COMPILATION^
9912 @cindex @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} (@command{gnatmake})
9913 Indicate that sources that are not part of any Project File may be compiled.
9914 Normally, when using Project Files, only sources that are part of a Project
9915 File may be compile. When this switch is used, a source outside of all Project
9916 Files may be compiled. The ALI file and the object file will be put in the
9917 object directory of the main Project. The compilation switches used will only
9918 be those specified on the command line. Even when
9919 @option{^-x^/NON_PROJECT_UNIT_COMPILATION^} is used, mains specified on the
9920 command line need to be sources of a project file.
9921
9922 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
9923 Indicate that external variable @var{name} has the value @var{value}.
9924 The Project Manager will use this value for occurrences of
9925 @code{external(name)} when parsing the project file.
9926 @xref{Switches Related to Project Files}.
9927
9928 @item ^-z^/NOMAIN^
9929 @cindex @option{^-z^/NOMAIN^} (@command{gnatmake})
9930 No main subprogram. Bind and link the program even if the unit name
9931 given on the command line is a package name. The resulting executable
9932 will execute the elaboration routines of the package and its closure,
9933 then the finalization routines.
9934
9935 @end table
9936
9937 @table @asis
9938 @item @command{gcc} @asis{switches}
9939 @ifclear vms
9940 Any uppercase or multi-character switch that is not a @command{gnatmake} switch
9941 is passed to @command{gcc} (e.g.@: @option{-O}, @option{-gnato,} etc.)
9942 @end ifclear
9943 @ifset vms
9944 Any qualifier that cannot be recognized as a qualifier for @code{GNAT MAKE}
9945 but is recognizable as a valid qualifier for @code{GNAT COMPILE} is
9946 automatically treated as a compiler switch, and passed on to all
9947 compilations that are carried out.
9948 @end ifset
9949 @end table
9950
9951 @noindent
9952 Source and library search path switches:
9953
9954 @table @option
9955 @c !sort!
9956 @item ^-aI^/SOURCE_SEARCH=^@var{dir}
9957 @cindex @option{^-aI^/SOURCE_SEARCH^} (@command{gnatmake})
9958 When looking for source files also look in directory @var{dir}.
9959 The order in which source files search is undertaken is
9960 described in @ref{Search Paths and the Run-Time Library (RTL)}.
9961
9962 @item ^-aL^/SKIP_MISSING=^@var{dir}
9963 @cindex @option{^-aL^/SKIP_MISSING^} (@command{gnatmake})
9964 Consider @var{dir} as being an externally provided Ada library.
9965 Instructs @command{gnatmake} to skip compilation units whose @file{.ALI}
9966 files have been located in directory @var{dir}. This allows you to have
9967 missing bodies for the units in @var{dir} and to ignore out of date bodies
9968 for the same units. You still need to specify
9969 the location of the specs for these units by using the switches
9970 @option{^-aI^/SOURCE_SEARCH=^@var{dir}}
9971 or @option{^-I^/SEARCH=^@var{dir}}.
9972 Note: this switch is provided for compatibility with previous versions
9973 of @command{gnatmake}. The easier method of causing standard libraries
9974 to be excluded from consideration is to write-protect the corresponding
9975 ALI files.
9976
9977 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
9978 @cindex @option{^-aO^/OBJECT_SEARCH^} (@command{gnatmake})
9979 When searching for library and object files, look in directory
9980 @var{dir}. The order in which library files are searched is described in
9981 @ref{Search Paths for gnatbind}.
9982
9983 @item ^-A^/CONDITIONAL_SOURCE_SEARCH=^@var{dir}
9984 @cindex Search paths, for @command{gnatmake}
9985 @cindex @option{^-A^/CONDITIONAL_SOURCE_SEARCH^} (@command{gnatmake})
9986 Equivalent to @option{^-aL^/SKIP_MISSING=^@var{dir}
9987 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9988
9989 @item ^-I^/SEARCH=^@var{dir}
9990 @cindex @option{^-I^/SEARCH^} (@command{gnatmake})
9991 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}
9992 ^-aI^/SOURCE_SEARCH=^@var{dir}}.
9993
9994 @item ^-I-^/NOCURRENT_DIRECTORY^
9995 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatmake})
9996 @cindex Source files, suppressing search
9997 Do not look for source files in the directory containing the source
9998 file named in the command line.
9999 Do not look for ALI or object files in the directory
10000 where @command{gnatmake} was invoked.
10001
10002 @item ^-L^/LIBRARY_SEARCH=^@var{dir}
10003 @cindex @option{^-L^/LIBRARY_SEARCH^} (@command{gnatmake})
10004 @cindex Linker libraries
10005 Add directory @var{dir} to the list of directories in which the linker
10006 will search for libraries. This is equivalent to
10007 @option{-largs ^-L^/LIBRARY_SEARCH=^}@var{dir}.
10008 @ifclear vms
10009 Furthermore, under Windows, the sources pointed to by the libraries path
10010 set in the registry are not searched for.
10011 @end ifclear
10012
10013 @item -nostdinc
10014 @cindex @option{-nostdinc} (@command{gnatmake})
10015 Do not look for source files in the system default directory.
10016
10017 @item -nostdlib
10018 @cindex @option{-nostdlib} (@command{gnatmake})
10019 Do not look for library files in the system default directory.
10020
10021 @item --RTS=@var{rts-path}
10022 @cindex @option{--RTS} (@command{gnatmake})
10023 Specifies the default location of the runtime library. GNAT looks for the
10024 runtime
10025 in the following directories, and stops as soon as a valid runtime is found
10026 (@file{adainclude} or @file{ada_source_path}, and @file{adalib} or
10027 @file{ada_object_path} present):
10028
10029 @itemize @bullet
10030 @item <current directory>/$rts_path
10031
10032 @item <default-search-dir>/$rts_path
10033
10034 @item <default-search-dir>/rts-$rts_path
10035 @end itemize
10036
10037 @noindent
10038 The selected path is handled like a normal RTS path.
10039
10040 @end table
10041
10042 @node Mode Switches for gnatmake
10043 @section Mode Switches for @command{gnatmake}
10044
10045 @noindent
10046 The mode switches (referred to as @code{mode_switches}) allow the
10047 inclusion of switches that are to be passed to the compiler itself, the
10048 binder or the linker. The effect of a mode switch is to cause all
10049 subsequent switches up to the end of the switch list, or up to the next
10050 mode switch, to be interpreted as switches to be passed on to the
10051 designated component of GNAT.
10052
10053 @table @option
10054 @c !sort!
10055 @item -cargs @var{switches}
10056 @cindex @option{-cargs} (@command{gnatmake})
10057 Compiler switches. Here @var{switches} is a list of switches
10058 that are valid switches for @command{gcc}. They will be passed on to
10059 all compile steps performed by @command{gnatmake}.
10060
10061 @item -bargs @var{switches}
10062 @cindex @option{-bargs} (@command{gnatmake})
10063 Binder switches. Here @var{switches} is a list of switches
10064 that are valid switches for @code{gnatbind}. They will be passed on to
10065 all bind steps performed by @command{gnatmake}.
10066
10067 @item -largs @var{switches}
10068 @cindex @option{-largs} (@command{gnatmake})
10069 Linker switches. Here @var{switches} is a list of switches
10070 that are valid switches for @command{gnatlink}. They will be passed on to
10071 all link steps performed by @command{gnatmake}.
10072
10073 @item -margs @var{switches}
10074 @cindex @option{-margs} (@command{gnatmake})
10075 Make switches. The switches are directly interpreted by @command{gnatmake},
10076 regardless of any previous occurrence of @option{-cargs}, @option{-bargs}
10077 or @option{-largs}.
10078 @end table
10079
10080 @node Notes on the Command Line
10081 @section Notes on the Command Line
10082
10083 @noindent
10084 This section contains some additional useful notes on the operation
10085 of the @command{gnatmake} command.
10086
10087 @itemize @bullet
10088 @item
10089 @cindex Recompilation, by @command{gnatmake}
10090 If @command{gnatmake} finds no ALI files, it recompiles the main program
10091 and all other units required by the main program.
10092 This means that @command{gnatmake}
10093 can be used for the initial compile, as well as during subsequent steps of
10094 the development cycle.
10095
10096 @item
10097 If you enter @code{gnatmake @var{file}.adb}, where @file{@var{file}.adb}
10098 is a subunit or body of a generic unit, @command{gnatmake} recompiles
10099 @file{@var{file}.adb} (because it finds no ALI) and stops, issuing a
10100 warning.
10101
10102 @item
10103 In @command{gnatmake} the switch @option{^-I^/SEARCH^}
10104 is used to specify both source and
10105 library file paths. Use @option{^-aI^/SOURCE_SEARCH^}
10106 instead if you just want to specify
10107 source paths only and @option{^-aO^/OBJECT_SEARCH^}
10108 if you want to specify library paths
10109 only.
10110
10111 @item
10112 @command{gnatmake} will ignore any files whose ALI file is write-protected.
10113 This may conveniently be used to exclude standard libraries from
10114 consideration and in particular it means that the use of the
10115 @option{^-f^/FORCE_COMPILE^} switch will not recompile these files
10116 unless @option{^-a^/ALL_FILES^} is also specified.
10117
10118 @item
10119 @command{gnatmake} has been designed to make the use of Ada libraries
10120 particularly convenient. Assume you have an Ada library organized
10121 as follows: @i{^obj-dir^[OBJ_DIR]^} contains the objects and ALI files for
10122 of your Ada compilation units,
10123 whereas @i{^include-dir^[INCLUDE_DIR]^} contains the
10124 specs of these units, but no bodies. Then to compile a unit
10125 stored in @code{main.adb}, which uses this Ada library you would just type
10126
10127 @smallexample
10128 @ifclear vms
10129 $ gnatmake -aI@var{include-dir} -aL@var{obj-dir} main
10130 @end ifclear
10131 @ifset vms
10132 $ gnatmake /SOURCE_SEARCH=@i{[INCLUDE_DIR]}
10133 /SKIP_MISSING=@i{[OBJ_DIR]} main
10134 @end ifset
10135 @end smallexample
10136
10137 @item
10138 Using @command{gnatmake} along with the
10139 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}
10140 switch provides a mechanism for avoiding unnecessary recompilations. Using
10141 this switch,
10142 you can update the comments/format of your
10143 source files without having to recompile everything. Note, however, that
10144 adding or deleting lines in a source files may render its debugging
10145 info obsolete. If the file in question is a spec, the impact is rather
10146 limited, as that debugging info will only be useful during the
10147 elaboration phase of your program. For bodies the impact can be more
10148 significant. In all events, your debugger will warn you if a source file
10149 is more recent than the corresponding object, and alert you to the fact
10150 that the debugging information may be out of date.
10151 @end itemize
10152
10153 @node How gnatmake Works
10154 @section How @command{gnatmake} Works
10155
10156 @noindent
10157 Generally @command{gnatmake} automatically performs all necessary
10158 recompilations and you don't need to worry about how it works. However,
10159 it may be useful to have some basic understanding of the @command{gnatmake}
10160 approach and in particular to understand how it uses the results of
10161 previous compilations without incorrectly depending on them.
10162
10163 First a definition: an object file is considered @dfn{up to date} if the
10164 corresponding ALI file exists and if all the source files listed in the
10165 dependency section of this ALI file have time stamps matching those in
10166 the ALI file. This means that neither the source file itself nor any
10167 files that it depends on have been modified, and hence there is no need
10168 to recompile this file.
10169
10170 @command{gnatmake} works by first checking if the specified main unit is up
10171 to date. If so, no compilations are required for the main unit. If not,
10172 @command{gnatmake} compiles the main program to build a new ALI file that
10173 reflects the latest sources. Then the ALI file of the main unit is
10174 examined to find all the source files on which the main program depends,
10175 and @command{gnatmake} recursively applies the above procedure on all these
10176 files.
10177
10178 This process ensures that @command{gnatmake} only trusts the dependencies
10179 in an existing ALI file if they are known to be correct. Otherwise it
10180 always recompiles to determine a new, guaranteed accurate set of
10181 dependencies. As a result the program is compiled ``upside down'' from what may
10182 be more familiar as the required order of compilation in some other Ada
10183 systems. In particular, clients are compiled before the units on which
10184 they depend. The ability of GNAT to compile in any order is critical in
10185 allowing an order of compilation to be chosen that guarantees that
10186 @command{gnatmake} will recompute a correct set of new dependencies if
10187 necessary.
10188
10189 When invoking @command{gnatmake} with several @var{file_names}, if a unit is
10190 imported by several of the executables, it will be recompiled at most once.
10191
10192 Note: when using non-standard naming conventions
10193 (@pxref{Using Other File Names}), changing through a configuration pragmas
10194 file the version of a source and invoking @command{gnatmake} to recompile may
10195 have no effect, if the previous version of the source is still accessible
10196 by @command{gnatmake}. It may be necessary to use the switch
10197 ^-f^/FORCE_COMPILE^.
10198
10199 @node Examples of gnatmake Usage
10200 @section Examples of @command{gnatmake} Usage
10201
10202 @table @code
10203 @item gnatmake hello.adb
10204 Compile all files necessary to bind and link the main program
10205 @file{hello.adb} (containing unit @code{Hello}) and bind and link the
10206 resulting object files to generate an executable file @file{^hello^HELLO.EXE^}.
10207
10208 @item gnatmake main1 main2 main3
10209 Compile all files necessary to bind and link the main programs
10210 @file{main1.adb} (containing unit @code{Main1}), @file{main2.adb}
10211 (containing unit @code{Main2}) and @file{main3.adb}
10212 (containing unit @code{Main3}) and bind and link the resulting object files
10213 to generate three executable files @file{^main1^MAIN1.EXE^},
10214 @file{^main2^MAIN2.EXE^}
10215 and @file{^main3^MAIN3.EXE^}.
10216
10217 @ifclear vms
10218 @item gnatmake -q Main_Unit -cargs -O2 -bargs -l
10219 @end ifclear
10220
10221 @ifset vms
10222 @item gnatmake Main_Unit /QUIET
10223 /COMPILER_QUALIFIERS /OPTIMIZE=ALL
10224 /BINDER_QUALIFIERS /ORDER_OF_ELABORATION
10225 @end ifset
10226 Compile all files necessary to bind and link the main program unit
10227 @code{Main_Unit} (from file @file{main_unit.adb}). All compilations will
10228 be done with optimization level 2 and the order of elaboration will be
10229 listed by the binder. @command{gnatmake} will operate in quiet mode, not
10230 displaying commands it is executing.
10231 @end table
10232
10233 @c *************************
10234 @node Improving Performance
10235 @chapter Improving Performance
10236 @cindex Improving performance
10237
10238 @noindent
10239 This chapter presents several topics related to program performance.
10240 It first describes some of the tradeoffs that need to be considered
10241 and some of the techniques for making your program run faster.
10242 It then documents
10243 @ifclear FSFEDITION
10244 the @command{gnatelim} tool and
10245 @end ifclear
10246 unused subprogram/data
10247 elimination feature, which can reduce the size of program executables.
10248
10249 @ifnottex
10250 @menu
10251 * Performance Considerations::
10252 * Text_IO Suggestions::
10253 @ifclear FSFEDITION
10254 * Reducing Size of Ada Executables with gnatelim::
10255 @end ifclear
10256 * Reducing Size of Executables with unused subprogram/data elimination::
10257 @end menu
10258 @end ifnottex
10259
10260 @c *****************************
10261 @node Performance Considerations
10262 @section Performance Considerations
10263
10264 @noindent
10265 The GNAT system provides a number of options that allow a trade-off
10266 between
10267
10268 @itemize @bullet
10269 @item
10270 performance of the generated code
10271
10272 @item
10273 speed of compilation
10274
10275 @item
10276 minimization of dependences and recompilation
10277
10278 @item
10279 the degree of run-time checking.
10280 @end itemize
10281
10282 @noindent
10283 The defaults (if no options are selected) aim at improving the speed
10284 of compilation and minimizing dependences, at the expense of performance
10285 of the generated code:
10286
10287 @itemize @bullet
10288 @item
10289 no optimization
10290
10291 @item
10292 no inlining of subprogram calls
10293
10294 @item
10295 all run-time checks enabled except overflow and elaboration checks
10296 @end itemize
10297
10298 @noindent
10299 These options are suitable for most program development purposes. This
10300 chapter describes how you can modify these choices, and also provides
10301 some guidelines on debugging optimized code.
10302
10303 @menu
10304 * Controlling Run-Time Checks::
10305 * Use of Restrictions::
10306 * Optimization Levels::
10307 * Debugging Optimized Code::
10308 * Inlining of Subprograms::
10309 * Vectorization of loops::
10310 * Other Optimization Switches::
10311 * Optimization and Strict Aliasing::
10312 * Aliased Variables and Optimization::
10313 * Atomic Variables and Optimization::
10314 * Passive Task Optimization::
10315
10316 @ifset vms
10317 * Coverage Analysis::
10318 @end ifset
10319 @end menu
10320
10321 @node Controlling Run-Time Checks
10322 @subsection Controlling Run-Time Checks
10323
10324 @noindent
10325 By default, GNAT generates all run-time checks, except integer overflow
10326 checks, stack overflow checks, and checks for access before elaboration on
10327 subprogram calls. The latter are not required in default mode, because all
10328 necessary checking is done at compile time.
10329 @cindex @option{-gnatp} (@command{gcc})
10330 @cindex @option{-gnato} (@command{gcc})
10331 Two gnat switches, @option{-gnatp} and @option{-gnato} allow this default to
10332 be modified. @xref{Run-Time Checks}.
10333
10334 Our experience is that the default is suitable for most development
10335 purposes.
10336
10337 We treat integer overflow specially because these
10338 are quite expensive and in our experience are not as important as other
10339 run-time checks in the development process. Note that division by zero
10340 is not considered an overflow check, and divide by zero checks are
10341 generated where required by default.
10342
10343 Elaboration checks are off by default, and also not needed by default, since
10344 GNAT uses a static elaboration analysis approach that avoids the need for
10345 run-time checking. This manual contains a full chapter discussing the issue
10346 of elaboration checks, and if the default is not satisfactory for your use,
10347 you should read this chapter.
10348
10349 For validity checks, the minimal checks required by the Ada Reference
10350 Manual (for case statements and assignments to array elements) are on
10351 by default. These can be suppressed by use of the @option{-gnatVn} switch.
10352 Note that in Ada 83, there were no validity checks, so if the Ada 83 mode
10353 is acceptable (or when comparing GNAT performance with an Ada 83 compiler),
10354 it may be reasonable to routinely use @option{-gnatVn}. Validity checks
10355 are also suppressed entirely if @option{-gnatp} is used.
10356
10357 @cindex Overflow checks
10358 @cindex Checks, overflow
10359 @findex Suppress
10360 @findex Unsuppress
10361 @cindex pragma Suppress
10362 @cindex pragma Unsuppress
10363 Note that the setting of the switches controls the default setting of
10364 the checks. They may be modified using either @code{pragma Suppress} (to
10365 remove checks) or @code{pragma Unsuppress} (to add back suppressed
10366 checks) in the program source.
10367
10368 @node Use of Restrictions
10369 @subsection Use of Restrictions
10370
10371 @noindent
10372 The use of pragma Restrictions allows you to control which features are
10373 permitted in your program. Apart from the obvious point that if you avoid
10374 relatively expensive features like finalization (enforceable by the use
10375 of pragma Restrictions (No_Finalization), the use of this pragma does not
10376 affect the generated code in most cases.
10377
10378 One notable exception to this rule is that the possibility of task abort
10379 results in some distributed overhead, particularly if finalization or
10380 exception handlers are used. The reason is that certain sections of code
10381 have to be marked as non-abortable.
10382
10383 If you use neither the @code{abort} statement, nor asynchronous transfer
10384 of control (@code{select @dots{} then abort}), then this distributed overhead
10385 is removed, which may have a general positive effect in improving
10386 overall performance. Especially code involving frequent use of tasking
10387 constructs and controlled types will show much improved performance.
10388 The relevant restrictions pragmas are
10389
10390 @smallexample @c ada
10391 pragma Restrictions (No_Abort_Statements);
10392 pragma Restrictions (Max_Asynchronous_Select_Nesting => 0);
10393 @end smallexample
10394
10395 @noindent
10396 It is recommended that these restriction pragmas be used if possible. Note
10397 that this also means that you can write code without worrying about the
10398 possibility of an immediate abort at any point.
10399
10400 @node Optimization Levels
10401 @subsection Optimization Levels
10402 @cindex @option{^-O^/OPTIMIZE^} (@command{gcc})
10403
10404 @noindent
10405 Without any optimization ^option,^qualifier,^
10406 the compiler's goal is to reduce the cost of
10407 compilation and to make debugging produce the expected results.
10408 Statements are independent: if you stop the program with a breakpoint between
10409 statements, you can then assign a new value to any variable or change
10410 the program counter to any other statement in the subprogram and get exactly
10411 the results you would expect from the source code.
10412
10413 Turning on optimization makes the compiler attempt to improve the
10414 performance and/or code size at the expense of compilation time and
10415 possibly the ability to debug the program.
10416
10417 If you use multiple
10418 ^-O options, with or without level numbers,^/OPTIMIZE qualifiers,^
10419 the last such option is the one that is effective.
10420
10421 @noindent
10422 The default is optimization off. This results in the fastest compile
10423 times, but GNAT makes absolutely no attempt to optimize, and the
10424 generated programs are considerably larger and slower than when
10425 optimization is enabled. You can use the
10426 @ifclear vms
10427 @option{-O} switch (the permitted forms are @option{-O0}, @option{-O1}
10428 @option{-O2}, @option{-O3}, and @option{-Os})
10429 @end ifclear
10430 @ifset vms
10431 @code{OPTIMIZE} qualifier
10432 @end ifset
10433 to @command{gcc} to control the optimization level:
10434
10435 @table @option
10436 @item ^-O0^/OPTIMIZE=NONE^
10437 No optimization (the default);
10438 generates unoptimized code but has
10439 the fastest compilation time.
10440
10441 Note that many other compilers do fairly extensive optimization
10442 even if ``no optimization'' is specified. With gcc, it is
10443 very unusual to use ^-O0^/OPTIMIZE=NONE^ for production if
10444 execution time is of any concern, since ^-O0^/OPTIMIZE=NONE^
10445 really does mean no optimization at all. This difference between
10446 gcc and other compilers should be kept in mind when doing
10447 performance comparisons.
10448
10449 @item ^-O1^/OPTIMIZE=SOME^
10450 Moderate optimization;
10451 optimizes reasonably well but does not
10452 degrade compilation time significantly.
10453
10454 @item ^-O2^/OPTIMIZE=ALL^
10455 @ifset vms
10456 @itemx /OPTIMIZE=DEVELOPMENT
10457 @end ifset
10458 Full optimization;
10459 generates highly optimized code and has
10460 the slowest compilation time.
10461
10462 @item ^-O3^/OPTIMIZE=INLINING^
10463 Full optimization as in @option{-O2};
10464 also uses more aggressive automatic inlining of subprograms within a unit
10465 (@pxref{Inlining of Subprograms}) and attempts to vectorize loops.
10466
10467 @item ^-Os^/OPTIMIZE=SPACE^
10468 Optimize space usage (code and data) of resulting program.
10469 @end table
10470
10471 @noindent
10472 Higher optimization levels perform more global transformations on the
10473 program and apply more expensive analysis algorithms in order to generate
10474 faster and more compact code. The price in compilation time, and the
10475 resulting improvement in execution time,
10476 both depend on the particular application and the hardware environment.
10477 You should experiment to find the best level for your application.
10478
10479 Since the precise set of optimizations done at each level will vary from
10480 release to release (and sometime from target to target), it is best to think
10481 of the optimization settings in general terms.
10482 @xref{Optimize Options,, Options That Control Optimization, gcc, Using
10483 the GNU Compiler Collection (GCC)}, for details about
10484 ^the @option{-O} settings and a number of @option{-f} options that^how to^
10485 individually enable or disable specific optimizations.
10486
10487 Unlike some other compilation systems, ^@command{gcc}^GNAT^ has
10488 been tested extensively at all optimization levels. There are some bugs
10489 which appear only with optimization turned on, but there have also been
10490 bugs which show up only in @emph{unoptimized} code. Selecting a lower
10491 level of optimization does not improve the reliability of the code
10492 generator, which in practice is highly reliable at all optimization
10493 levels.
10494
10495 Note regarding the use of @option{-O3}: The use of this optimization level
10496 is generally discouraged with GNAT, since it often results in larger
10497 executables which may run more slowly. See further discussion of this point
10498 in @ref{Inlining of Subprograms}.
10499
10500 @node Debugging Optimized Code
10501 @subsection Debugging Optimized Code
10502 @cindex Debugging optimized code
10503 @cindex Optimization and debugging
10504
10505 @noindent
10506 Although it is possible to do a reasonable amount of debugging at
10507 @ifclear vms
10508 nonzero optimization levels,
10509 the higher the level the more likely that
10510 @end ifclear
10511 @ifset vms
10512 @option{/OPTIMIZE} settings other than @code{NONE},
10513 such settings will make it more likely that
10514 @end ifset
10515 source-level constructs will have been eliminated by optimization.
10516 For example, if a loop is strength-reduced, the loop
10517 control variable may be completely eliminated and thus cannot be
10518 displayed in the debugger.
10519 This can only happen at @option{-O2} or @option{-O3}.
10520 Explicit temporary variables that you code might be eliminated at
10521 ^level^setting^ @option{-O1} or higher.
10522
10523 The use of the @option{^-g^/DEBUG^} switch,
10524 @cindex @option{^-g^/DEBUG^} (@command{gcc})
10525 which is needed for source-level debugging,
10526 affects the size of the program executable on disk,
10527 and indeed the debugging information can be quite large.
10528 However, it has no effect on the generated code (and thus does not
10529 degrade performance)
10530
10531 Since the compiler generates debugging tables for a compilation unit before
10532 it performs optimizations, the optimizing transformations may invalidate some
10533 of the debugging data. You therefore need to anticipate certain
10534 anomalous situations that may arise while debugging optimized code.
10535 These are the most common cases:
10536
10537 @enumerate
10538 @item
10539 @i{The ``hopping Program Counter'':} Repeated @code{step} or @code{next}
10540 commands show
10541 the PC bouncing back and forth in the code. This may result from any of
10542 the following optimizations:
10543
10544 @itemize @bullet
10545 @item
10546 @i{Common subexpression elimination:} using a single instance of code for a
10547 quantity that the source computes several times. As a result you
10548 may not be able to stop on what looks like a statement.
10549
10550 @item
10551 @i{Invariant code motion:} moving an expression that does not change within a
10552 loop, to the beginning of the loop.
10553
10554 @item
10555 @i{Instruction scheduling:} moving instructions so as to
10556 overlap loads and stores (typically) with other code, or in
10557 general to move computations of values closer to their uses. Often
10558 this causes you to pass an assignment statement without the assignment
10559 happening and then later bounce back to the statement when the
10560 value is actually needed. Placing a breakpoint on a line of code
10561 and then stepping over it may, therefore, not always cause all the
10562 expected side-effects.
10563 @end itemize
10564
10565 @item
10566 @i{The ``big leap'':} More commonly known as @emph{cross-jumping}, in which
10567 two identical pieces of code are merged and the program counter suddenly
10568 jumps to a statement that is not supposed to be executed, simply because
10569 it (and the code following) translates to the same thing as the code
10570 that @emph{was} supposed to be executed. This effect is typically seen in
10571 sequences that end in a jump, such as a @code{goto}, a @code{return}, or
10572 a @code{break} in a C @code{^switch^switch^} statement.
10573
10574 @item
10575 @i{The ``roving variable'':} The symptom is an unexpected value in a variable.
10576 There are various reasons for this effect:
10577
10578 @itemize @bullet
10579 @item
10580 In a subprogram prologue, a parameter may not yet have been moved to its
10581 ``home''.
10582
10583 @item
10584 A variable may be dead, and its register re-used. This is
10585 probably the most common cause.
10586
10587 @item
10588 As mentioned above, the assignment of a value to a variable may
10589 have been moved.
10590
10591 @item
10592 A variable may be eliminated entirely by value propagation or
10593 other means. In this case, GCC may incorrectly generate debugging
10594 information for the variable
10595 @end itemize
10596
10597 @noindent
10598 In general, when an unexpected value appears for a local variable or parameter
10599 you should first ascertain if that value was actually computed by
10600 your program, as opposed to being incorrectly reported by the debugger.
10601 Record fields or
10602 array elements in an object designated by an access value
10603 are generally less of a problem, once you have ascertained that the access
10604 value is sensible.
10605 Typically, this means checking variables in the preceding code and in the
10606 calling subprogram to verify that the value observed is explainable from other
10607 values (one must apply the procedure recursively to those
10608 other values); or re-running the code and stopping a little earlier
10609 (perhaps before the call) and stepping to better see how the variable obtained
10610 the value in question; or continuing to step @emph{from} the point of the
10611 strange value to see if code motion had simply moved the variable's
10612 assignments later.
10613 @end enumerate
10614
10615 @noindent
10616 In light of such anomalies, a recommended technique is to use @option{-O0}
10617 early in the software development cycle, when extensive debugging capabilities
10618 are most needed, and then move to @option{-O1} and later @option{-O2} as
10619 the debugger becomes less critical.
10620 Whether to use the @option{^-g^/DEBUG^} switch in the release version is
10621 a release management issue.
10622 @ifclear vms
10623 Note that if you use @option{-g} you can then use the @command{strip} program
10624 on the resulting executable,
10625 which removes both debugging information and global symbols.
10626 @end ifclear
10627
10628 @node Inlining of Subprograms
10629 @subsection Inlining of Subprograms
10630
10631 @noindent
10632 A call to a subprogram in the current unit is inlined if all the
10633 following conditions are met:
10634
10635 @itemize @bullet
10636 @item
10637 The optimization level is at least @option{-O1}.
10638
10639 @item
10640 The called subprogram is suitable for inlining: It must be small enough
10641 and not contain something that @command{gcc} cannot support in inlined
10642 subprograms.
10643
10644 @item
10645 @cindex pragma Inline
10646 @findex Inline
10647 Any one of the following applies: @code{pragma Inline} is applied to the
10648 subprogram and the @option{^-gnatn^/INLINE^} switch is specified; the
10649 subprogram is local to the unit and called once from within it; the
10650 subprogram is small and optimization level @option{-O2} is specified;
10651 optimization level @option{-O3} is specified.
10652 @end itemize
10653
10654 @noindent
10655 Calls to subprograms in @code{with}'ed units are normally not inlined.
10656 To achieve actual inlining (that is, replacement of the call by the code
10657 in the body of the subprogram), the following conditions must all be true:
10658
10659 @itemize @bullet
10660 @item
10661 The optimization level is at least @option{-O1}.
10662
10663 @item
10664 The called subprogram is suitable for inlining: It must be small enough
10665 and not contain something that @command{gcc} cannot support in inlined
10666 subprograms.
10667
10668 @item
10669 The call appears in a body (not in a package spec).
10670
10671 @item
10672 There is a @code{pragma Inline} for the subprogram.
10673
10674 @item
10675 The @option{^-gnatn^/INLINE^} switch is used on the command line.
10676 @end itemize
10677
10678 Even if all these conditions are met, it may not be possible for
10679 the compiler to inline the call, due to the length of the body,
10680 or features in the body that make it impossible for the compiler
10681 to do the inlining.
10682
10683 Note that specifying the @option{-gnatn} switch causes additional
10684 compilation dependencies. Consider the following:
10685
10686 @smallexample @c ada
10687 @cartouche
10688 package R is
10689 procedure Q;
10690 pragma Inline (Q);
10691 end R;
10692 package body R is
10693 @dots{}
10694 end R;
10695
10696 with R;
10697 procedure Main is
10698 begin
10699 @dots{}
10700 R.Q;
10701 end Main;
10702 @end cartouche
10703 @end smallexample
10704
10705 @noindent
10706 With the default behavior (no @option{-gnatn} switch specified), the
10707 compilation of the @code{Main} procedure depends only on its own source,
10708 @file{main.adb}, and the spec of the package in file @file{r.ads}. This
10709 means that editing the body of @code{R} does not require recompiling
10710 @code{Main}.
10711
10712 On the other hand, the call @code{R.Q} is not inlined under these
10713 circumstances. If the @option{-gnatn} switch is present when @code{Main}
10714 is compiled, the call will be inlined if the body of @code{Q} is small
10715 enough, but now @code{Main} depends on the body of @code{R} in
10716 @file{r.adb} as well as on the spec. This means that if this body is edited,
10717 the main program must be recompiled. Note that this extra dependency
10718 occurs whether or not the call is in fact inlined by @command{gcc}.
10719
10720 The use of front end inlining with @option{-gnatN} generates similar
10721 additional dependencies.
10722
10723 @cindex @option{^-fno-inline^/INLINE=SUPPRESS^} (@command{gcc})
10724 Note: The @option{^-fno-inline^/INLINE=SUPPRESS^} switch
10725 can be used to prevent
10726 all inlining. This switch overrides all other conditions and ensures
10727 that no inlining occurs. The extra dependences resulting from
10728 @option{-gnatn} will still be active, even if
10729 this switch is used to suppress the resulting inlining actions.
10730
10731 @cindex @option{-fno-inline-functions} (@command{gcc})
10732 Note: The @option{-fno-inline-functions} switch can be used to prevent
10733 automatic inlining of subprograms if @option{-O3} is used.
10734
10735 @cindex @option{-fno-inline-small-functions} (@command{gcc})
10736 Note: The @option{-fno-inline-small-functions} switch can be used to prevent
10737 automatic inlining of small subprograms if @option{-O2} is used.
10738
10739 @cindex @option{-fno-inline-functions-called-once} (@command{gcc})
10740 Note: The @option{-fno-inline-functions-called-once} switch
10741 can be used to prevent inlining of subprograms local to the unit
10742 and called once from within it if @option{-O1} is used.
10743
10744 Note regarding the use of @option{-O3}: @option{-gnatn} is made up of two
10745 sub-switches @option{-gnatn1} and @option{-gnatn2} that can be directly
10746 specified in lieu of it, @option{-gnatn} being translated into one of them
10747 based on the optimization level. With @option{-O2} or below, @option{-gnatn}
10748 is equivalent to @option{-gnatn1} which activates pragma @code{Inline} with
10749 moderate inlining across modules. With @option{-O3}, @option{-gnatn} is
10750 equivalent to @option{-gnatn2} which activates pragma @code{Inline} with
10751 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
10752 effect of inlining subprograms you did not think should be inlined. We have
10753 found that the use of @option{-O3} may slow down the compilation and increase
10754 the code size by performing excessive inlining, leading to increased
10755 instruction cache pressure from the increased code size and thus minor
10756 performance improvements. So the bottom line here is that you should not
10757 automatically assume that @option{-O3} is better than @option{-O2}, and
10758 indeed you should use @option{-O3} only if tests show that it actually
10759 improves performance for your program.
10760
10761 @node Vectorization of loops
10762 @subsection Vectorization of loops
10763 @cindex Optimization Switches
10764
10765 You can take advantage of the auto-vectorizer present in the @command{gcc}
10766 back end to vectorize loops with GNAT. The corresponding command line switch
10767 is @option{-ftree-vectorize} but, as it is enabled by default at @option{-O3}
10768 and other aggressive optimizations helpful for vectorization also are enabled
10769 by default at this level, using @option{-O3} directly is recommended.
10770
10771 You also need to make sure that the target architecture features a supported
10772 SIMD instruction set. For example, for the x86 architecture, you should at
10773 least specify @option{-msse2} to get significant vectorization (but you don't
10774 need to specify it for x86-64 as it is part of the base 64-bit architecture).
10775 Similarly, for the PowerPC architecture, you should specify @option{-maltivec}.
10776
10777 The preferred loop form for vectorization is the @code{for} iteration scheme.
10778 Loops with a @code{while} iteration scheme can also be vectorized if they are
10779 very simple, but the vectorizer will quickly give up otherwise. With either
10780 iteration scheme, the flow of control must be straight, in particular no
10781 @code{exit} statement may appear in the loop body. The loop may however
10782 contain a single nested loop, if it can be vectorized when considered alone:
10783
10784 @smallexample @c ada
10785 @cartouche
10786 A : array (1..4, 1..4) of Long_Float;
10787 S : array (1..4) of Long_Float;
10788
10789 procedure Sum is
10790 begin
10791 for I in A'Range(1) loop
10792 for J in A'Range(2) loop
10793 S (I) := S (I) + A (I, J);
10794 end loop;
10795 end loop;
10796 end Sum;
10797 @end cartouche
10798 @end smallexample
10799
10800 The vectorizable operations depend on the targeted SIMD instruction set, but
10801 the adding and some of the multiplying operators are generally supported, as
10802 well as the logical operators for modular types. Note that, in the former
10803 case, enabling overflow checks, for example with @option{-gnato}, totally
10804 disables vectorization. The other checks are not supposed to have the same
10805 definitive effect, although compiling with @option{-gnatp} might well reveal
10806 cases where some checks do thwart vectorization.
10807
10808 Type conversions may also prevent vectorization if they involve semantics that
10809 are not directly supported by the code generator or the SIMD instruction set.
10810 A typical example is direct conversion from floating-point to integer types.
10811 The solution in this case is to use the following idiom:
10812
10813 @smallexample @c ada
10814 Integer (S'Truncation (F))
10815 @end smallexample
10816
10817 @noindent
10818 if @code{S} is the subtype of floating-point object @code{F}.
10819
10820 In most cases, the vectorizable loops are loops that iterate over arrays.
10821 All kinds of array types are supported, i.e. constrained array types with
10822 static bounds:
10823
10824 @smallexample @c ada
10825 type Array_Type is array (1 .. 4) of Long_Float;
10826 @end smallexample
10827
10828 @noindent
10829 constrained array types with dynamic bounds:
10830
10831 @smallexample @c ada
10832 type Array_Type is array (1 .. Q.N) of Long_Float;
10833
10834 type Array_Type is array (Q.K .. 4) of Long_Float;
10835
10836 type Array_Type is array (Q.K .. Q.N) of Long_Float;
10837 @end smallexample
10838
10839 @noindent
10840 or unconstrained array types:
10841
10842 @smallexample @c ada
10843 type Array_Type is array (Positive range <>) of Long_Float;
10844 @end smallexample
10845
10846 @noindent
10847 The quality of the generated code decreases when the dynamic aspect of the
10848 array type increases, the worst code being generated for unconstrained array
10849 types. This is so because, the less information the compiler has about the
10850 bounds of the array, the more fallback code it needs to generate in order to
10851 fix things up at run time.
10852
10853 It is possible to specify that a given loop should be subject to vectorization
10854 preferably to other optimizations by means of pragma @code{Loop_Optimize}:
10855
10856 @smallexample @c ada
10857 pragma Loop_Optimize (Vector);
10858 @end smallexample
10859
10860 @noindent
10861 placed immediately within the loop will convey the appropriate hint to the
10862 compiler for this loop.
10863
10864 It is also possible to help the compiler generate better vectorized code
10865 for a given loop by asserting that there are no loop-carried dependencies
10866 in the loop. Consider for example the procedure:
10867
10868 @smallexample @c ada
10869 type Arr is array (1 .. 4) of Long_Float;
10870
10871 procedure Add (X, Y : not null access Arr; R : not null access Arr) is
10872 begin
10873 for I in Arr'Range loop
10874 R(I) := X(I) + Y(I);
10875 end loop;
10876 end;
10877 @end smallexample
10878
10879 @noindent
10880 By default, the compiler cannot unconditionally vectorize the loop because
10881 assigning to a component of the array designated by R in one iteration could
10882 change the value read from the components of the arrays designated by X or Y
10883 in a later iteration. As a result, the compiler will generate two versions
10884 of the loop in the object code, one vectorized and the other not vectorized,
10885 as well as a test to select the appropriate version at run time. This can
10886 be overcome by another hint:
10887
10888 @smallexample @c ada
10889 pragma Loop_Optimize (Ivdep);
10890 @end smallexample
10891
10892 @noindent
10893 placed immediately within the loop will tell the compiler that it can safely
10894 omit the non-vectorized version of the loop as well as the run-time test.
10895
10896 @node Other Optimization Switches
10897 @subsection Other Optimization Switches
10898 @cindex Optimization Switches
10899
10900 Since @code{GNAT} uses the @command{gcc} back end, all the specialized
10901 @command{gcc} optimization switches are potentially usable. These switches
10902 have not been extensively tested with GNAT but can generally be expected
10903 to work. Examples of switches in this category are @option{-funroll-loops}
10904 and the various target-specific @option{-m} options (in particular, it has
10905 been observed that @option{-march=xxx} can significantly improve performance
10906 on appropriate machines). For full details of these switches, see
10907 @ref{Submodel Options,, Hardware Models and Configurations, gcc, Using
10908 the GNU Compiler Collection (GCC)}.
10909
10910 @node Optimization and Strict Aliasing
10911 @subsection Optimization and Strict Aliasing
10912 @cindex Aliasing
10913 @cindex Strict Aliasing
10914 @cindex No_Strict_Aliasing
10915
10916 @noindent
10917 The strong typing capabilities of Ada allow an optimizer to generate
10918 efficient code in situations where other languages would be forced to
10919 make worst case assumptions preventing such optimizations. Consider
10920 the following example:
10921
10922 @smallexample @c ada
10923 @cartouche
10924 procedure R is
10925 type Int1 is new Integer;
10926 type Int2 is new Integer;
10927 type Int1A is access Int1;
10928 type Int2A is access Int2;
10929 Int1V : Int1A;
10930 Int2V : Int2A;
10931 @dots{}
10932
10933 begin
10934 @dots{}
10935 for J in Data'Range loop
10936 if Data (J) = Int1V.all then
10937 Int2V.all := Int2V.all + 1;
10938 end if;
10939 end loop;
10940 @dots{}
10941 end R;
10942 @end cartouche
10943 @end smallexample
10944
10945 @noindent
10946 In this example, since the variable @code{Int1V} can only access objects
10947 of type @code{Int1}, and @code{Int2V} can only access objects of type
10948 @code{Int2}, there is no possibility that the assignment to
10949 @code{Int2V.all} affects the value of @code{Int1V.all}. This means that
10950 the compiler optimizer can "know" that the value @code{Int1V.all} is constant
10951 for all iterations of the loop and avoid the extra memory reference
10952 required to dereference it each time through the loop.
10953
10954 This kind of optimization, called strict aliasing analysis, is
10955 triggered by specifying an optimization level of @option{-O2} or
10956 higher or @option{-Os} and allows @code{GNAT} to generate more efficient code
10957 when access values are involved.
10958
10959 However, although this optimization is always correct in terms of
10960 the formal semantics of the Ada Reference Manual, difficulties can
10961 arise if features like @code{Unchecked_Conversion} are used to break
10962 the typing system. Consider the following complete program example:
10963
10964 @smallexample @c ada
10965 @cartouche
10966 package p1 is
10967 type int1 is new integer;
10968 type int2 is new integer;
10969 type a1 is access int1;
10970 type a2 is access int2;
10971 end p1;
10972
10973 with p1; use p1;
10974 package p2 is
10975 function to_a2 (Input : a1) return a2;
10976 end p2;
10977
10978 with Unchecked_Conversion;
10979 package body p2 is
10980 function to_a2 (Input : a1) return a2 is
10981 function to_a2u is
10982 new Unchecked_Conversion (a1, a2);
10983 begin
10984 return to_a2u (Input);
10985 end to_a2;
10986 end p2;
10987
10988 with p2; use p2;
10989 with p1; use p1;
10990 with Text_IO; use Text_IO;
10991 procedure m is
10992 v1 : a1 := new int1;
10993 v2 : a2 := to_a2 (v1);
10994 begin
10995 v1.all := 1;
10996 v2.all := 0;
10997 put_line (int1'image (v1.all));
10998 end;
10999 @end cartouche
11000 @end smallexample
11001
11002 @noindent
11003 This program prints out 0 in @option{-O0} or @option{-O1}
11004 mode, but it prints out 1 in @option{-O2} mode. That's
11005 because in strict aliasing mode, the compiler can and
11006 does assume that the assignment to @code{v2.all} could not
11007 affect the value of @code{v1.all}, since different types
11008 are involved.
11009
11010 This behavior is not a case of non-conformance with the standard, since
11011 the Ada RM specifies that an unchecked conversion where the resulting
11012 bit pattern is not a correct value of the target type can result in an
11013 abnormal value and attempting to reference an abnormal value makes the
11014 execution of a program erroneous. That's the case here since the result
11015 does not point to an object of type @code{int2}. This means that the
11016 effect is entirely unpredictable.
11017
11018 However, although that explanation may satisfy a language
11019 lawyer, in practice an applications programmer expects an
11020 unchecked conversion involving pointers to create true
11021 aliases and the behavior of printing 1 seems plain wrong.
11022 In this case, the strict aliasing optimization is unwelcome.
11023
11024 Indeed the compiler recognizes this possibility, and the
11025 unchecked conversion generates a warning:
11026
11027 @smallexample
11028 p2.adb:5:07: warning: possible aliasing problem with type "a2"
11029 p2.adb:5:07: warning: use -fno-strict-aliasing switch for references
11030 p2.adb:5:07: warning: or use "pragma No_Strict_Aliasing (a2);"
11031 @end smallexample
11032
11033 @noindent
11034 Unfortunately the problem is recognized when compiling the body of
11035 package @code{p2}, but the actual "bad" code is generated while
11036 compiling the body of @code{m} and this latter compilation does not see
11037 the suspicious @code{Unchecked_Conversion}.
11038
11039 As implied by the warning message, there are approaches you can use to
11040 avoid the unwanted strict aliasing optimization in a case like this.
11041
11042 One possibility is to simply avoid the use of @option{-O2}, but
11043 that is a bit drastic, since it throws away a number of useful
11044 optimizations that do not involve strict aliasing assumptions.
11045
11046 A less drastic approach is to compile the program using the
11047 option @option{-fno-strict-aliasing}. Actually it is only the
11048 unit containing the dereferencing of the suspicious pointer
11049 that needs to be compiled. So in this case, if we compile
11050 unit @code{m} with this switch, then we get the expected
11051 value of zero printed. Analyzing which units might need
11052 the switch can be painful, so a more reasonable approach
11053 is to compile the entire program with options @option{-O2}
11054 and @option{-fno-strict-aliasing}. If the performance is
11055 satisfactory with this combination of options, then the
11056 advantage is that the entire issue of possible "wrong"
11057 optimization due to strict aliasing is avoided.
11058
11059 To avoid the use of compiler switches, the configuration
11060 pragma @code{No_Strict_Aliasing} with no parameters may be
11061 used to specify that for all access types, the strict
11062 aliasing optimization should be suppressed.
11063
11064 However, these approaches are still overkill, in that they causes
11065 all manipulations of all access values to be deoptimized. A more
11066 refined approach is to concentrate attention on the specific
11067 access type identified as problematic.
11068
11069 First, if a careful analysis of uses of the pointer shows
11070 that there are no possible problematic references, then
11071 the warning can be suppressed by bracketing the
11072 instantiation of @code{Unchecked_Conversion} to turn
11073 the warning off:
11074
11075 @smallexample @c ada
11076 pragma Warnings (Off);
11077 function to_a2u is
11078 new Unchecked_Conversion (a1, a2);
11079 pragma Warnings (On);
11080 @end smallexample
11081
11082 @noindent
11083 Of course that approach is not appropriate for this particular
11084 example, since indeed there is a problematic reference. In this
11085 case we can take one of two other approaches.
11086
11087 The first possibility is to move the instantiation of unchecked
11088 conversion to the unit in which the type is declared. In
11089 this example, we would move the instantiation of
11090 @code{Unchecked_Conversion} from the body of package
11091 @code{p2} to the spec of package @code{p1}. Now the
11092 warning disappears. That's because any use of the
11093 access type knows there is a suspicious unchecked
11094 conversion, and the strict aliasing optimization
11095 is automatically suppressed for the type.
11096
11097 If it is not practical to move the unchecked conversion to the same unit
11098 in which the destination access type is declared (perhaps because the
11099 source type is not visible in that unit), you may use pragma
11100 @code{No_Strict_Aliasing} for the type. This pragma must occur in the
11101 same declarative sequence as the declaration of the access type:
11102
11103 @smallexample @c ada
11104 type a2 is access int2;
11105 pragma No_Strict_Aliasing (a2);
11106 @end smallexample
11107
11108 @noindent
11109 Here again, the compiler now knows that the strict aliasing optimization
11110 should be suppressed for any reference to type @code{a2} and the
11111 expected behavior is obtained.
11112
11113 Finally, note that although the compiler can generate warnings for
11114 simple cases of unchecked conversions, there are tricker and more
11115 indirect ways of creating type incorrect aliases which the compiler
11116 cannot detect. Examples are the use of address overlays and unchecked
11117 conversions involving composite types containing access types as
11118 components. In such cases, no warnings are generated, but there can
11119 still be aliasing problems. One safe coding practice is to forbid the
11120 use of address clauses for type overlaying, and to allow unchecked
11121 conversion only for primitive types. This is not really a significant
11122 restriction since any possible desired effect can be achieved by
11123 unchecked conversion of access values.
11124
11125 The aliasing analysis done in strict aliasing mode can certainly
11126 have significant benefits. We have seen cases of large scale
11127 application code where the time is increased by up to 5% by turning
11128 this optimization off. If you have code that includes significant
11129 usage of unchecked conversion, you might want to just stick with
11130 @option{-O1} and avoid the entire issue. If you get adequate
11131 performance at this level of optimization level, that's probably
11132 the safest approach. If tests show that you really need higher
11133 levels of optimization, then you can experiment with @option{-O2}
11134 and @option{-O2 -fno-strict-aliasing} to see how much effect this
11135 has on size and speed of the code. If you really need to use
11136 @option{-O2} with strict aliasing in effect, then you should
11137 review any uses of unchecked conversion of access types,
11138 particularly if you are getting the warnings described above.
11139
11140 @node Aliased Variables and Optimization
11141 @subsection Aliased Variables and Optimization
11142 @cindex Aliasing
11143 There are scenarios in which programs may
11144 use low level techniques to modify variables
11145 that otherwise might be considered to be unassigned. For example,
11146 a variable can be passed to a procedure by reference, which takes
11147 the address of the parameter and uses the address to modify the
11148 variable's value, even though it is passed as an IN parameter.
11149 Consider the following example:
11150
11151 @smallexample @c ada
11152 procedure P is
11153 Max_Length : constant Natural := 16;
11154 type Char_Ptr is access all Character;
11155
11156 procedure Get_String(Buffer: Char_Ptr; Size : Integer);
11157 pragma Import (C, Get_String, "get_string");
11158
11159 Name : aliased String (1 .. Max_Length) := (others => ' ');
11160 Temp : Char_Ptr;
11161
11162 function Addr (S : String) return Char_Ptr is
11163 function To_Char_Ptr is
11164 new Ada.Unchecked_Conversion (System.Address, Char_Ptr);
11165 begin
11166 return To_Char_Ptr (S (S'First)'Address);
11167 end;
11168
11169 begin
11170 Temp := Addr (Name);
11171 Get_String (Temp, Max_Length);
11172 end;
11173 @end smallexample
11174
11175 @noindent
11176 where Get_String is a C function that uses the address in Temp to
11177 modify the variable @code{Name}. This code is dubious, and arguably
11178 erroneous, and the compiler would be entitled to assume that
11179 @code{Name} is never modified, and generate code accordingly.
11180
11181 However, in practice, this would cause some existing code that
11182 seems to work with no optimization to start failing at high
11183 levels of optimzization.
11184
11185 What the compiler does for such cases is to assume that marking
11186 a variable as aliased indicates that some "funny business" may
11187 be going on. The optimizer recognizes the aliased keyword and
11188 inhibits optimizations that assume the value cannot be assigned.
11189 This means that the above example will in fact "work" reliably,
11190 that is, it will produce the expected results.
11191
11192 @node Atomic Variables and Optimization
11193 @subsection Atomic Variables and Optimization
11194 @cindex Atomic
11195 There are two considerations with regard to performance when
11196 atomic variables are used.
11197
11198 First, the RM only guarantees that access to atomic variables
11199 be atomic, it has nothing to say about how this is achieved,
11200 though there is a strong implication that this should not be
11201 achieved by explicit locking code. Indeed GNAT will never
11202 generate any locking code for atomic variable access (it will
11203 simply reject any attempt to make a variable or type atomic
11204 if the atomic access cannot be achieved without such locking code).
11205
11206 That being said, it is important to understand that you cannot
11207 assume that the entire variable will always be accessed. Consider
11208 this example:
11209
11210 @smallexample @c ada
11211 type R is record
11212 A,B,C,D : Character;
11213 end record;
11214 for R'Size use 32;
11215 for R'Alignment use 4;
11216
11217 RV : R;
11218 pragma Atomic (RV);
11219 X : Character;
11220 ...
11221 X := RV.B;
11222 @end smallexample
11223
11224 @noindent
11225 You cannot assume that the reference to @code{RV.B}
11226 will read the entire 32-bit
11227 variable with a single load instruction. It is perfectly legitimate if
11228 the hardware allows it to do a byte read of just the B field. This read
11229 is still atomic, which is all the RM requires. GNAT can and does take
11230 advantage of this, depending on the architecture and optimization level.
11231 Any assumption to the contrary is non-portable and risky. Even if you
11232 examine the assembly language and see a full 32-bit load, this might
11233 change in a future version of the compiler.
11234
11235 If your application requires that all accesses to @code{RV} in this
11236 example be full 32-bit loads, you need to make a copy for the access
11237 as in:
11238
11239 @smallexample @c ada
11240 declare
11241 RV_Copy : constant R := RV;
11242 begin
11243 X := RV_Copy.B;
11244 end;
11245 @end smallexample
11246
11247
11248 @noindent
11249 Now the reference to RV must read the whole variable.
11250 Actually one can imagine some compiler which figures
11251 out that the whole copy is not required (because only
11252 the B field is actually accessed), but GNAT
11253 certainly won't do that, and we don't know of any
11254 compiler that would not handle this right, and the
11255 above code will in practice work portably across
11256 all architectures (that permit the Atomic declaration).
11257
11258 The second issue with atomic variables has to do with
11259 the possible requirement of generating synchronization
11260 code. For more details on this, consult the sections on
11261 the pragmas Enable/Disable_Atomic_Synchronization in the
11262 GNAT Reference Manual. If performance is critical, and
11263 such synchronization code is not required, it may be
11264 useful to disable it.
11265
11266 @node Passive Task Optimization
11267 @subsection Passive Task Optimization
11268 @cindex Passive Task
11269
11270 A passive task is one which is sufficiently simple that
11271 in theory a compiler could recognize it an implement it
11272 efficiently without creating a new thread. The original design
11273 of Ada 83 had in mind this kind of passive task optimization, but
11274 only a few Ada 83 compilers attempted it. The problem was that
11275 it was difficult to determine the exact conditions under which
11276 the optimization was possible. The result is a very fragile
11277 optimization where a very minor change in the program can
11278 suddenly silently make a task non-optimizable.
11279
11280 With the revisiting of this issue in Ada 95, there was general
11281 agreement that this approach was fundamentally flawed, and the
11282 notion of protected types was introduced. When using protected
11283 types, the restrictions are well defined, and you KNOW that the
11284 operations will be optimized, and furthermore this optimized
11285 performance is fully portable.
11286
11287 Although it would theoretically be possible for GNAT to attempt to
11288 do this optimization, but it really doesn't make sense in the
11289 context of Ada 95, and none of the Ada 95 compilers implement
11290 this optimization as far as we know. In particular GNAT never
11291 attempts to perform this optimization.
11292
11293 In any new Ada 95 code that is written, you should always
11294 use protected types in place of tasks that might be able to
11295 be optimized in this manner.
11296 Of course this does not help if you have legacy Ada 83 code
11297 that depends on this optimization, but it is unusual to encounter
11298 a case where the performance gains from this optimization
11299 are significant.
11300
11301 Your program should work correctly without this optimization. If
11302 you have performance problems, then the most practical
11303 approach is to figure out exactly where these performance problems
11304 arise, and update those particular tasks to be protected types. Note
11305 that typically clients of the tasks who call entries, will not have
11306 to be modified, only the task definition itself.
11307
11308 @ifset vms
11309 @node Coverage Analysis
11310 @subsection Coverage Analysis
11311
11312 @noindent
11313 GNAT supports the HP Performance Coverage Analyzer (PCA), which allows
11314 the user to determine the distribution of execution time across a program,
11315 @pxref{Profiling} for details of usage.
11316 @end ifset
11317
11318
11319 @node Text_IO Suggestions
11320 @section @code{Text_IO} Suggestions
11321 @cindex @code{Text_IO} and performance
11322
11323 @noindent
11324 The @code{Ada.Text_IO} package has fairly high overheads due in part to
11325 the requirement of maintaining page and line counts. If performance
11326 is critical, a recommendation is to use @code{Stream_IO} instead of
11327 @code{Text_IO} for volume output, since this package has less overhead.
11328
11329 If @code{Text_IO} must be used, note that by default output to the standard
11330 output and standard error files is unbuffered (this provides better
11331 behavior when output statements are used for debugging, or if the
11332 progress of a program is observed by tracking the output, e.g. by
11333 using the Unix @command{tail -f} command to watch redirected output.
11334
11335 If you are generating large volumes of output with @code{Text_IO} and
11336 performance is an important factor, use a designated file instead
11337 of the standard output file, or change the standard output file to
11338 be buffered using @code{Interfaces.C_Streams.setvbuf}.
11339
11340
11341 @ifclear FSFEDITION
11342 @node Reducing Size of Ada Executables with gnatelim
11343 @section Reducing Size of Ada Executables with @code{gnatelim}
11344 @findex gnatelim
11345
11346 @noindent
11347 This section describes @command{gnatelim}, a tool which detects unused
11348 subprograms and helps the compiler to create a smaller executable for your
11349 program.
11350
11351 @menu
11352 * About gnatelim::
11353 * Running gnatelim::
11354 * Processing Precompiled Libraries::
11355 * Correcting the List of Eliminate Pragmas::
11356 * Making Your Executables Smaller::
11357 * Summary of the gnatelim Usage Cycle::
11358 @end menu
11359
11360 @node About gnatelim
11361 @subsection About @code{gnatelim}
11362
11363 @noindent
11364 When a program shares a set of Ada
11365 packages with other programs, it may happen that this program uses
11366 only a fraction of the subprograms defined in these packages. The code
11367 created for these unused subprograms increases the size of the executable.
11368
11369 @code{gnatelim} tracks unused subprograms in an Ada program and
11370 outputs a list of GNAT-specific pragmas @code{Eliminate} marking all the
11371 subprograms that are declared but never called. By placing the list of
11372 @code{Eliminate} pragmas in the GNAT configuration file @file{gnat.adc} and
11373 recompiling your program, you may decrease the size of its executable,
11374 because the compiler will not generate the code for 'eliminated' subprograms.
11375 @xref{Pragma Eliminate,,, gnat_rm, GNAT Reference Manual}, for more
11376 information about this pragma.
11377
11378 @code{gnatelim} needs as its input data the name of the main subprogram.
11379
11380 If a set of source files is specified as @code{gnatelim} arguments, it
11381 treats these files as a complete set of sources making up a program to
11382 analyse, and analyses only these sources.
11383
11384 After a full successful build of the main subprogram @code{gnatelim} can be
11385 called without specifying sources to analyse, in this case it computes
11386 the source closure of the main unit from the @file{ALI} files.
11387
11388 The following command will create the set of @file{ALI} files needed for
11389 @code{gnatelim}:
11390
11391 @smallexample
11392 $ gnatmake ^-c Main_Prog^/ACTIONS=COMPILE MAIN_PROG^
11393 @end smallexample
11394
11395 Note that @code{gnatelim} does not need object files.
11396
11397 @node Running gnatelim
11398 @subsection Running @code{gnatelim}
11399
11400 @noindent
11401 @code{gnatelim} has the following command-line interface:
11402
11403 @smallexample
11404 $ gnatelim [@var{switches}] ^-main^?MAIN^=@var{main_unit_name} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
11405 @end smallexample
11406
11407 @noindent
11408 @var{main_unit_name} should be a name of a source file that contains the main
11409 subprogram of a program (partition).
11410
11411 Each @var{filename} is the name (including the extension) of a source
11412 file to process. ``Wildcards'' are allowed, and
11413 the file name may contain path information.
11414
11415 @samp{@var{gcc_switches}} is a list of switches for
11416 @command{gcc}. They will be passed on to all compiler invocations made by
11417 @command{gnatelim} to generate the ASIS trees. Here you can provide
11418 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
11419 use the @option{-gnatec} switch to set the configuration file,
11420 use the @option{-gnat05} switch if sources should be compiled in
11421 Ada 2005 mode etc.
11422
11423 @code{gnatelim} has the following switches:
11424
11425 @table @option
11426 @c !sort!
11427 @item --version
11428 @cindex @option{--version} @command{gnatelim}
11429 Display Copyright and version, then exit disregarding all other options.
11430
11431 @item --help
11432 @cindex @option{--help} @command{gnatelim}
11433 Display usage, then exit disregarding all other options.
11434
11435 @item -P @var{file}
11436 @cindex @option{-P} @command{gnatelim}
11437 Indicates the name of the project file that describes the set of sources
11438 to be processed.
11439
11440 @item -X@var{name}=@var{value}
11441 @cindex @option{-X} @command{gnatelim}
11442 Indicates that external variable @var{name} in the argument project
11443 has the value @var{value}. Has no effect if no project is specified as
11444 tool argument.
11445
11446 @item ^-files^/FILES^=@var{filename}
11447 @cindex @option{^-files^/FILES^} (@code{gnatelim})
11448 Take the argument source files from the specified file. This file should be an
11449 ordinary text file containing file names separated by spaces or
11450 line breaks. You can use this switch more than once in the same call to
11451 @command{gnatelim}. You also can combine this switch with
11452 an explicit list of files.
11453
11454 @item ^-log^/LOG^
11455 @cindex @option{^-log^/LOG^} (@command{gnatelim})
11456 Duplicate all the output sent to @file{stderr} into a log file. The log file
11457 is named @file{gnatelim.log} and is located in the current directory.
11458
11459 @ignore
11460 @item ^-log^/LOGFILE^=@var{filename}
11461 @cindex @option{^-log^/LOGFILE^} (@command{gnatelim})
11462 Duplicate all the output sent to @file{stderr} into a specified log file.
11463 @end ignore
11464
11465 @cindex @option{^--no-elim-dispatch^/NO_DISPATCH^} (@command{gnatelim})
11466 @item ^--no-elim-dispatch^/NO_DISPATCH^
11467 Do not generate pragmas for dispatching operations.
11468
11469 @item ^--ignore^/IGNORE^=@var{filename}
11470 @cindex @option{^--ignore^/IGNORE^} (@command{gnatelim})
11471 Do not generate pragmas for subprograms declared in the sources
11472 listed in a specified file
11473
11474 @cindex @option{^-o^/OUTPUT^} (@command{gnatelim})
11475 @item ^-o^/OUTPUT^=@var{report_file}
11476 Put @command{gnatelim} output into a specified file. If this file already exists,
11477 it is overridden. If this switch is not used, @command{gnatelim} outputs its results
11478 into @file{stderr}
11479
11480 @item ^-j^/PROCESSES=^@var{n}
11481 @cindex @option{^-j^/PROCESSES^} (@command{gnatelim})
11482 Use @var{n} processes to carry out the tree creations (internal representations
11483 of the argument sources). On a multiprocessor machine this speeds up processing
11484 of big sets of argument sources. If @var{n} is 0, then the maximum number of
11485 parallel tree creations is the number of core processors on the platform.
11486
11487 @item ^-q^/QUIET^
11488 @cindex @option{^-q^/QUIET^} (@command{gnatelim})
11489 Quiet mode: by default @code{gnatelim} outputs to the standard error
11490 stream the number of program units left to be processed. This option turns
11491 this trace off.
11492
11493 @cindex @option{^-t^/TIME^} (@command{gnatelim})
11494 @item ^-t^/TIME^
11495 Print out execution time.
11496
11497 @item ^-v^/VERBOSE^
11498 @cindex @option{^-v^/VERBOSE^} (@command{gnatelim})
11499 Verbose mode: @code{gnatelim} version information is printed as Ada
11500 comments to the standard output stream. Also, in addition to the number of
11501 program units left @code{gnatelim} will output the name of the current unit
11502 being processed.
11503
11504 @item ^-wq^/WARNINGS=QUIET^
11505 @cindex @option{^-wq^/WARNINGS=QUIET^} (@command{gnatelim})
11506 Quiet warning mode - some warnings are suppressed. In particular warnings that
11507 indicate that the analysed set of sources is incomplete to make up a
11508 partition and that some subprogram bodies are missing are not generated.
11509 @end table
11510
11511 @noindent
11512 Note: to invoke @command{gnatelim} with a project file, use the @code{gnat}
11513 driver (see @ref{The GNAT Driver and Project Files}).
11514
11515 @node Processing Precompiled Libraries
11516 @subsection Processing Precompiled Libraries
11517
11518 @noindent
11519 If some program uses a precompiled Ada library, it can be processed by
11520 @code{gnatelim} in a usual way. @code{gnatelim} will newer generate an
11521 Eliminate pragma for a subprogram if the body of this subprogram has not
11522 been analysed, this is a typical case for subprograms from precompiled
11523 libraries. Switch @option{^-wq^/WARNINGS=QUIET^} may be used to suppress
11524 warnings about missing source files and non-analyzed subprogram bodies
11525 that can be generated when processing precompiled Ada libraries.
11526
11527 @node Correcting the List of Eliminate Pragmas
11528 @subsection Correcting the List of Eliminate Pragmas
11529
11530 @noindent
11531 In some rare cases @code{gnatelim} may try to eliminate
11532 subprograms that are actually called in the program. In this case, the
11533 compiler will generate an error message of the form:
11534
11535 @smallexample
11536 main.adb:4:08: cannot reference subprogram "P" eliminated at elim.out:5
11537 @end smallexample
11538
11539 @noindent
11540 You will need to manually remove the wrong @code{Eliminate} pragmas from
11541 the configuration file indicated in the error message. You should recompile
11542 your program from scratch after that, because you need a consistent
11543 configuration file(s) during the entire compilation.
11544
11545 @node Making Your Executables Smaller
11546 @subsection Making Your Executables Smaller
11547
11548 @noindent
11549 In order to get a smaller executable for your program you now have to
11550 recompile the program completely with the configuration file containing
11551 pragmas Eliminate generated by gnatelim. If these pragmas are placed in
11552 @file{gnat.adc} file located in your current directory, just do:
11553
11554 @smallexample
11555 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11556 @end smallexample
11557
11558 @noindent
11559 (Use the @option{^-f^/FORCE_COMPILE^} option for @command{gnatmake} to
11560 recompile everything
11561 with the set of pragmas @code{Eliminate} that you have obtained with
11562 @command{gnatelim}).
11563
11564 Be aware that the set of @code{Eliminate} pragmas is specific to each
11565 program. It is not recommended to merge sets of @code{Eliminate}
11566 pragmas created for different programs in one configuration file.
11567
11568 @node Summary of the gnatelim Usage Cycle
11569 @subsection Summary of the @code{gnatelim} Usage Cycle
11570
11571 @noindent
11572 Here is a quick summary of the steps to be taken in order to reduce
11573 the size of your executables with @code{gnatelim}. You may use
11574 other GNAT options to control the optimization level,
11575 to produce the debugging information, to set search path, etc.
11576
11577 @enumerate
11578 @item
11579 Create a complete set of @file{ALI} files (if the program has not been
11580 built already)
11581
11582 @smallexample
11583 $ gnatmake ^-c main_prog^/ACTIONS=COMPILE MAIN_PROG^
11584 @end smallexample
11585
11586 @item
11587 Generate a list of @code{Eliminate} pragmas in default configuration file
11588 @file{gnat.adc} in the current directory
11589 @smallexample
11590 @ifset vms
11591 $ PIPE GNAT ELIM MAIN_PROG > GNAT.ADC
11592 @end ifset
11593 @ifclear vms
11594 $ gnatelim main_prog >@r{[}>@r{]} gnat.adc
11595 @end ifclear
11596 @end smallexample
11597
11598 @item
11599 Recompile the application
11600
11601 @smallexample
11602 $ gnatmake ^-f main_prog^/FORCE_COMPILE MAIN_PROG^
11603 @end smallexample
11604
11605 @end enumerate
11606 @end ifclear
11607
11608 @node Reducing Size of Executables with unused subprogram/data elimination
11609 @section Reducing Size of Executables with Unused Subprogram/Data Elimination
11610 @findex unused subprogram/data elimination
11611
11612 @noindent
11613 This section describes how you can eliminate unused subprograms and data from
11614 your executable just by setting options at compilation time.
11615
11616 @menu
11617 * About unused subprogram/data elimination::
11618 * Compilation options::
11619 * Example of unused subprogram/data elimination::
11620 @end menu
11621
11622 @node About unused subprogram/data elimination
11623 @subsection About unused subprogram/data elimination
11624
11625 @noindent
11626 By default, an executable contains all code and data of its composing objects
11627 (directly linked or coming from statically linked libraries), even data or code
11628 never used by this executable.
11629
11630 This feature will allow you to eliminate such unused code from your
11631 executable, making it smaller (in disk and in memory).
11632
11633 This functionality is available on all Linux platforms except for the IA-64
11634 architecture and on all cross platforms using the ELF binary file format.
11635 In both cases GNU binutils version 2.16 or later are required to enable it.
11636
11637 @node Compilation options
11638 @subsection Compilation options
11639
11640 @noindent
11641 The operation of eliminating the unused code and data from the final executable
11642 is directly performed by the linker.
11643
11644 In order to do this, it has to work with objects compiled with the
11645 following options:
11646 @option{-ffunction-sections} @option{-fdata-sections}.
11647 @cindex @option{-ffunction-sections} (@command{gcc})
11648 @cindex @option{-fdata-sections} (@command{gcc})
11649 These options are usable with C and Ada files.
11650 They will place respectively each
11651 function or data in a separate section in the resulting object file.
11652
11653 Once the objects and static libraries are created with these options, the
11654 linker can perform the dead code elimination. You can do this by setting
11655 the @option{-Wl,--gc-sections} option to gcc command or in the
11656 @option{-largs} section of @command{gnatmake}. This will perform a
11657 garbage collection of code and data never referenced.
11658
11659 If the linker performs a partial link (@option{-r} linker option), then you
11660 will need to provide the entry point using the @option{-e} / @option{--entry}
11661 linker option.
11662
11663 Note that objects compiled without the @option{-ffunction-sections} and
11664 @option{-fdata-sections} options can still be linked with the executable.
11665 However, no dead code elimination will be performed on those objects (they will
11666 be linked as is).
11667
11668 The GNAT static library is now compiled with -ffunction-sections and
11669 -fdata-sections on some platforms. This allows you to eliminate the unused code
11670 and data of the GNAT library from your executable.
11671
11672 @node Example of unused subprogram/data elimination
11673 @subsection Example of unused subprogram/data elimination
11674
11675 @noindent
11676 Here is a simple example:
11677
11678 @smallexample @c ada
11679 with Aux;
11680
11681 procedure Test is
11682 begin
11683 Aux.Used (10);
11684 end Test;
11685
11686 package Aux is
11687 Used_Data : Integer;
11688 Unused_Data : Integer;
11689
11690 procedure Used (Data : Integer);
11691 procedure Unused (Data : Integer);
11692 end Aux;
11693
11694 package body Aux is
11695 procedure Used (Data : Integer) is
11696 begin
11697 Used_Data := Data;
11698 end Used;
11699
11700 procedure Unused (Data : Integer) is
11701 begin
11702 Unused_Data := Data;
11703 end Unused;
11704 end Aux;
11705 @end smallexample
11706
11707 @noindent
11708 @code{Unused} and @code{Unused_Data} are never referenced in this code
11709 excerpt, and hence they may be safely removed from the final executable.
11710
11711 @smallexample
11712 $ gnatmake test
11713
11714 $ nm test | grep used
11715 020015f0 T aux__unused
11716 02005d88 B aux__unused_data
11717 020015cc T aux__used
11718 02005d84 B aux__used_data
11719
11720 $ gnatmake test -cargs -fdata-sections -ffunction-sections \
11721 -largs -Wl,--gc-sections
11722
11723 $ nm test | grep used
11724 02005350 T aux__used
11725 0201ffe0 B aux__used_data
11726 @end smallexample
11727
11728 @noindent
11729 It can be observed that the procedure @code{Unused} and the object
11730 @code{Unused_Data} are removed by the linker when using the
11731 appropriate options.
11732
11733 @c ********************************
11734 @node Renaming Files with gnatchop
11735 @chapter Renaming Files with @code{gnatchop}
11736 @findex gnatchop
11737
11738 @noindent
11739 This chapter discusses how to handle files with multiple units by using
11740 the @code{gnatchop} utility. This utility is also useful in renaming
11741 files to meet the standard GNAT default file naming conventions.
11742
11743 @menu
11744 * Handling Files with Multiple Units::
11745 * Operating gnatchop in Compilation Mode::
11746 * Command Line for gnatchop::
11747 * Switches for gnatchop::
11748 * Examples of gnatchop Usage::
11749 @end menu
11750
11751 @node Handling Files with Multiple Units
11752 @section Handling Files with Multiple Units
11753
11754 @noindent
11755 The basic compilation model of GNAT requires that a file submitted to the
11756 compiler have only one unit and there be a strict correspondence
11757 between the file name and the unit name.
11758
11759 The @code{gnatchop} utility allows both of these rules to be relaxed,
11760 allowing GNAT to process files which contain multiple compilation units
11761 and files with arbitrary file names. @code{gnatchop}
11762 reads the specified file and generates one or more output files,
11763 containing one unit per file. The unit and the file name correspond,
11764 as required by GNAT.
11765
11766 If you want to permanently restructure a set of ``foreign'' files so that
11767 they match the GNAT rules, and do the remaining development using the
11768 GNAT structure, you can simply use @command{gnatchop} once, generate the
11769 new set of files and work with them from that point on.
11770
11771 Alternatively, if you want to keep your files in the ``foreign'' format,
11772 perhaps to maintain compatibility with some other Ada compilation
11773 system, you can set up a procedure where you use @command{gnatchop} each
11774 time you compile, regarding the source files that it writes as temporary
11775 files that you throw away.
11776
11777 Note that if your file containing multiple units starts with a byte order
11778 mark (BOM) specifying UTF-8 encoding, then the files generated by gnatchop
11779 will each start with a copy of this BOM, meaning that they can be compiled
11780 automatically in UTF-8 mode without needing to specify an explicit encoding.
11781
11782 @node Operating gnatchop in Compilation Mode
11783 @section Operating gnatchop in Compilation Mode
11784
11785 @noindent
11786 The basic function of @code{gnatchop} is to take a file with multiple units
11787 and split it into separate files. The boundary between files is reasonably
11788 clear, except for the issue of comments and pragmas. In default mode, the
11789 rule is that any pragmas between units belong to the previous unit, except
11790 that configuration pragmas always belong to the following unit. Any comments
11791 belong to the following unit. These rules
11792 almost always result in the right choice of
11793 the split point without needing to mark it explicitly and most users will
11794 find this default to be what they want. In this default mode it is incorrect to
11795 submit a file containing only configuration pragmas, or one that ends in
11796 configuration pragmas, to @code{gnatchop}.
11797
11798 However, using a special option to activate ``compilation mode'',
11799 @code{gnatchop}
11800 can perform another function, which is to provide exactly the semantics
11801 required by the RM for handling of configuration pragmas in a compilation.
11802 In the absence of configuration pragmas (at the main file level), this
11803 option has no effect, but it causes such configuration pragmas to be handled
11804 in a quite different manner.
11805
11806 First, in compilation mode, if @code{gnatchop} is given a file that consists of
11807 only configuration pragmas, then this file is appended to the
11808 @file{gnat.adc} file in the current directory. This behavior provides
11809 the required behavior described in the RM for the actions to be taken
11810 on submitting such a file to the compiler, namely that these pragmas
11811 should apply to all subsequent compilations in the same compilation
11812 environment. Using GNAT, the current directory, possibly containing a
11813 @file{gnat.adc} file is the representation
11814 of a compilation environment. For more information on the
11815 @file{gnat.adc} file, see @ref{Handling of Configuration Pragmas}.
11816
11817 Second, in compilation mode, if @code{gnatchop}
11818 is given a file that starts with
11819 configuration pragmas, and contains one or more units, then these
11820 configuration pragmas are prepended to each of the chopped files. This
11821 behavior provides the required behavior described in the RM for the
11822 actions to be taken on compiling such a file, namely that the pragmas
11823 apply to all units in the compilation, but not to subsequently compiled
11824 units.
11825
11826 Finally, if configuration pragmas appear between units, they are appended
11827 to the previous unit. This results in the previous unit being illegal,
11828 since the compiler does not accept configuration pragmas that follow
11829 a unit. This provides the required RM behavior that forbids configuration
11830 pragmas other than those preceding the first compilation unit of a
11831 compilation.
11832
11833 For most purposes, @code{gnatchop} will be used in default mode. The
11834 compilation mode described above is used only if you need exactly
11835 accurate behavior with respect to compilations, and you have files
11836 that contain multiple units and configuration pragmas. In this
11837 circumstance the use of @code{gnatchop} with the compilation mode
11838 switch provides the required behavior, and is for example the mode
11839 in which GNAT processes the ACVC tests.
11840
11841 @node Command Line for gnatchop
11842 @section Command Line for @code{gnatchop}
11843
11844 @noindent
11845 The @code{gnatchop} command has the form:
11846
11847 @smallexample
11848 @c $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11849 @c @ovar{directory}
11850 @c Expanding @ovar macro inline (explanation in macro def comments)
11851 $ gnatchop switches @var{file name} @r{[}@var{file name} @dots{}@r{]}
11852 @r{[}@var{directory}@r{]}
11853 @end smallexample
11854
11855 @noindent
11856 The only required argument is the file name of the file to be chopped.
11857 There are no restrictions on the form of this file name. The file itself
11858 contains one or more Ada units, in normal GNAT format, concatenated
11859 together. As shown, more than one file may be presented to be chopped.
11860
11861 When run in default mode, @code{gnatchop} generates one output file in
11862 the current directory for each unit in each of the files.
11863
11864 @var{directory}, if specified, gives the name of the directory to which
11865 the output files will be written. If it is not specified, all files are
11866 written to the current directory.
11867
11868 For example, given a
11869 file called @file{hellofiles} containing
11870
11871 @smallexample @c ada
11872 @group
11873 @cartouche
11874 procedure hello;
11875
11876 with Text_IO; use Text_IO;
11877 procedure hello is
11878 begin
11879 Put_Line ("Hello");
11880 end hello;
11881 @end cartouche
11882 @end group
11883 @end smallexample
11884
11885 @noindent
11886 the command
11887
11888 @smallexample
11889 $ gnatchop ^hellofiles^HELLOFILES.^
11890 @end smallexample
11891
11892 @noindent
11893 generates two files in the current directory, one called
11894 @file{hello.ads} containing the single line that is the procedure spec,
11895 and the other called @file{hello.adb} containing the remaining text. The
11896 original file is not affected. The generated files can be compiled in
11897 the normal manner.
11898
11899 @noindent
11900 When gnatchop is invoked on a file that is empty or that contains only empty
11901 lines and/or comments, gnatchop will not fail, but will not produce any
11902 new sources.
11903
11904 For example, given a
11905 file called @file{toto.txt} containing
11906
11907 @smallexample @c ada
11908 @group
11909 @cartouche
11910 -- Just a comment
11911 @end cartouche
11912 @end group
11913 @end smallexample
11914
11915 @noindent
11916 the command
11917
11918 @smallexample
11919 $ gnatchop ^toto.txt^TOT.TXT^
11920 @end smallexample
11921
11922 @noindent
11923 will not produce any new file and will result in the following warnings:
11924
11925 @smallexample
11926 toto.txt:1:01: warning: empty file, contains no compilation units
11927 no compilation units found
11928 no source files written
11929 @end smallexample
11930
11931 @node Switches for gnatchop
11932 @section Switches for @code{gnatchop}
11933
11934 @noindent
11935 @command{gnatchop} recognizes the following switches:
11936
11937 @table @option
11938 @c !sort!
11939
11940 @item --version
11941 @cindex @option{--version} @command{gnatchop}
11942 Display Copyright and version, then exit disregarding all other options.
11943
11944 @item --help
11945 @cindex @option{--help} @command{gnatchop}
11946 If @option{--version} was not used, display usage, then exit disregarding
11947 all other options.
11948
11949 @item ^-c^/COMPILATION^
11950 @cindex @option{^-c^/COMPILATION^} (@code{gnatchop})
11951 Causes @code{gnatchop} to operate in compilation mode, in which
11952 configuration pragmas are handled according to strict RM rules. See
11953 previous section for a full description of this mode.
11954
11955 @ifclear vms
11956 @item -gnat@var{xxx}
11957 This passes the given @option{-gnat@var{xxx}} switch to @code{gnat} which is
11958 used to parse the given file. Not all @var{xxx} options make sense,
11959 but for example, the use of @option{-gnati2} allows @code{gnatchop} to
11960 process a source file that uses Latin-2 coding for identifiers.
11961 @end ifclear
11962
11963 @item ^-h^/HELP^
11964 Causes @code{gnatchop} to generate a brief help summary to the standard
11965 output file showing usage information.
11966
11967 @item ^-k@var{mm}^/FILE_NAME_MAX_LENGTH=@var{mm}^
11968 @cindex @option{^-k^/FILE_NAME_MAX_LENGTH^} (@code{gnatchop})
11969 Limit generated file names to the specified number @code{mm}
11970 of characters.
11971 This is useful if the
11972 resulting set of files is required to be interoperable with systems
11973 which limit the length of file names.
11974 @ifset vms
11975 If no value is given, or
11976 if no @code{/FILE_NAME_MAX_LENGTH} qualifier is given,
11977 a default of 39, suitable for OpenVMS Alpha
11978 Systems, is assumed
11979 @end ifset
11980 @ifclear vms
11981 No space is allowed between the @option{-k} and the numeric value. The numeric
11982 value may be omitted in which case a default of @option{-k8},
11983 suitable for use
11984 with DOS-like file systems, is used. If no @option{-k} switch
11985 is present then
11986 there is no limit on the length of file names.
11987 @end ifclear
11988
11989 @item ^-p^/PRESERVE^
11990 @cindex @option{^-p^/PRESERVE^} (@code{gnatchop})
11991 Causes the file ^modification^creation^ time stamp of the input file to be
11992 preserved and used for the time stamp of the output file(s). This may be
11993 useful for preserving coherency of time stamps in an environment where
11994 @code{gnatchop} is used as part of a standard build process.
11995
11996 @item ^-q^/QUIET^
11997 @cindex @option{^-q^/QUIET^} (@code{gnatchop})
11998 Causes output of informational messages indicating the set of generated
11999 files to be suppressed. Warnings and error messages are unaffected.
12000
12001 @item ^-r^/REFERENCE^
12002 @cindex @option{^-r^/REFERENCE^} (@code{gnatchop})
12003 @findex Source_Reference
12004 Generate @code{Source_Reference} pragmas. Use this switch if the output
12005 files are regarded as temporary and development is to be done in terms
12006 of the original unchopped file. This switch causes
12007 @code{Source_Reference} pragmas to be inserted into each of the
12008 generated files to refers back to the original file name and line number.
12009 The result is that all error messages refer back to the original
12010 unchopped file.
12011 In addition, the debugging information placed into the object file (when
12012 the @option{^-g^/DEBUG^} switch of @command{gcc} or @command{gnatmake} is
12013 specified)
12014 also refers back to this original file so that tools like profilers and
12015 debuggers will give information in terms of the original unchopped file.
12016
12017 If the original file to be chopped itself contains
12018 a @code{Source_Reference}
12019 pragma referencing a third file, then gnatchop respects
12020 this pragma, and the generated @code{Source_Reference} pragmas
12021 in the chopped file refer to the original file, with appropriate
12022 line numbers. This is particularly useful when @code{gnatchop}
12023 is used in conjunction with @code{gnatprep} to compile files that
12024 contain preprocessing statements and multiple units.
12025
12026 @item ^-v^/VERBOSE^
12027 @cindex @option{^-v^/VERBOSE^} (@code{gnatchop})
12028 Causes @code{gnatchop} to operate in verbose mode. The version
12029 number and copyright notice are output, as well as exact copies of
12030 the gnat1 commands spawned to obtain the chop control information.
12031
12032 @item ^-w^/OVERWRITE^
12033 @cindex @option{^-w^/OVERWRITE^} (@code{gnatchop})
12034 Overwrite existing file names. Normally @code{gnatchop} regards it as a
12035 fatal error if there is already a file with the same name as a
12036 file it would otherwise output, in other words if the files to be
12037 chopped contain duplicated units. This switch bypasses this
12038 check, and causes all but the last instance of such duplicated
12039 units to be skipped.
12040
12041 @ifclear vms
12042 @item --GCC=@var{xxxx}
12043 @cindex @option{--GCC=} (@code{gnatchop})
12044 Specify the path of the GNAT parser to be used. When this switch is used,
12045 no attempt is made to add the prefix to the GNAT parser executable.
12046 @end ifclear
12047 @end table
12048
12049 @node Examples of gnatchop Usage
12050 @section Examples of @code{gnatchop} Usage
12051
12052 @table @code
12053 @ifset vms
12054 @item gnatchop /OVERWRITE HELLO_S.ADA [PRERELEASE.FILES]
12055 @end ifset
12056 @ifclear vms
12057 @item gnatchop -w hello_s.ada prerelease/files
12058 @end ifclear
12059
12060 Chops the source file @file{hello_s.ada}. The output files will be
12061 placed in the directory @file{^prerelease/files^[PRERELEASE.FILES]^},
12062 overwriting any
12063 files with matching names in that directory (no files in the current
12064 directory are modified).
12065
12066 @item gnatchop ^archive^ARCHIVE.^
12067 Chops the source file @file{^archive^ARCHIVE.^}
12068 into the current directory. One
12069 useful application of @code{gnatchop} is in sending sets of sources
12070 around, for example in email messages. The required sources are simply
12071 concatenated (for example, using a ^Unix @code{cat}^VMS @code{APPEND/NEW}^
12072 command), and then
12073 @command{gnatchop} is used at the other end to reconstitute the original
12074 file names.
12075
12076 @item gnatchop file1 file2 file3 direc
12077 Chops all units in files @file{file1}, @file{file2}, @file{file3}, placing
12078 the resulting files in the directory @file{direc}. Note that if any units
12079 occur more than once anywhere within this set of files, an error message
12080 is generated, and no files are written. To override this check, use the
12081 @option{^-w^/OVERWRITE^} switch,
12082 in which case the last occurrence in the last file will
12083 be the one that is output, and earlier duplicate occurrences for a given
12084 unit will be skipped.
12085 @end table
12086
12087 @node Configuration Pragmas
12088 @chapter Configuration Pragmas
12089 @cindex Configuration pragmas
12090 @cindex Pragmas, configuration
12091
12092 @menu
12093 * Handling of Configuration Pragmas::
12094 * The Configuration Pragmas Files::
12095 @end menu
12096
12097 @noindent
12098 Configuration pragmas include those pragmas described as
12099 such in the Ada Reference Manual, as well as
12100 implementation-dependent pragmas that are configuration pragmas.
12101 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
12102 for details on these additional GNAT-specific configuration pragmas.
12103 Most notably, the pragma @code{Source_File_Name}, which allows
12104 specifying non-default names for source files, is a configuration
12105 pragma. The following is a complete list of configuration pragmas
12106 recognized by GNAT:
12107
12108 @smallexample
12109 Ada_83
12110 Ada_95
12111 Ada_05
12112 Ada_2005
12113 Ada_12
12114 Ada_2012
12115 Allow_Integer_Address
12116 Annotate
12117 Assertion_Policy
12118 Assume_No_Invalid_Values
12119 C_Pass_By_Copy
12120 Check_Name
12121 Check_Policy
12122 Compile_Time_Error
12123 Compile_Time_Warning
12124 Compiler_Unit
12125 Component_Alignment
12126 Convention_Identifier
12127 Debug_Policy
12128 Detect_Blocking
12129 Default_Storage_Pool
12130 Discard_Names
12131 Elaboration_Checks
12132 Eliminate
12133 Extend_System
12134 Extensions_Allowed
12135 External_Name_Casing
12136 Fast_Math
12137 Favor_Top_Level
12138 Float_Representation
12139 Implicit_Packing
12140 Initialize_Scalars
12141 Interrupt_State
12142 License
12143 Locking_Policy
12144 Long_Float
12145 No_Run_Time
12146 No_Strict_Aliasing
12147 Normalize_Scalars
12148 Optimize_Alignment
12149 Persistent_BSS
12150 Polling
12151 Priority_Specific_Dispatching
12152 Profile
12153 Profile_Warnings
12154 Propagate_Exceptions
12155 Queuing_Policy
12156 Ravenscar
12157 Restricted_Run_Time
12158 Restrictions
12159 Restrictions_Warnings
12160 Reviewable
12161 Short_Circuit_And_Or
12162 Source_File_Name
12163 Source_File_Name_Project
12164 SPARK_Mode
12165 Style_Checks
12166 Suppress
12167 Suppress_Exception_Locations
12168 Task_Dispatching_Policy
12169 Universal_Data
12170 Unsuppress
12171 Use_VADS_Size
12172 Validity_Checks
12173 Warnings
12174 Wide_Character_Encoding
12175 @end smallexample
12176
12177 @node Handling of Configuration Pragmas
12178 @section Handling of Configuration Pragmas
12179
12180 Configuration pragmas may either appear at the start of a compilation
12181 unit, or they can appear in a configuration pragma file to apply to
12182 all compilations performed in a given compilation environment.
12183
12184 GNAT also provides the @code{gnatchop} utility to provide an automatic
12185 way to handle configuration pragmas following the semantics for
12186 compilations (that is, files with multiple units), described in the RM.
12187 See @ref{Operating gnatchop in Compilation Mode} for details.
12188 However, for most purposes, it will be more convenient to edit the
12189 @file{gnat.adc} file that contains configuration pragmas directly,
12190 as described in the following section.
12191
12192 In the case of @code{Restrictions} pragmas appearing as configuration
12193 pragmas in individual compilation units, the exact handling depends on
12194 the type of restriction.
12195
12196 Restrictions that require partition-wide consistency (like
12197 @code{No_Tasking}) are
12198 recognized wherever they appear
12199 and can be freely inherited, e.g. from a with'ed unit to the with'ing
12200 unit. This makes sense since the binder will in any case insist on seeing
12201 consistent use, so any unit not conforming to any restrictions that are
12202 anywhere in the partition will be rejected, and you might as well find
12203 that out at compile time rather than at bind time.
12204
12205 For restrictions that do not require partition-wide consistency, e.g.
12206 SPARK or No_Implementation_Attributes, in general the restriction applies
12207 only to the unit in which the pragma appears, and not to any other units.
12208
12209 The exception is No_Elaboration_Code which always applies to the entire
12210 object file from a compilation, i.e. to the body, spec, and all subunits.
12211 This restriction can be specified in a configuration pragma file, or it
12212 can be on the body and/or the spec (in eithe case it applies to all the
12213 relevant units). It can appear on a subunit only if it has previously
12214 appeared in the body of spec.
12215
12216 @node The Configuration Pragmas Files
12217 @section The Configuration Pragmas Files
12218 @cindex @file{gnat.adc}
12219
12220 @noindent
12221 In GNAT a compilation environment is defined by the current
12222 directory at the time that a compile command is given. This current
12223 directory is searched for a file whose name is @file{gnat.adc}. If
12224 this file is present, it is expected to contain one or more
12225 configuration pragmas that will be applied to the current compilation.
12226 However, if the switch @option{-gnatA} is used, @file{gnat.adc} is not
12227 considered.
12228
12229 Configuration pragmas may be entered into the @file{gnat.adc} file
12230 either by running @code{gnatchop} on a source file that consists only of
12231 configuration pragmas, or more conveniently by
12232 direct editing of the @file{gnat.adc} file, which is a standard format
12233 source file.
12234
12235 In addition to @file{gnat.adc}, additional files containing configuration
12236 pragmas may be applied to the current compilation using the switch
12237 @option{-gnatec}@var{path}. @var{path} must designate an existing file that
12238 contains only configuration pragmas. These configuration pragmas are
12239 in addition to those found in @file{gnat.adc} (provided @file{gnat.adc}
12240 is present and switch @option{-gnatA} is not used).
12241
12242 It is allowed to specify several switches @option{-gnatec}, all of which
12243 will be taken into account.
12244
12245 If you are using project file, a separate mechanism is provided using
12246 project attributes, see @ref{Specifying Configuration Pragmas} for more
12247 details.
12248
12249 @ifset vms
12250 Of special interest to GNAT OpenVMS Alpha is the following
12251 configuration pragma:
12252
12253 @smallexample @c ada
12254 @cartouche
12255 pragma Extend_System (Aux_DEC);
12256 @end cartouche
12257 @end smallexample
12258
12259 @noindent
12260 In the presence of this pragma, GNAT adds to the definition of the
12261 predefined package SYSTEM all the additional types and subprograms that are
12262 defined in HP Ada. See @ref{Compatibility with HP Ada} for details.
12263 @end ifset
12264
12265 @node Handling Arbitrary File Naming Conventions with gnatname
12266 @chapter Handling Arbitrary File Naming Conventions with @code{gnatname}
12267 @cindex Arbitrary File Naming Conventions
12268
12269 @menu
12270 * Arbitrary File Naming Conventions::
12271 * Running gnatname::
12272 * Switches for gnatname::
12273 * Examples of gnatname Usage::
12274 @end menu
12275
12276 @node Arbitrary File Naming Conventions
12277 @section Arbitrary File Naming Conventions
12278
12279 @noindent
12280 The GNAT compiler must be able to know the source file name of a compilation
12281 unit. When using the standard GNAT default file naming conventions
12282 (@code{.ads} for specs, @code{.adb} for bodies), the GNAT compiler
12283 does not need additional information.
12284
12285 @noindent
12286 When the source file names do not follow the standard GNAT default file naming
12287 conventions, the GNAT compiler must be given additional information through
12288 a configuration pragmas file (@pxref{Configuration Pragmas})
12289 or a project file.
12290 When the non-standard file naming conventions are well-defined,
12291 a small number of pragmas @code{Source_File_Name} specifying a naming pattern
12292 (@pxref{Alternative File Naming Schemes}) may be sufficient. However,
12293 if the file naming conventions are irregular or arbitrary, a number
12294 of pragma @code{Source_File_Name} for individual compilation units
12295 must be defined.
12296 To help maintain the correspondence between compilation unit names and
12297 source file names within the compiler,
12298 GNAT provides a tool @code{gnatname} to generate the required pragmas for a
12299 set of files.
12300
12301 @node Running gnatname
12302 @section Running @code{gnatname}
12303
12304 @noindent
12305 The usual form of the @code{gnatname} command is
12306
12307 @smallexample
12308 @c $ gnatname @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}
12309 @c @r{[}--and @ovar{switches} @var{naming_pattern} @ovar{naming_patterns}@r{]}
12310 @c Expanding @ovar macro inline (explanation in macro def comments)
12311 $ gnatname @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}
12312 @r{[}--and @r{[}@var{switches}@r{]} @var{naming_pattern} @r{[}@var{naming_patterns}@r{]}@r{]}
12313 @end smallexample
12314
12315 @noindent
12316 All of the arguments are optional. If invoked without any argument,
12317 @code{gnatname} will display its usage.
12318
12319 @noindent
12320 When used with at least one naming pattern, @code{gnatname} will attempt to
12321 find all the compilation units in files that follow at least one of the
12322 naming patterns. To find these compilation units,
12323 @code{gnatname} will use the GNAT compiler in syntax-check-only mode on all
12324 regular files.
12325
12326 @noindent
12327 One or several Naming Patterns may be given as arguments to @code{gnatname}.
12328 Each Naming Pattern is enclosed between double quotes (or single
12329 quotes on Windows).
12330 A Naming Pattern is a regular expression similar to the wildcard patterns
12331 used in file names by the Unix shells or the DOS prompt.
12332
12333 @noindent
12334 @code{gnatname} may be called with several sections of directories/patterns.
12335 Sections are separated by switch @code{--and}. In each section, there must be
12336 at least one pattern. If no directory is specified in a section, the current
12337 directory (or the project directory is @code{-P} is used) is implied.
12338 The options other that the directory switches and the patterns apply globally
12339 even if they are in different sections.
12340
12341 @noindent
12342 Examples of Naming Patterns are
12343
12344 @smallexample
12345 "*.[12].ada"
12346 "*.ad[sb]*"
12347 "body_*" "spec_*"
12348 @end smallexample
12349
12350 @noindent
12351 For a more complete description of the syntax of Naming Patterns,
12352 see the second kind of regular expressions described in @file{g-regexp.ads}
12353 (the ``Glob'' regular expressions).
12354
12355 @noindent
12356 When invoked with no switch @code{-P}, @code{gnatname} will create a
12357 configuration pragmas file @file{gnat.adc} in the current working directory,
12358 with pragmas @code{Source_File_Name} for each file that contains a valid Ada
12359 unit.
12360
12361 @node Switches for gnatname
12362 @section Switches for @code{gnatname}
12363
12364 @noindent
12365 Switches for @code{gnatname} must precede any specified Naming Pattern.
12366
12367 @noindent
12368 You may specify any of the following switches to @code{gnatname}:
12369
12370 @table @option
12371 @c !sort!
12372
12373 @item --version
12374 @cindex @option{--version} @command{gnatname}
12375 Display Copyright and version, then exit disregarding all other options.
12376
12377 @item --help
12378 @cindex @option{--help} @command{gnatname}
12379 If @option{--version} was not used, display usage, then exit disregarding
12380 all other options.
12381
12382 @item --subdirs=<dir>
12383 Real object, library or exec directories are subdirectories <dir> of the
12384 specified ones.
12385
12386 @item --no-backup
12387 Do not create a backup copy of an existing project file.
12388
12389 @item --and
12390 Start another section of directories/patterns.
12391
12392 @item ^-c^/CONFIG_FILE=^@file{file}
12393 @cindex @option{^-c^/CONFIG_FILE^} (@code{gnatname})
12394 Create a configuration pragmas file @file{file} (instead of the default
12395 @file{gnat.adc}).
12396 @ifclear vms
12397 There may be zero, one or more space between @option{-c} and
12398 @file{file}.
12399 @end ifclear
12400 @file{file} may include directory information. @file{file} must be
12401 writable. There may be only one switch @option{^-c^/CONFIG_FILE^}.
12402 When a switch @option{^-c^/CONFIG_FILE^} is
12403 specified, no switch @option{^-P^/PROJECT_FILE^} may be specified (see below).
12404
12405 @item ^-d^/SOURCE_DIRS=^@file{dir}
12406 @cindex @option{^-d^/SOURCE_DIRS^} (@code{gnatname})
12407 Look for source files in directory @file{dir}. There may be zero, one or more
12408 spaces between @option{^-d^/SOURCE_DIRS=^} and @file{dir}.
12409 @file{dir} may end with @code{/**}, that is it may be of the form
12410 @code{root_dir/**}. In this case, the directory @code{root_dir} and all of its
12411 subdirectories, recursively, have to be searched for sources.
12412 When a switch @option{^-d^/SOURCE_DIRS^}
12413 is specified, the current working directory will not be searched for source
12414 files, unless it is explicitly specified with a @option{^-d^/SOURCE_DIRS^}
12415 or @option{^-D^/DIR_FILES^} switch.
12416 Several switches @option{^-d^/SOURCE_DIRS^} may be specified.
12417 If @file{dir} is a relative path, it is relative to the directory of
12418 the configuration pragmas file specified with switch
12419 @option{^-c^/CONFIG_FILE^},
12420 or to the directory of the project file specified with switch
12421 @option{^-P^/PROJECT_FILE^} or,
12422 if neither switch @option{^-c^/CONFIG_FILE^}
12423 nor switch @option{^-P^/PROJECT_FILE^} are specified, it is relative to the
12424 current working directory. The directory
12425 specified with switch @option{^-d^/SOURCE_DIRS^} must exist and be readable.
12426
12427 @item ^-D^/DIRS_FILE=^@file{file}
12428 @cindex @option{^-D^/DIRS_FILE^} (@code{gnatname})
12429 Look for source files in all directories listed in text file @file{file}.
12430 There may be zero, one or more spaces between @option{^-D^/DIRS_FILE=^}
12431 and @file{file}.
12432 @file{file} must be an existing, readable text file.
12433 Each nonempty line in @file{file} must be a directory.
12434 Specifying switch @option{^-D^/DIRS_FILE^} is equivalent to specifying as many
12435 switches @option{^-d^/SOURCE_DIRS^} as there are nonempty lines in
12436 @file{file}.
12437
12438 @item -eL
12439 Follow symbolic links when processing project files.
12440
12441 @item ^-f^/FOREIGN_PATTERN=^@file{pattern}
12442 @cindex @option{^-f^/FOREIGN_PATTERN^} (@code{gnatname})
12443 Foreign patterns. Using this switch, it is possible to add sources of languages
12444 other than Ada to the list of sources of a project file.
12445 It is only useful if a ^-P^/PROJECT_FILE^ switch is used.
12446 For example,
12447 @smallexample
12448 gnatname ^-Pprj -f"*.c"^/PROJECT_FILE=PRJ /FOREIGN_PATTERN=*.C^ "*.ada"
12449 @end smallexample
12450 @noindent
12451 will look for Ada units in all files with the @file{.ada} extension,
12452 and will add to the list of file for project @file{prj.gpr} the C files
12453 with extension @file{.^c^C^}.
12454
12455 @item ^-h^/HELP^
12456 @cindex @option{^-h^/HELP^} (@code{gnatname})
12457 Output usage (help) information. The output is written to @file{stdout}.
12458
12459 @item ^-P^/PROJECT_FILE=^@file{proj}
12460 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatname})
12461 Create or update project file @file{proj}. There may be zero, one or more space
12462 between @option{-P} and @file{proj}. @file{proj} may include directory
12463 information. @file{proj} must be writable.
12464 There may be only one switch @option{^-P^/PROJECT_FILE^}.
12465 When a switch @option{^-P^/PROJECT_FILE^} is specified,
12466 no switch @option{^-c^/CONFIG_FILE^} may be specified.
12467 On all platforms, except on VMS, when @code{gnatname} is invoked for an
12468 existing project file <proj>.gpr, a backup copy of the project file is created
12469 in the project directory with file name <proj>.gpr.saved_x. 'x' is the first
12470 non negative number that makes this backup copy a new file.
12471
12472 @item ^-v^/VERBOSE^
12473 @cindex @option{^-v^/VERBOSE^} (@code{gnatname})
12474 Verbose mode. Output detailed explanation of behavior to @file{stdout}.
12475 This includes name of the file written, the name of the directories to search
12476 and, for each file in those directories whose name matches at least one of
12477 the Naming Patterns, an indication of whether the file contains a unit,
12478 and if so the name of the unit.
12479
12480 @item ^-v -v^/VERBOSE /VERBOSE^
12481 @cindex @option{^-v -v^/VERBOSE /VERBOSE^} (@code{gnatname})
12482 Very Verbose mode. In addition to the output produced in verbose mode,
12483 for each file in the searched directories whose name matches none of
12484 the Naming Patterns, an indication is given that there is no match.
12485
12486 @item ^-x^/EXCLUDED_PATTERN=^@file{pattern}
12487 @cindex @option{^-x^/EXCLUDED_PATTERN^} (@code{gnatname})
12488 Excluded patterns. Using this switch, it is possible to exclude some files
12489 that would match the name patterns. For example,
12490 @smallexample
12491 gnatname ^-x "*_nt.ada"^/EXCLUDED_PATTERN=*_nt.ada^ "*.ada"
12492 @end smallexample
12493 @noindent
12494 will look for Ada units in all files with the @file{.ada} extension,
12495 except those whose names end with @file{_nt.ada}.
12496
12497 @end table
12498
12499 @node Examples of gnatname Usage
12500 @section Examples of @code{gnatname} Usage
12501
12502 @ifset vms
12503 @smallexample
12504 $ gnatname /CONFIG_FILE=[HOME.ME]NAMES.ADC /SOURCE_DIRS=SOURCES "[a-z]*.ada*"
12505 @end smallexample
12506 @end ifset
12507
12508 @ifclear vms
12509 @smallexample
12510 $ gnatname -c /home/me/names.adc -d sources "[a-z]*.ada*"
12511 @end smallexample
12512 @end ifclear
12513
12514 @noindent
12515 In this example, the directory @file{^/home/me^[HOME.ME]^} must already exist
12516 and be writable. In addition, the directory
12517 @file{^/home/me/sources^[HOME.ME.SOURCES]^} (specified by
12518 @option{^-d sources^/SOURCE_DIRS=SOURCES^}) must exist and be readable.
12519
12520 @ifclear vms
12521 Note the optional spaces after @option{-c} and @option{-d}.
12522 @end ifclear
12523
12524 @smallexample
12525 @ifclear vms
12526 $ gnatname -P/home/me/proj -x "*_nt_body.ada"
12527 -dsources -dsources/plus -Dcommon_dirs.txt "body_*" "spec_*"
12528 @end ifclear
12529 @ifset vms
12530 $ gnatname /PROJECT_FILE=[HOME.ME]PROJ
12531 /EXCLUDED_PATTERN=*_nt_body.ada
12532 /SOURCE_DIRS=(SOURCES,[SOURCES.PLUS])
12533 /DIRS_FILE=COMMON_DIRS.TXT "body_*" "spec_*"
12534 @end ifset
12535 @end smallexample
12536
12537 Note that several switches @option{^-d^/SOURCE_DIRS^} may be used,
12538 even in conjunction with one or several switches
12539 @option{^-D^/DIRS_FILE^}. Several Naming Patterns and one excluded pattern
12540 are used in this example.
12541
12542 @c *****************************************
12543 @c * G N A T P r o j e c t M a n a g e r *
12544 @c *****************************************
12545
12546 @c ------ macros for projects.texi
12547 @c These macros are needed when building the gprbuild documentation, but
12548 @c should have no effect in the gnat user's guide
12549
12550 @macro CODESAMPLE{TXT}
12551 @smallexample
12552 @group
12553 \TXT\
12554 @end group
12555 @end smallexample
12556 @end macro
12557
12558 @macro PROJECTFILE{TXT}
12559 @CODESAMPLE{\TXT\}
12560 @end macro
12561
12562 @c simulates a newline when in a @CODESAMPLE
12563 @macro NL{}
12564 @end macro
12565
12566 @macro TIP{TXT}
12567 @quotation
12568 @noindent
12569 \TXT\
12570 @end quotation
12571 @end macro
12572
12573 @macro TIPHTML{TXT}
12574 \TXT\
12575 @end macro
12576
12577 @macro IMPORTANT{TXT}
12578 @quotation
12579 @noindent
12580 \TXT\
12581 @end quotation
12582
12583 @end macro
12584
12585 @macro NOTE{TXT}
12586 @quotation
12587 @noindent
12588 \TXT\
12589 @end quotation
12590 @end macro
12591
12592 @include projects.texi
12593
12594 @c ---------------------------------------------
12595 @c Tools Supporting Project Files
12596 @c ---------------------------------------------
12597
12598 @node Tools Supporting Project Files
12599 @chapter Tools Supporting Project Files
12600
12601 @noindent
12602
12603 @menu
12604 * gnatmake and Project Files::
12605 * The GNAT Driver and Project Files::
12606 @end menu
12607
12608 @c ---------------------------------------------
12609 @node gnatmake and Project Files
12610 @section gnatmake and Project Files
12611 @c ---------------------------------------------
12612
12613 @noindent
12614 This section covers several topics related to @command{gnatmake} and
12615 project files: defining ^switches^switches^ for @command{gnatmake}
12616 and for the tools that it invokes; specifying configuration pragmas;
12617 the use of the @code{Main} attribute; building and rebuilding library project
12618 files.
12619
12620 @menu
12621 * Switches Related to Project Files::
12622 * Switches and Project Files::
12623 * Specifying Configuration Pragmas::
12624 * Project Files and Main Subprograms::
12625 * Library Project Files::
12626 @end menu
12627
12628 @c ---------------------------------------------
12629 @node Switches Related to Project Files
12630 @subsection Switches Related to Project Files
12631 @c ---------------------------------------------
12632
12633 @noindent
12634 The following switches are used by GNAT tools that support project files:
12635
12636 @table @option
12637
12638 @item ^-P^/PROJECT_FILE=^@var{project}
12639 @cindex @option{^-P^/PROJECT_FILE^} (any project-aware tool)
12640 Indicates the name of a project file. This project file will be parsed with
12641 the verbosity indicated by @option{^-vP^MESSAGE_PROJECT_FILES=^@emph{x}},
12642 if any, and using the external references indicated
12643 by @option{^-X^/EXTERNAL_REFERENCE^} switches, if any.
12644 @ifclear vms
12645 There may zero, one or more spaces between @option{-P} and @var{project}.
12646 @end ifclear
12647
12648 There must be only one @option{^-P^/PROJECT_FILE^} switch on the command line.
12649
12650 Since the Project Manager parses the project file only after all the switches
12651 on the command line are checked, the order of the switches
12652 @option{^-P^/PROJECT_FILE^},
12653 @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}}
12654 or @option{^-X^/EXTERNAL_REFERENCE^} is not significant.
12655
12656 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
12657 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (any project-aware tool)
12658 Indicates that external variable @var{name} has the value @var{value}.
12659 The Project Manager will use this value for occurrences of
12660 @code{external(name)} when parsing the project file.
12661
12662 @ifclear vms
12663 If @var{name} or @var{value} includes a space, then @var{name=value} should be
12664 put between quotes.
12665 @smallexample
12666 -XOS=NT
12667 -X"user=John Doe"
12668 @end smallexample
12669 @end ifclear
12670
12671 Several @option{^-X^/EXTERNAL_REFERENCE^} switches can be used simultaneously.
12672 If several @option{^-X^/EXTERNAL_REFERENCE^} switches specify the same
12673 @var{name}, only the last one is used.
12674
12675 An external variable specified with a @option{^-X^/EXTERNAL_REFERENCE^} switch
12676 takes precedence over the value of the same name in the environment.
12677
12678 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
12679 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (any project-aware tool)
12680 Indicates the verbosity of the parsing of GNAT project files.
12681
12682 @ifclear vms
12683 @option{-vP0} means Default;
12684 @option{-vP1} means Medium;
12685 @option{-vP2} means High.
12686 @end ifclear
12687
12688 @ifset vms
12689 There are three possible options for this qualifier: DEFAULT, MEDIUM and
12690 HIGH.
12691 @end ifset
12692
12693 The default is ^Default^DEFAULT^: no output for syntactically correct
12694 project files.
12695 If several @option{^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}} switches are present,
12696 only the last one is used.
12697
12698 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^<dir>
12699 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (any project-aware tool)
12700 Add directory <dir> at the beginning of the project search path, in order,
12701 after the current working directory.
12702
12703 @ifclear vms
12704 @item -eL
12705 @cindex @option{-eL} (any project-aware tool)
12706 Follow all symbolic links when processing project files.
12707 @end ifclear
12708
12709 @item ^--subdirs^/SUBDIRS^=<subdir>
12710 @cindex @option{^--subdirs^/SUBDIRS^=} (gnatmake and gnatclean)
12711 This switch is recognized by @command{gnatmake} and @command{gnatclean}. It
12712 indicate that the real directories (except the source directories) are the
12713 subdirectories <subdir> of the directories specified in the project files.
12714 This applies in particular to object directories, library directories and
12715 exec directories. If the subdirectories do not exist, they are created
12716 automatically.
12717
12718 @end table
12719
12720 @c ---------------------------------------------
12721 @node Switches and Project Files
12722 @subsection Switches and Project Files
12723 @c ---------------------------------------------
12724
12725 @noindent
12726 @ifset vms
12727 It is not currently possible to specify VMS style qualifiers in the project
12728 files; only Unix style ^switches^switches^ may be specified.
12729 @end ifset
12730
12731 For each of the packages @code{Builder}, @code{Compiler}, @code{Binder}, and
12732 @code{Linker}, you can specify a @code{^Default_Switches^Default_Switches^}
12733 attribute, a @code{Switches} attribute, or both;
12734 as their names imply, these ^switch^switch^-related
12735 attributes affect the ^switches^switches^ that are used for each of these GNAT
12736 components when
12737 @command{gnatmake} is invoked. As will be explained below, these
12738 component-specific ^switches^switches^ precede
12739 the ^switches^switches^ provided on the @command{gnatmake} command line.
12740
12741 The @code{^Default_Switches^Default_Switches^} attribute is an attribute
12742 indexed by language name (case insensitive) whose value is a string list.
12743 For example:
12744
12745 @smallexample @c projectfile
12746 @group
12747 package Compiler is
12748 for ^Default_Switches^Default_Switches^ ("Ada")
12749 use ("^-gnaty^-gnaty^",
12750 "^-v^-v^");
12751 end Compiler;
12752 @end group
12753 @end smallexample
12754
12755 @noindent
12756 The @code{Switches} attribute is indexed on a file name (which may or may
12757 not be case sensitive, depending
12758 on the operating system) whose value is a string list. For example:
12759
12760 @smallexample @c projectfile
12761 @group
12762 package Builder is
12763 for Switches ("main1.adb")
12764 use ("^-O2^-O2^");
12765 for Switches ("main2.adb")
12766 use ("^-g^-g^");
12767 end Builder;
12768 @end group
12769 @end smallexample
12770
12771 @noindent
12772 For the @code{Builder} package, the file names must designate source files
12773 for main subprograms. For the @code{Binder} and @code{Linker} packages, the
12774 file names must designate @file{ALI} or source files for main subprograms.
12775 In each case just the file name without an explicit extension is acceptable.
12776
12777 For each tool used in a program build (@command{gnatmake}, the compiler, the
12778 binder, and the linker), the corresponding package @dfn{contributes} a set of
12779 ^switches^switches^ for each file on which the tool is invoked, based on the
12780 ^switch^switch^-related attributes defined in the package.
12781 In particular, the ^switches^switches^
12782 that each of these packages contributes for a given file @var{f} comprise:
12783
12784 @itemize @bullet
12785 @item the value of attribute @code{Switches (@var{f})},
12786 if it is specified in the package for the given file,
12787 @item otherwise, the value of @code{^Default_Switches^Default_Switches^ ("Ada")},
12788 if it is specified in the package.
12789
12790 @end itemize
12791
12792 @noindent
12793 If neither of these attributes is defined in the package, then the package does
12794 not contribute any ^switches^switches^ for the given file.
12795
12796 When @command{gnatmake} is invoked on a file, the ^switches^switches^ comprise
12797 two sets, in the following order: those contributed for the file
12798 by the @code{Builder} package;
12799 and the switches passed on the command line.
12800
12801 When @command{gnatmake} invokes a tool (compiler, binder, linker) on a file,
12802 the ^switches^switches^ passed to the tool comprise three sets,
12803 in the following order:
12804
12805 @enumerate
12806 @item
12807 the applicable ^switches^switches^ contributed for the file
12808 by the @code{Builder} package in the project file supplied on the command line;
12809
12810 @item
12811 those contributed for the file by the package (in the relevant project file --
12812 see below) corresponding to the tool; and
12813
12814 @item
12815 the applicable switches passed on the command line.
12816 @end enumerate
12817
12818 The term @emph{applicable ^switches^switches^} reflects the fact that
12819 @command{gnatmake} ^switches^switches^ may or may not be passed to individual
12820 tools, depending on the individual ^switch^switch^.
12821
12822 @command{gnatmake} may invoke the compiler on source files from different
12823 projects. The Project Manager will use the appropriate project file to
12824 determine the @code{Compiler} package for each source file being compiled.
12825 Likewise for the @code{Binder} and @code{Linker} packages.
12826
12827 As an example, consider the following package in a project file:
12828
12829 @smallexample @c projectfile
12830 @group
12831 project Proj1 is
12832 package Compiler is
12833 for ^Default_Switches^Default_Switches^ ("Ada")
12834 use ("^-g^-g^");
12835 for Switches ("a.adb")
12836 use ("^-O1^-O1^");
12837 for Switches ("b.adb")
12838 use ("^-O2^-O2^",
12839 "^-gnaty^-gnaty^");
12840 end Compiler;
12841 end Proj1;
12842 @end group
12843 @end smallexample
12844
12845 @noindent
12846 If @command{gnatmake} is invoked with this project file, and it needs to
12847 compile, say, the files @file{a.adb}, @file{b.adb}, and @file{c.adb}, then
12848 @file{a.adb} will be compiled with the ^switch^switch^
12849 @option{^-O1^-O1^},
12850 @file{b.adb} with ^switches^switches^
12851 @option{^-O2^-O2^}
12852 and @option{^-gnaty^-gnaty^},
12853 and @file{c.adb} with @option{^-g^-g^}.
12854
12855 The following example illustrates the ordering of the ^switches^switches^
12856 contributed by different packages:
12857
12858 @smallexample @c projectfile
12859 @group
12860 project Proj2 is
12861 package Builder is
12862 for Switches ("main.adb")
12863 use ("^-g^-g^",
12864 "^-O1^-)1^",
12865 "^-f^-f^");
12866 end Builder;
12867 @end group
12868
12869 @group
12870 package Compiler is
12871 for Switches ("main.adb")
12872 use ("^-O2^-O2^");
12873 end Compiler;
12874 end Proj2;
12875 @end group
12876 @end smallexample
12877
12878 @noindent
12879 If you issue the command:
12880
12881 @smallexample
12882 gnatmake ^-Pproj2^/PROJECT_FILE=PROJ2^ -O0 main
12883 @end smallexample
12884
12885 @noindent
12886 then the compiler will be invoked on @file{main.adb} with the following
12887 sequence of ^switches^switches^
12888
12889 @smallexample
12890 ^-g -O1 -O2 -O0^-g -O1 -O2 -O0^
12891 @end smallexample
12892
12893 @noindent
12894 with the last @option{^-O^-O^}
12895 ^switch^switch^ having precedence over the earlier ones;
12896 several other ^switches^switches^
12897 (such as @option{^-c^-c^}) are added implicitly.
12898
12899 The ^switches^switches^
12900 @option{^-g^-g^}
12901 and @option{^-O1^-O1^} are contributed by package
12902 @code{Builder}, @option{^-O2^-O2^} is contributed
12903 by the package @code{Compiler}
12904 and @option{^-O0^-O0^} comes from the command line.
12905
12906 The @option{^-g^-g^}
12907 ^switch^switch^ will also be passed in the invocation of
12908 @command{Gnatlink.}
12909
12910 A final example illustrates switch contributions from packages in different
12911 project files:
12912
12913 @smallexample @c projectfile
12914 @group
12915 project Proj3 is
12916 for Source_Files use ("pack.ads", "pack.adb");
12917 package Compiler is
12918 for ^Default_Switches^Default_Switches^ ("Ada")
12919 use ("^-gnata^-gnata^");
12920 end Compiler;
12921 end Proj3;
12922 @end group
12923
12924 @group
12925 with "Proj3";
12926 project Proj4 is
12927 for Source_Files use ("foo_main.adb", "bar_main.adb");
12928 package Builder is
12929 for Switches ("foo_main.adb")
12930 use ("^-s^-s^",
12931 "^-g^-g^");
12932 end Builder;
12933 end Proj4;
12934 @end group
12935
12936 @group
12937 -- Ada source file:
12938 with Pack;
12939 procedure Foo_Main is
12940 @dots{}
12941 end Foo_Main;
12942 @end group
12943 @end smallexample
12944
12945 @noindent
12946 If the command is
12947 @smallexample
12948 gnatmake ^-PProj4^/PROJECT_FILE=PROJ4^ foo_main.adb -cargs -gnato
12949 @end smallexample
12950
12951 @noindent
12952 then the ^switches^switches^ passed to the compiler for @file{foo_main.adb} are
12953 @option{^-g^-g^} (contributed by the package @code{Proj4.Builder}) and
12954 @option{^-gnato^-gnato^} (passed on the command line).
12955 When the imported package @code{Pack} is compiled, the ^switches^switches^ used
12956 are @option{^-g^-g^} from @code{Proj4.Builder},
12957 @option{^-gnata^-gnata^} (contributed from package @code{Proj3.Compiler},
12958 and @option{^-gnato^-gnato^} from the command line.
12959
12960 When using @command{gnatmake} with project files, some ^switches^switches^ or
12961 arguments may be expressed as relative paths. As the working directory where
12962 compilation occurs may change, these relative paths are converted to absolute
12963 paths. For the ^switches^switches^ found in a project file, the relative paths
12964 are relative to the project file directory, for the switches on the command
12965 line, they are relative to the directory where @command{gnatmake} is invoked.
12966 The ^switches^switches^ for which this occurs are:
12967 ^-I^-I^,
12968 ^-A^-A^,
12969 ^-L^-L^,
12970 ^-aO^-aO^,
12971 ^-aL^-aL^,
12972 ^-aI^-aI^, as well as all arguments that are not switches (arguments to
12973 ^switch^switch^
12974 ^-o^-o^, object files specified in package @code{Linker} or after
12975 -largs on the command line). The exception to this rule is the ^switch^switch^
12976 ^--RTS=^--RTS=^ for which a relative path argument is never converted.
12977
12978 @c ---------------------------------------------
12979 @node Specifying Configuration Pragmas
12980 @subsection Specifying Configuration Pragmas
12981 @c ---------------------------------------------
12982
12983 @noindent
12984 When using @command{gnatmake} with project files, if there exists a file
12985 @file{gnat.adc} that contains configuration pragmas, this file will be
12986 ignored.
12987
12988 Configuration pragmas can be defined by means of the following attributes in
12989 project files: @code{Global_Configuration_Pragmas} in package @code{Builder}
12990 and @code{Local_Configuration_Pragmas} in package @code{Compiler}.
12991
12992 Both these attributes are single string attributes. Their values is the path
12993 name of a file containing configuration pragmas. If a path name is relative,
12994 then it is relative to the project directory of the project file where the
12995 attribute is defined.
12996
12997 When compiling a source, the configuration pragmas used are, in order,
12998 those listed in the file designated by attribute
12999 @code{Global_Configuration_Pragmas} in package @code{Builder} of the main
13000 project file, if it is specified, and those listed in the file designated by
13001 attribute @code{Local_Configuration_Pragmas} in package @code{Compiler} of
13002 the project file of the source, if it exists.
13003
13004 @c ---------------------------------------------
13005 @node Project Files and Main Subprograms
13006 @subsection Project Files and Main Subprograms
13007 @c ---------------------------------------------
13008
13009 @noindent
13010 When using a project file, you can invoke @command{gnatmake}
13011 with one or several main subprograms, by specifying their source files on the
13012 command line.
13013
13014 @smallexample
13015 gnatmake ^-P^/PROJECT_FILE=^prj main1.adb main2.adb main3.adb
13016 @end smallexample
13017
13018 @noindent
13019 Each of these needs to be a source file of the same project, except
13020 when the switch ^-u^/UNIQUE^ is used.
13021
13022 When ^-u^/UNIQUE^ is not used, all the mains need to be sources of the
13023 same project, one of the project in the tree rooted at the project specified
13024 on the command line. The package @code{Builder} of this common project, the
13025 "main project" is the one that is considered by @command{gnatmake}.
13026
13027 When ^-u^/UNIQUE^ is used, the specified source files may be in projects
13028 imported directly or indirectly by the project specified on the command line.
13029 Note that if such a source file is not part of the project specified on the
13030 command line, the ^switches^switches^ found in package @code{Builder} of the
13031 project specified on the command line, if any, that are transmitted
13032 to the compiler will still be used, not those found in the project file of
13033 the source file.
13034
13035 When using a project file, you can also invoke @command{gnatmake} without
13036 explicitly specifying any main, and the effect depends on whether you have
13037 defined the @code{Main} attribute. This attribute has a string list value,
13038 where each element in the list is the name of a source file (the file
13039 extension is optional) that contains a unit that can be a main subprogram.
13040
13041 If the @code{Main} attribute is defined in a project file as a non-empty
13042 string list and the switch @option{^-u^/UNIQUE^} is not used on the command
13043 line, then invoking @command{gnatmake} with this project file but without any
13044 main on the command line is equivalent to invoking @command{gnatmake} with all
13045 the file names in the @code{Main} attribute on the command line.
13046
13047 Example:
13048 @smallexample @c projectfile
13049 @group
13050 project Prj is
13051 for Main use ("main1.adb", "main2.adb", "main3.adb");
13052 end Prj;
13053 @end group
13054 @end smallexample
13055
13056 @noindent
13057 With this project file, @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^"}
13058 is equivalent to
13059 @code{"gnatmake ^-Pprj^/PROJECT_FILE=PRJ^ main1.adb main2.adb main3.adb"}.
13060
13061 When the project attribute @code{Main} is not specified, or is specified
13062 as an empty string list, or when the switch @option{-u} is used on the command
13063 line, then invoking @command{gnatmake} with no main on the command line will
13064 result in all immediate sources of the project file being checked, and
13065 potentially recompiled. Depending on the presence of the switch @option{-u},
13066 sources from other project files on which the immediate sources of the main
13067 project file depend are also checked and potentially recompiled. In other
13068 words, the @option{-u} switch is applied to all of the immediate sources of the
13069 main project file.
13070
13071 When no main is specified on the command line and attribute @code{Main} exists
13072 and includes several mains, or when several mains are specified on the
13073 command line, the default ^switches^switches^ in package @code{Builder} will
13074 be used for all mains, even if there are specific ^switches^switches^
13075 specified for one or several mains.
13076
13077 But the ^switches^switches^ from package @code{Binder} or @code{Linker} will be
13078 the specific ^switches^switches^ for each main, if they are specified.
13079
13080 @c ---------------------------------------------
13081 @node Library Project Files
13082 @subsection Library Project Files
13083 @c ---------------------------------------------
13084
13085 @noindent
13086 When @command{gnatmake} is invoked with a main project file that is a library
13087 project file, it is not allowed to specify one or more mains on the command
13088 line.
13089
13090 When a library project file is specified, switches ^-b^/ACTION=BIND^ and
13091 ^-l^/ACTION=LINK^ have special meanings.
13092
13093 @itemize @bullet
13094 @item ^-b^/ACTION=BIND^ is only allowed for stand-alone libraries. It indicates
13095 to @command{gnatmake} that @command{gnatbind} should be invoked for the
13096 library.
13097
13098 @item ^-l^/ACTION=LINK^ may be used for all library projects. It indicates
13099 to @command{gnatmake} that the binder generated file should be compiled
13100 (in the case of a stand-alone library) and that the library should be built.
13101 @end itemize
13102
13103 @c ---------------------------------------------
13104 @node The GNAT Driver and Project Files
13105 @section The GNAT Driver and Project Files
13106 @c ---------------------------------------------
13107
13108 @noindent
13109 A number of GNAT tools, other than @command{^gnatmake^gnatmake^}
13110 can benefit from project files:
13111 (@command{^gnatbind^gnatbind^},
13112 @ifclear FSFEDITION
13113 @command{^gnatcheck^gnatcheck^},
13114 @end ifclear
13115 @command{^gnatclean^gnatclean^},
13116 @ifclear FSFEDITION
13117 @command{^gnatelim^gnatelim^},
13118 @end ifclear
13119 @command{^gnatfind^gnatfind^},
13120 @command{^gnatlink^gnatlink^},
13121 @command{^gnatls^gnatls^},
13122 @ifclear FSFEDITION
13123 @command{^gnatmetric^gnatmetric^},
13124 @command{^gnatpp^gnatpp^},
13125 @command{^gnatstub^gnatstub^},
13126 @end ifclear
13127 and @command{^gnatxref^gnatxref^}). However, none of these tools can be invoked
13128 directly with a project file switch (@option{^-P^/PROJECT_FILE=^}).
13129 They must be invoked through the @command{gnat} driver.
13130
13131 The @command{gnat} driver is a wrapper that accepts a number of commands and
13132 calls the corresponding tool. It was designed initially for VMS platforms (to
13133 convert VMS qualifiers to Unix-style switches), but it is now available on all
13134 GNAT platforms.
13135
13136 On non-VMS platforms, the @command{gnat} driver accepts the following commands
13137 (case insensitive):
13138
13139 @itemize @bullet
13140 @item BIND to invoke @command{^gnatbind^gnatbind^}
13141 @item CHOP to invoke @command{^gnatchop^gnatchop^}
13142 @item CLEAN to invoke @command{^gnatclean^gnatclean^}
13143 @item COMP or COMPILE to invoke the compiler
13144 @ifclear FSFEDITION
13145 @item ELIM to invoke @command{^gnatelim^gnatelim^}
13146 @end ifclear
13147 @item FIND to invoke @command{^gnatfind^gnatfind^}
13148 @item KR or KRUNCH to invoke @command{^gnatkr^gnatkr^}
13149 @item LINK to invoke @command{^gnatlink^gnatlink^}
13150 @item LS or LIST to invoke @command{^gnatls^gnatls^}
13151 @item MAKE to invoke @command{^gnatmake^gnatmake^}
13152 @item NAME to invoke @command{^gnatname^gnatname^}
13153 @item PREP or PREPROCESS to invoke @command{^gnatprep^gnatprep^}
13154 @ifclear FSFEDITION
13155 @item PP or PRETTY to invoke @command{^gnatpp^gnatpp^}
13156 @item METRIC to invoke @command{^gnatmetric^gnatmetric^}
13157 @item STUB to invoke @command{^gnatstub^gnatstub^}
13158 @end ifclear
13159 @item XREF to invoke @command{^gnatxref^gnatxref^}
13160
13161 @end itemize
13162
13163 @noindent
13164 (note that the compiler is invoked using the command
13165 @command{^gnatmake -f -u -c^gnatmake -f -u -c^}).
13166
13167 On non-VMS platforms, between @command{gnat} and the command, two
13168 special switches may be used:
13169
13170 @itemize @bullet
13171 @item @command{-v} to display the invocation of the tool.
13172 @item @command{-dn} to prevent the @command{gnat} driver from removing
13173 the temporary files it has created. These temporary files are
13174 configuration files and temporary file list files.
13175
13176 @end itemize
13177
13178 @noindent
13179 The command may be followed by switches and arguments for the invoked
13180 tool.
13181
13182 @smallexample
13183 gnat bind -C main.ali
13184 gnat ls -a main
13185 gnat chop foo.txt
13186 @end smallexample
13187
13188 @noindent
13189 Switches may also be put in text files, one switch per line, and the text
13190 files may be specified with their path name preceded by '@@'.
13191
13192 @smallexample
13193 gnat bind @@args.txt main.ali
13194 @end smallexample
13195
13196 @noindent
13197 In addition, for commands BIND, COMP or COMPILE, FIND,
13198 @ifclear FSFEDITION
13199 ELIM,
13200 @end ifclear
13201 LS or LIST, LINK,
13202 @ifclear FSFEDITION
13203 METRIC,
13204 PP or PRETTY,
13205 STUB,
13206 @end ifclear
13207 and XREF, the project file related switches
13208 (@option{^-P^/PROJECT_FILE^},
13209 @option{^-X^/EXTERNAL_REFERENCE^} and
13210 @option{^-vP^/MESSAGES_PROJECT_FILE=^x}) may be used in addition to
13211 the switches of the invoking tool.
13212
13213 @ifclear FSFEDITION
13214 When GNAT PP or GNAT PRETTY is used with a project file, but with no source
13215 specified on the command line, it invokes @command{^gnatpp^gnatpp^} with all
13216 the immediate sources of the specified project file.
13217 @end ifclear
13218
13219 @ifclear FSFEDITION
13220 When GNAT METRIC is used with a project file, but with no source
13221 specified on the command line, it invokes @command{^gnatmetric^gnatmetric^}
13222 with all the immediate sources of the specified project file and with
13223 @option{^-d^/DIRECTORY^} with the parameter pointing to the object directory
13224 of the project.
13225 @end ifclear
13226
13227 @ifclear FSFEDITION
13228 In addition, when GNAT PP, GNAT PRETTY or GNAT METRIC is used with
13229 a project file, no source is specified on the command line and
13230 switch ^-U^/ALL_PROJECTS^ is specified on the command line, then
13231 the underlying tool (^gnatpp^gnatpp^ or
13232 ^gnatmetric^gnatmetric^) is invoked for all sources of all projects,
13233 not only for the immediate sources of the main project.
13234 @ifclear vms
13235 (-U stands for Universal or Union of the project files of the project tree)
13236 @end ifclear
13237 @end ifclear
13238
13239 For each of the following commands, there is optionally a corresponding
13240 package in the main project.
13241
13242 @itemize @bullet
13243 @item package @code{Binder} for command BIND (invoking @code{^gnatbind^gnatbind^})
13244
13245 @ifclear FSFEDITION
13246 @item package @code{Check} for command CHECK (invoking
13247 @code{^gnatcheck^gnatcheck^})
13248 @end ifclear
13249
13250 @item package @code{Compiler} for command COMP or COMPILE (invoking the compiler)
13251
13252 @item package @code{Cross_Reference} for command XREF (invoking
13253 @code{^gnatxref^gnatxref^})
13254
13255 @ifclear FSFEDITION
13256 @item package @code{Eliminate} for command ELIM (invoking
13257 @code{^gnatelim^gnatelim^})
13258 @end ifclear
13259
13260 @item package @code{Finder} for command FIND (invoking @code{^gnatfind^gnatfind^})
13261
13262 @item package @code{Gnatls} for command LS or LIST (invoking @code{^gnatls^gnatls^})
13263
13264 @ifclear FSFEDITION
13265 @item package @code{Gnatstub} for command STUB
13266 (invoking @code{^gnatstub^gnatstub^})
13267 @end ifclear
13268
13269 @item package @code{Linker} for command LINK (invoking @code{^gnatlink^gnatlink^})
13270
13271 @ifclear FSFEDITION
13272 @item package @code{Check} for command CHECK
13273 (invoking @code{^gnatcheck^gnatcheck^})
13274 @end ifclear
13275
13276 @ifclear FSFEDITION
13277 @item package @code{Metrics} for command METRIC
13278 (invoking @code{^gnatmetric^gnatmetric^})
13279 @end ifclear
13280
13281 @ifclear FSFEDITION
13282 @item package @code{Pretty_Printer} for command PP or PRETTY
13283 (invoking @code{^gnatpp^gnatpp^})
13284 @end ifclear
13285
13286 @end itemize
13287
13288 @noindent
13289 Package @code{Gnatls} has a unique attribute @code{Switches},
13290 a simple variable with a string list value. It contains ^switches^switches^
13291 for the invocation of @code{^gnatls^gnatls^}.
13292
13293 @smallexample @c projectfile
13294 @group
13295 project Proj1 is
13296 package gnatls is
13297 for Switches
13298 use ("^-a^-a^",
13299 "^-v^-v^");
13300 end gnatls;
13301 end Proj1;
13302 @end group
13303 @end smallexample
13304
13305 @noindent
13306 All other packages have two attribute @code{Switches} and
13307 @code{^Default_Switches^Default_Switches^}.
13308
13309 @code{Switches} is an indexed attribute, indexed by the
13310 source file name, that has a string list value: the ^switches^switches^ to be
13311 used when the tool corresponding to the package is invoked for the specific
13312 source file.
13313
13314 @code{^Default_Switches^Default_Switches^} is an attribute,
13315 indexed by the programming language that has a string list value.
13316 @code{^Default_Switches^Default_Switches^ ("Ada")} contains the
13317 ^switches^switches^ for the invocation of the tool corresponding
13318 to the package, except if a specific @code{Switches} attribute
13319 is specified for the source file.
13320
13321 @smallexample @c projectfile
13322 @group
13323 project Proj is
13324
13325 for Source_Dirs use ("**");
13326
13327 package gnatls is
13328 for Switches use
13329 ("^-a^-a^",
13330 "^-v^-v^");
13331 end gnatls;
13332 @end group
13333 @group
13334
13335 package Compiler is
13336 for ^Default_Switches^Default_Switches^ ("Ada")
13337 use ("^-gnatv^-gnatv^",
13338 "^-gnatwa^-gnatwa^");
13339 end Binder;
13340 @end group
13341 @group
13342
13343 package Binder is
13344 for ^Default_Switches^Default_Switches^ ("Ada")
13345 use ("^-C^-C^",
13346 "^-e^-e^");
13347 end Binder;
13348 @end group
13349 @group
13350
13351 package Linker is
13352 for ^Default_Switches^Default_Switches^ ("Ada")
13353 use ("^-C^-C^");
13354 for Switches ("main.adb")
13355 use ("^-C^-C^",
13356 "^-v^-v^",
13357 "^-v^-v^");
13358 end Linker;
13359 @end group
13360 @group
13361
13362 package Finder is
13363 for ^Default_Switches^Default_Switches^ ("Ada")
13364 use ("^-a^-a^",
13365 "^-f^-f^");
13366 end Finder;
13367 @end group
13368 @group
13369
13370 package Cross_Reference is
13371 for ^Default_Switches^Default_Switches^ ("Ada")
13372 use ("^-a^-a^",
13373 "^-f^-f^",
13374 "^-d^-d^",
13375 "^-u^-u^");
13376 end Cross_Reference;
13377 end Proj;
13378 @end group
13379 @end smallexample
13380
13381 @noindent
13382 With the above project file, commands such as
13383
13384 @smallexample
13385 ^gnat comp -Pproj main^GNAT COMP /PROJECT_FILE=PROJ MAIN^
13386 ^gnat ls -Pproj main^GNAT LIST /PROJECT_FILE=PROJ MAIN^
13387 ^gnat xref -Pproj main^GNAT XREF /PROJECT_FILE=PROJ MAIN^
13388 ^gnat bind -Pproj main.ali^GNAT BIND /PROJECT_FILE=PROJ MAIN.ALI^
13389 ^gnat link -Pproj main.ali^GNAT LINK /PROJECT_FILE=PROJ MAIN.ALI^
13390 @end smallexample
13391
13392 @noindent
13393 will set up the environment properly and invoke the tool with the switches
13394 found in the package corresponding to the tool:
13395 @code{^Default_Switches^Default_Switches^ ("Ada")} for all tools,
13396 except @code{Switches ("main.adb")}
13397 for @code{^gnatlink^gnatlink^}.
13398 @ifclear FSFEDITION
13399 It is also possible to invoke some of the tools,
13400 (@code{^gnatcheck^gnatcheck^},
13401 @code{^gnatmetric^gnatmetric^},
13402 and @code{^gnatpp^gnatpp^})
13403 on a set of project units thanks to the combination of the switches
13404 @option{-P}, @option{-U} and possibly the main unit when one is interested
13405 in its closure. For instance,
13406 @smallexample
13407 gnat metric -Pproj
13408 @end smallexample
13409
13410 @noindent
13411 will compute the metrics for all the immediate units of project
13412 @code{proj}.
13413 @smallexample
13414 gnat metric -Pproj -U
13415 @end smallexample
13416
13417 @noindent
13418 will compute the metrics for all the units of the closure of projects
13419 rooted at @code{proj}.
13420 @smallexample
13421 gnat metric -Pproj -U main_unit
13422 @end smallexample
13423
13424 @noindent
13425 will compute the metrics for the closure of units rooted at
13426 @code{main_unit}. This last possibility relies implicitly
13427 on @command{gnatbind}'s option @option{-R}. But if the argument files for the
13428 tool invoked by the @command{gnat} driver are explicitly specified
13429 either directly or through the tool @option{-files} option, then the tool
13430 is called only for these explicitly specified files.
13431 @end ifclear
13432
13433 @c *****************************************
13434 @c * Cross-referencing tools
13435 @c *****************************************
13436
13437 @node The Cross-Referencing Tools gnatxref and gnatfind
13438 @chapter The Cross-Referencing Tools @code{gnatxref} and @code{gnatfind}
13439 @findex gnatxref
13440 @findex gnatfind
13441
13442 @noindent
13443 The compiler generates cross-referencing information (unless
13444 you set the @samp{-gnatx} switch), which are saved in the @file{.ali} files.
13445 This information indicates where in the source each entity is declared and
13446 referenced. Note that entities in package Standard are not included, but
13447 entities in all other predefined units are included in the output.
13448
13449 Before using any of these two tools, you need to compile successfully your
13450 application, so that GNAT gets a chance to generate the cross-referencing
13451 information.
13452
13453 The two tools @code{gnatxref} and @code{gnatfind} take advantage of this
13454 information to provide the user with the capability to easily locate the
13455 declaration and references to an entity. These tools are quite similar,
13456 the difference being that @code{gnatfind} is intended for locating
13457 definitions and/or references to a specified entity or entities, whereas
13458 @code{gnatxref} is oriented to generating a full report of all
13459 cross-references.
13460
13461 To use these tools, you must not compile your application using the
13462 @option{-gnatx} switch on the @command{gnatmake} command line
13463 (@pxref{The GNAT Make Program gnatmake}). Otherwise, cross-referencing
13464 information will not be generated.
13465
13466 Note: to invoke @code{gnatxref} or @code{gnatfind} with a project file,
13467 use the @code{gnat} driver (see @ref{The GNAT Driver and Project Files}).
13468
13469 @menu
13470 * Switches for gnatxref::
13471 * Switches for gnatfind::
13472 * Project Files for gnatxref and gnatfind::
13473 * Regular Expressions in gnatfind and gnatxref::
13474 * Examples of gnatxref Usage::
13475 * Examples of gnatfind Usage::
13476 @end menu
13477
13478 @node Switches for gnatxref
13479 @section @code{gnatxref} Switches
13480
13481 @noindent
13482 The command invocation for @code{gnatxref} is:
13483 @smallexample
13484 @c $ gnatxref @ovar{switches} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
13485 @c Expanding @ovar macro inline (explanation in macro def comments)
13486 $ gnatxref @r{[}@var{switches}@r{]} @var{sourcefile1} @r{[}@var{sourcefile2} @dots{}@r{]}
13487 @end smallexample
13488
13489 @noindent
13490 where
13491
13492 @table @var
13493 @item sourcefile1
13494 @itemx sourcefile2
13495 identifies the source files for which a report is to be generated. The
13496 ``with''ed units will be processed too. You must provide at least one file.
13497
13498 These file names are considered to be regular expressions, so for instance
13499 specifying @file{source*.adb} is the same as giving every file in the current
13500 directory whose name starts with @file{source} and whose extension is
13501 @file{adb}.
13502
13503 You shouldn't specify any directory name, just base names. @command{gnatxref}
13504 and @command{gnatfind} will be able to locate these files by themselves using
13505 the source path. If you specify directories, no result is produced.
13506
13507 @end table
13508
13509 @noindent
13510 The switches can be:
13511 @table @option
13512 @c !sort!
13513 @item --version
13514 @cindex @option{--version} @command{gnatxref}
13515 Display Copyright and version, then exit disregarding all other options.
13516
13517 @item --help
13518 @cindex @option{--help} @command{gnatxref}
13519 If @option{--version} was not used, display usage, then exit disregarding
13520 all other options.
13521
13522 @item ^-a^/ALL_FILES^
13523 @cindex @option{^-a^/ALL_FILES^} (@command{gnatxref})
13524 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13525 the read-only files found in the library search path. Otherwise, these files
13526 will be ignored. This option can be used to protect Gnat sources or your own
13527 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13528 much faster, and their output much smaller. Read-only here refers to access
13529 or permissions status in the file system for the current user.
13530
13531 @item -aIDIR
13532 @cindex @option{-aIDIR} (@command{gnatxref})
13533 When looking for source files also look in directory DIR. The order in which
13534 source file search is undertaken is the same as for @command{gnatmake}.
13535
13536 @item -aODIR
13537 @cindex @option{-aODIR} (@command{gnatxref})
13538 When searching for library and object files, look in directory
13539 DIR. The order in which library files are searched is the same as for
13540 @command{gnatmake}.
13541
13542 @item -nostdinc
13543 @cindex @option{-nostdinc} (@command{gnatxref})
13544 Do not look for sources in the system default directory.
13545
13546 @item -nostdlib
13547 @cindex @option{-nostdlib} (@command{gnatxref})
13548 Do not look for library files in the system default directory.
13549
13550 @item --ext=@var{extension}
13551 @cindex @option{--ext} (@command{gnatxref})
13552 Specify an alternate ali file extension. The default is @code{ali} and other
13553 extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
13554 may be specified via this switch. Note that if this switch overrides the
13555 default, which means that only the new extension will be considered.
13556
13557 @item --RTS=@var{rts-path}
13558 @cindex @option{--RTS} (@command{gnatxref})
13559 Specifies the default location of the runtime library. Same meaning as the
13560 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13561
13562 @item ^-d^/DERIVED_TYPES^
13563 @cindex @option{^-d^/DERIVED_TYPES^} (@command{gnatxref})
13564 If this switch is set @code{gnatxref} will output the parent type
13565 reference for each matching derived types.
13566
13567 @item ^-f^/FULL_PATHNAME^
13568 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatxref})
13569 If this switch is set, the output file names will be preceded by their
13570 directory (if the file was found in the search path). If this switch is
13571 not set, the directory will not be printed.
13572
13573 @item ^-g^/IGNORE_LOCALS^
13574 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatxref})
13575 If this switch is set, information is output only for library-level
13576 entities, ignoring local entities. The use of this switch may accelerate
13577 @code{gnatfind} and @code{gnatxref}.
13578
13579 @item -IDIR
13580 @cindex @option{-IDIR} (@command{gnatxref})
13581 Equivalent to @samp{-aODIR -aIDIR}.
13582
13583 @item -pFILE
13584 @cindex @option{-pFILE} (@command{gnatxref})
13585 Specify a project file to use @xref{GNAT Project Manager}.
13586 If you need to use the @file{.gpr}
13587 project files, you should use gnatxref through the GNAT driver
13588 (@command{gnat xref -Pproject}).
13589
13590 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13591 project file in the current directory.
13592
13593 If a project file is either specified or found by the tools, then the content
13594 of the source directory and object directory lines are added as if they
13595 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^}
13596 and @samp{^-aO^OBJECT_SEARCH^}.
13597 @item ^-u^/UNUSED^
13598 Output only unused symbols. This may be really useful if you give your
13599 main compilation unit on the command line, as @code{gnatxref} will then
13600 display every unused entity and 'with'ed package.
13601
13602 @ifclear vms
13603 @item -v
13604 Instead of producing the default output, @code{gnatxref} will generate a
13605 @file{tags} file that can be used by vi. For examples how to use this
13606 feature, see @ref{Examples of gnatxref Usage}. The tags file is output
13607 to the standard output, thus you will have to redirect it to a file.
13608 @end ifclear
13609
13610 @end table
13611
13612 @noindent
13613 All these switches may be in any order on the command line, and may even
13614 appear after the file names. They need not be separated by spaces, thus
13615 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13616 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13617
13618 @node Switches for gnatfind
13619 @section @code{gnatfind} Switches
13620
13621 @noindent
13622 The command line for @code{gnatfind} is:
13623
13624 @smallexample
13625 @c $ gnatfind @ovar{switches} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13626 @c @r{[}@var{file1} @var{file2} @dots{}]
13627 @c Expanding @ovar macro inline (explanation in macro def comments)
13628 $ gnatfind @r{[}@var{switches}@r{]} @var{pattern}@r{[}:@var{sourcefile}@r{[}:@var{line}@r{[}:@var{column}@r{]]]}
13629 @r{[}@var{file1} @var{file2} @dots{}@r{]}
13630 @end smallexample
13631
13632 @noindent
13633 where
13634
13635 @table @var
13636 @item pattern
13637 An entity will be output only if it matches the regular expression found
13638 in @var{pattern}, see @ref{Regular Expressions in gnatfind and gnatxref}.
13639
13640 Omitting the pattern is equivalent to specifying @samp{*}, which
13641 will match any entity. Note that if you do not provide a pattern, you
13642 have to provide both a sourcefile and a line.
13643
13644 Entity names are given in Latin-1, with uppercase/lowercase equivalence
13645 for matching purposes. At the current time there is no support for
13646 8-bit codes other than Latin-1, or for wide characters in identifiers.
13647
13648 @item sourcefile
13649 @code{gnatfind} will look for references, bodies or declarations
13650 of symbols referenced in @file{@var{sourcefile}}, at line @var{line}
13651 and column @var{column}. See @ref{Examples of gnatfind Usage}
13652 for syntax examples.
13653
13654 @item line
13655 is a decimal integer identifying the line number containing
13656 the reference to the entity (or entities) to be located.
13657
13658 @item column
13659 is a decimal integer identifying the exact location on the
13660 line of the first character of the identifier for the
13661 entity reference. Columns are numbered from 1.
13662
13663 @item file1 file2 @dots{}
13664 The search will be restricted to these source files. If none are given, then
13665 the search will be done for every library file in the search path.
13666 These file must appear only after the pattern or sourcefile.
13667
13668 These file names are considered to be regular expressions, so for instance
13669 specifying @file{source*.adb} is the same as giving every file in the current
13670 directory whose name starts with @file{source} and whose extension is
13671 @file{adb}.
13672
13673 The location of the spec of the entity will always be displayed, even if it
13674 isn't in one of @file{@var{file1}}, @file{@var{file2}},@enddots{} The
13675 occurrences of the entity in the separate units of the ones given on the
13676 command line will also be displayed.
13677
13678 Note that if you specify at least one file in this part, @code{gnatfind} may
13679 sometimes not be able to find the body of the subprograms.
13680
13681 @end table
13682
13683 @noindent
13684 At least one of 'sourcefile' or 'pattern' has to be present on
13685 the command line.
13686
13687 The following switches are available:
13688 @table @option
13689 @c !sort!
13690
13691 @cindex @option{--version} @command{gnatfind}
13692 Display Copyright and version, then exit disregarding all other options.
13693
13694 @item --help
13695 @cindex @option{--help} @command{gnatfind}
13696 If @option{--version} was not used, display usage, then exit disregarding
13697 all other options.
13698
13699 @item ^-a^/ALL_FILES^
13700 @cindex @option{^-a^/ALL_FILES^} (@command{gnatfind})
13701 If this switch is present, @code{gnatfind} and @code{gnatxref} will parse
13702 the read-only files found in the library search path. Otherwise, these files
13703 will be ignored. This option can be used to protect Gnat sources or your own
13704 libraries from being parsed, thus making @code{gnatfind} and @code{gnatxref}
13705 much faster, and their output much smaller. Read-only here refers to access
13706 or permission status in the file system for the current user.
13707
13708 @item -aIDIR
13709 @cindex @option{-aIDIR} (@command{gnatfind})
13710 When looking for source files also look in directory DIR. The order in which
13711 source file search is undertaken is the same as for @command{gnatmake}.
13712
13713 @item -aODIR
13714 @cindex @option{-aODIR} (@command{gnatfind})
13715 When searching for library and object files, look in directory
13716 DIR. The order in which library files are searched is the same as for
13717 @command{gnatmake}.
13718
13719 @item -nostdinc
13720 @cindex @option{-nostdinc} (@command{gnatfind})
13721 Do not look for sources in the system default directory.
13722
13723 @item -nostdlib
13724 @cindex @option{-nostdlib} (@command{gnatfind})
13725 Do not look for library files in the system default directory.
13726
13727 @item --ext=@var{extension}
13728 @cindex @option{--ext} (@command{gnatfind})
13729 Specify an alternate ali file extension. The default is @code{ali} and other
13730 extensions (e.g. @code{gli} for C/C++ sources when using @option{-fdump-xref})
13731 may be specified via this switch. Note that if this switch overrides the
13732 default, which means that only the new extension will be considered.
13733
13734 @item --RTS=@var{rts-path}
13735 @cindex @option{--RTS} (@command{gnatfind})
13736 Specifies the default location of the runtime library. Same meaning as the
13737 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
13738
13739 @item ^-d^/DERIVED_TYPE_INFORMATION^
13740 @cindex @option{^-d^/DERIVED_TYPE_INFORMATION^} (@code{gnatfind})
13741 If this switch is set, then @code{gnatfind} will output the parent type
13742 reference for each matching derived types.
13743
13744 @item ^-e^/EXPRESSIONS^
13745 @cindex @option{^-e^/EXPRESSIONS^} (@command{gnatfind})
13746 By default, @code{gnatfind} accept the simple regular expression set for
13747 @samp{pattern}. If this switch is set, then the pattern will be
13748 considered as full Unix-style regular expression.
13749
13750 @item ^-f^/FULL_PATHNAME^
13751 @cindex @option{^-f^/FULL_PATHNAME^} (@command{gnatfind})
13752 If this switch is set, the output file names will be preceded by their
13753 directory (if the file was found in the search path). If this switch is
13754 not set, the directory will not be printed.
13755
13756 @item ^-g^/IGNORE_LOCALS^
13757 @cindex @option{^-g^/IGNORE_LOCALS^} (@command{gnatfind})
13758 If this switch is set, information is output only for library-level
13759 entities, ignoring local entities. The use of this switch may accelerate
13760 @code{gnatfind} and @code{gnatxref}.
13761
13762 @item -IDIR
13763 @cindex @option{-IDIR} (@command{gnatfind})
13764 Equivalent to @samp{-aODIR -aIDIR}.
13765
13766 @item -pFILE
13767 @cindex @option{-pFILE} (@command{gnatfind})
13768 Specify a project file (@pxref{GNAT Project Manager}) to use.
13769 By default, @code{gnatxref} and @code{gnatfind} will try to locate a
13770 project file in the current directory.
13771
13772 If a project file is either specified or found by the tools, then the content
13773 of the source directory and object directory lines are added as if they
13774 had been specified respectively by @samp{^-aI^/SOURCE_SEARCH^} and
13775 @samp{^-aO^/OBJECT_SEARCH^}.
13776
13777 @item ^-r^/REFERENCES^
13778 @cindex @option{^-r^/REFERENCES^} (@command{gnatfind})
13779 By default, @code{gnatfind} will output only the information about the
13780 declaration, body or type completion of the entities. If this switch is
13781 set, the @code{gnatfind} will locate every reference to the entities in
13782 the files specified on the command line (or in every file in the search
13783 path if no file is given on the command line).
13784
13785 @item ^-s^/PRINT_LINES^
13786 @cindex @option{^-s^/PRINT_LINES^} (@command{gnatfind})
13787 If this switch is set, then @code{gnatfind} will output the content
13788 of the Ada source file lines were the entity was found.
13789
13790 @item ^-t^/TYPE_HIERARCHY^
13791 @cindex @option{^-t^/TYPE_HIERARCHY^} (@command{gnatfind})
13792 If this switch is set, then @code{gnatfind} will output the type hierarchy for
13793 the specified type. It act like -d option but recursively from parent
13794 type to parent type. When this switch is set it is not possible to
13795 specify more than one file.
13796
13797 @end table
13798
13799 @noindent
13800 All these switches may be in any order on the command line, and may even
13801 appear after the file names. They need not be separated by spaces, thus
13802 you can say @samp{gnatxref ^-ag^/ALL_FILES/IGNORE_LOCALS^} instead of
13803 @samp{gnatxref ^-a -g^/ALL_FILES /IGNORE_LOCALS^}.
13804
13805 As stated previously, gnatfind will search in every directory in the
13806 search path. You can force it to look only in the current directory if
13807 you specify @code{*} at the end of the command line.
13808
13809 @node Project Files for gnatxref and gnatfind
13810 @section Project Files for @command{gnatxref} and @command{gnatfind}
13811
13812 @noindent
13813 Project files allow a programmer to specify how to compile its
13814 application, where to find sources, etc. These files are used
13815 @ifclear vms
13816 primarily by GPS, but they can also be used
13817 @end ifclear
13818 by the two tools
13819 @code{gnatxref} and @code{gnatfind}.
13820
13821 A project file name must end with @file{.gpr}. If a single one is
13822 present in the current directory, then @code{gnatxref} and @code{gnatfind} will
13823 extract the information from it. If multiple project files are found, none of
13824 them is read, and you have to use the @samp{-p} switch to specify the one
13825 you want to use.
13826
13827 The following lines can be included, even though most of them have default
13828 values which can be used in most cases.
13829 The lines can be entered in any order in the file.
13830 Except for @file{src_dir} and @file{obj_dir}, you can only have one instance of
13831 each line. If you have multiple instances, only the last one is taken into
13832 account.
13833
13834 @table @code
13835 @item src_dir=DIR
13836 [default: @code{"^./^[]^"}]
13837 specifies a directory where to look for source files. Multiple @code{src_dir}
13838 lines can be specified and they will be searched in the order they
13839 are specified.
13840
13841 @item obj_dir=DIR
13842 [default: @code{"^./^[]^"}]
13843 specifies a directory where to look for object and library files. Multiple
13844 @code{obj_dir} lines can be specified, and they will be searched in the order
13845 they are specified
13846
13847 @item comp_opt=SWITCHES
13848 [default: @code{""}]
13849 creates a variable which can be referred to subsequently by using
13850 the @code{$@{comp_opt@}} notation. This is intended to store the default
13851 switches given to @command{gnatmake} and @command{gcc}.
13852
13853 @item bind_opt=SWITCHES
13854 [default: @code{""}]
13855 creates a variable which can be referred to subsequently by using
13856 the @samp{$@{bind_opt@}} notation. This is intended to store the default
13857 switches given to @command{gnatbind}.
13858
13859 @item link_opt=SWITCHES
13860 [default: @code{""}]
13861 creates a variable which can be referred to subsequently by using
13862 the @samp{$@{link_opt@}} notation. This is intended to store the default
13863 switches given to @command{gnatlink}.
13864
13865 @item main=EXECUTABLE
13866 [default: @code{""}]
13867 specifies the name of the executable for the application. This variable can
13868 be referred to in the following lines by using the @samp{$@{main@}} notation.
13869
13870 @ifset vms
13871 @item comp_cmd=COMMAND
13872 [default: @code{"GNAT COMPILE /SEARCH=$@{src_dir@} /DEBUG /TRY_SEMANTICS"}]
13873 @end ifset
13874 @ifclear vms
13875 @item comp_cmd=COMMAND
13876 [default: @code{"gcc -c -I$@{src_dir@} -g -gnatq"}]
13877 @end ifclear
13878 specifies the command used to compile a single file in the application.
13879
13880 @ifset vms
13881 @item make_cmd=COMMAND
13882 [default: @code{"GNAT MAKE $@{main@}
13883 /SOURCE_SEARCH=$@{src_dir@} /OBJECT_SEARCH=$@{obj_dir@}
13884 /DEBUG /TRY_SEMANTICS /COMPILER_QUALIFIERS $@{comp_opt@}
13885 /BINDER_QUALIFIERS $@{bind_opt@} /LINKER_QUALIFIERS $@{link_opt@}"}]
13886 @end ifset
13887 @ifclear vms
13888 @item make_cmd=COMMAND
13889 [default: @code{"gnatmake $@{main@} -aI$@{src_dir@}
13890 -aO$@{obj_dir@} -g -gnatq -cargs $@{comp_opt@}
13891 -bargs $@{bind_opt@} -largs $@{link_opt@}"}]
13892 @end ifclear
13893 specifies the command used to recompile the whole application.
13894
13895 @item run_cmd=COMMAND
13896 [default: @code{"$@{main@}"}]
13897 specifies the command used to run the application.
13898
13899 @item debug_cmd=COMMAND
13900 [default: @code{"gdb $@{main@}"}]
13901 specifies the command used to debug the application
13902
13903 @end table
13904
13905 @noindent
13906 @command{gnatxref} and @command{gnatfind} only take into account the
13907 @code{src_dir} and @code{obj_dir} lines, and ignore the others.
13908
13909 @node Regular Expressions in gnatfind and gnatxref
13910 @section Regular Expressions in @code{gnatfind} and @code{gnatxref}
13911
13912 @noindent
13913 As specified in the section about @command{gnatfind}, the pattern can be a
13914 regular expression. Actually, there are to set of regular expressions
13915 which are recognized by the program:
13916
13917 @table @code
13918 @item globbing patterns
13919 These are the most usual regular expression. They are the same that you
13920 generally used in a Unix shell command line, or in a DOS session.
13921
13922 Here is a more formal grammar:
13923 @smallexample
13924 @group
13925 @iftex
13926 @leftskip=.5cm
13927 @end iftex
13928 regexp ::= term
13929 term ::= elmt -- matches elmt
13930 term ::= elmt elmt -- concatenation (elmt then elmt)
13931 term ::= * -- any string of 0 or more characters
13932 term ::= ? -- matches any character
13933 term ::= [char @{char@}] -- matches any character listed
13934 term ::= [char - char] -- matches any character in range
13935 @end group
13936 @end smallexample
13937
13938 @item full regular expression
13939 The second set of regular expressions is much more powerful. This is the
13940 type of regular expressions recognized by utilities such a @file{grep}.
13941
13942 The following is the form of a regular expression, expressed in Ada
13943 reference manual style BNF is as follows
13944
13945 @smallexample
13946 @iftex
13947 @leftskip=.5cm
13948 @end iftex
13949 @group
13950 regexp ::= term @{| term@} -- alternation (term or term @dots{})
13951
13952 term ::= item @{item@} -- concatenation (item then item)
13953
13954 item ::= elmt -- match elmt
13955 item ::= elmt * -- zero or more elmt's
13956 item ::= elmt + -- one or more elmt's
13957 item ::= elmt ? -- matches elmt or nothing
13958 @end group
13959 @group
13960 elmt ::= nschar -- matches given character
13961 elmt ::= [nschar @{nschar@}] -- matches any character listed
13962 elmt ::= [^^^ nschar @{nschar@}] -- matches any character not listed
13963 elmt ::= [char - char] -- matches chars in given range
13964 elmt ::= \ char -- matches given character
13965 elmt ::= . -- matches any single character
13966 elmt ::= ( regexp ) -- parens used for grouping
13967
13968 char ::= any character, including special characters
13969 nschar ::= any character except ()[].*+?^^^
13970 @end group
13971 @end smallexample
13972
13973 Following are a few examples:
13974
13975 @table @samp
13976 @item abcde|fghi
13977 will match any of the two strings @samp{abcde} and @samp{fghi},
13978
13979 @item abc*d
13980 will match any string like @samp{abd}, @samp{abcd}, @samp{abccd},
13981 @samp{abcccd}, and so on,
13982
13983 @item [a-z]+
13984 will match any string which has only lowercase characters in it (and at
13985 least one character.
13986
13987 @end table
13988 @end table
13989
13990 @node Examples of gnatxref Usage
13991 @section Examples of @code{gnatxref} Usage
13992
13993 @subsection General Usage
13994
13995 @noindent
13996 For the following examples, we will consider the following units:
13997
13998 @smallexample @c ada
13999 @group
14000 @cartouche
14001 main.ads:
14002 1: with Bar;
14003 2: package Main is
14004 3: procedure Foo (B : in Integer);
14005 4: C : Integer;
14006 5: private
14007 6: D : Integer;
14008 7: end Main;
14009
14010 main.adb:
14011 1: package body Main is
14012 2: procedure Foo (B : in Integer) is
14013 3: begin
14014 4: C := B;
14015 5: D := B;
14016 6: Bar.Print (B);
14017 7: Bar.Print (C);
14018 8: end Foo;
14019 9: end Main;
14020
14021 bar.ads:
14022 1: package Bar is
14023 2: procedure Print (B : Integer);
14024 3: end bar;
14025 @end cartouche
14026 @end group
14027 @end smallexample
14028
14029 @table @code
14030
14031 @noindent
14032 The first thing to do is to recompile your application (for instance, in
14033 that case just by doing a @samp{gnatmake main}, so that GNAT generates
14034 the cross-referencing information.
14035 You can then issue any of the following commands:
14036
14037 @item gnatxref main.adb
14038 @code{gnatxref} generates cross-reference information for main.adb
14039 and every unit 'with'ed by main.adb.
14040
14041 The output would be:
14042 @smallexample
14043 @iftex
14044 @leftskip=0cm
14045 @end iftex
14046 B Type: Integer
14047 Decl: bar.ads 2:22
14048 B Type: Integer
14049 Decl: main.ads 3:20
14050 Body: main.adb 2:20
14051 Ref: main.adb 4:13 5:13 6:19
14052 Bar Type: Unit
14053 Decl: bar.ads 1:9
14054 Ref: main.adb 6:8 7:8
14055 main.ads 1:6
14056 C Type: Integer
14057 Decl: main.ads 4:5
14058 Modi: main.adb 4:8
14059 Ref: main.adb 7:19
14060 D Type: Integer
14061 Decl: main.ads 6:5
14062 Modi: main.adb 5:8
14063 Foo Type: Unit
14064 Decl: main.ads 3:15
14065 Body: main.adb 2:15
14066 Main Type: Unit
14067 Decl: main.ads 2:9
14068 Body: main.adb 1:14
14069 Print Type: Unit
14070 Decl: bar.ads 2:15
14071 Ref: main.adb 6:12 7:12
14072 @end smallexample
14073
14074 @noindent
14075 that is the entity @code{Main} is declared in main.ads, line 2, column 9,
14076 its body is in main.adb, line 1, column 14 and is not referenced any where.
14077
14078 The entity @code{Print} is declared in bar.ads, line 2, column 15 and it
14079 is referenced in main.adb, line 6 column 12 and line 7 column 12.
14080
14081 @item gnatxref package1.adb package2.ads
14082 @code{gnatxref} will generates cross-reference information for
14083 package1.adb, package2.ads and any other package 'with'ed by any
14084 of these.
14085
14086 @end table
14087
14088 @ifclear vms
14089 @subsection Using gnatxref with vi
14090
14091 @code{gnatxref} can generate a tags file output, which can be used
14092 directly from @command{vi}. Note that the standard version of @command{vi}
14093 will not work properly with overloaded symbols. Consider using another
14094 free implementation of @command{vi}, such as @command{vim}.
14095
14096 @smallexample
14097 $ gnatxref -v gnatfind.adb > tags
14098 @end smallexample
14099
14100 @noindent
14101 will generate the tags file for @code{gnatfind} itself (if the sources
14102 are in the search path!).
14103
14104 From @command{vi}, you can then use the command @samp{:tag @var{entity}}
14105 (replacing @var{entity} by whatever you are looking for), and vi will
14106 display a new file with the corresponding declaration of entity.
14107 @end ifclear
14108
14109 @node Examples of gnatfind Usage
14110 @section Examples of @code{gnatfind} Usage
14111
14112 @table @code
14113
14114 @item gnatfind ^-f^/FULL_PATHNAME^ xyz:main.adb
14115 Find declarations for all entities xyz referenced at least once in
14116 main.adb. The references are search in every library file in the search
14117 path.
14118
14119 The directories will be printed as well (as the @samp{^-f^/FULL_PATHNAME^}
14120 switch is set)
14121
14122 The output will look like:
14123 @smallexample
14124 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14125 ^directory/^[directory]^main.adb:24:10: xyz <= body
14126 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14127 @end smallexample
14128
14129 @noindent
14130 that is to say, one of the entities xyz found in main.adb is declared at
14131 line 12 of main.ads (and its body is in main.adb), and another one is
14132 declared at line 45 of foo.ads
14133
14134 @item gnatfind ^-fs^/FULL_PATHNAME/SOURCE_LINE^ xyz:main.adb
14135 This is the same command as the previous one, instead @code{gnatfind} will
14136 display the content of the Ada source file lines.
14137
14138 The output will look like:
14139
14140 @smallexample
14141 ^directory/^[directory]^main.ads:106:14: xyz <= declaration
14142 procedure xyz;
14143 ^directory/^[directory]^main.adb:24:10: xyz <= body
14144 procedure xyz is
14145 ^directory/^[directory]^foo.ads:45:23: xyz <= declaration
14146 xyz : Integer;
14147 @end smallexample
14148
14149 @noindent
14150 This can make it easier to find exactly the location your are looking
14151 for.
14152
14153 @item gnatfind ^-r^/REFERENCES^ "*x*":main.ads:123 foo.adb
14154 Find references to all entities containing an x that are
14155 referenced on line 123 of main.ads.
14156 The references will be searched only in main.ads and foo.adb.
14157
14158 @item gnatfind main.ads:123
14159 Find declarations and bodies for all entities that are referenced on
14160 line 123 of main.ads.
14161
14162 This is the same as @code{gnatfind "*":main.adb:123}.
14163
14164 @item gnatfind ^mydir/^[mydir]^main.adb:123:45
14165 Find the declaration for the entity referenced at column 45 in
14166 line 123 of file main.adb in directory mydir. Note that it
14167 is usual to omit the identifier name when the column is given,
14168 since the column position identifies a unique reference.
14169
14170 The column has to be the beginning of the identifier, and should not
14171 point to any character in the middle of the identifier.
14172
14173 @end table
14174
14175 @ifclear FSFEDITION
14176 @c *********************************
14177 @node The GNAT Pretty-Printer gnatpp
14178 @chapter The GNAT Pretty-Printer @command{gnatpp}
14179 @findex gnatpp
14180 @cindex Pretty-Printer
14181
14182 @menu
14183 * Switches for gnatpp::
14184 * Formatting Rules::
14185 @end menu
14186
14187 @noindent
14188 ^The @command{gnatpp} tool^GNAT PRETTY^ is an ASIS-based utility
14189 for source reformatting / pretty-printing.
14190 It takes an Ada source file as input and generates a reformatted
14191 version as output.
14192 You can specify various style directives via switches; e.g.,
14193 identifier case conventions, rules of indentation, and comment layout.
14194
14195 Note: A newly-redesigned set of formatting algorithms used by gnatpp
14196 is now available.
14197 To invoke the old formatting algorithms, use the @option{--pp-old} switch.
14198 Support for @option{--pp-old} will be removed in some future version.
14199
14200 To produce a reformatted file, @command{gnatpp} invokes the Ada
14201 compiler and generates and uses the ASIS tree for the input source;
14202 thus the input must be legal Ada code, and the tool should have all the
14203 information needed to compile the input source. To provide this information,
14204 you may specify as a tool parameter the project file the input source belongs to
14205 (or you may call @command{gnatpp}
14206 through the @command{gnat} driver (see @ref{The GNAT Driver and
14207 Project Files}). Another possibility is to specify the source search
14208 path and needed configuration files in @option{-cargs} section of @command{gnatpp}
14209 call, see the description of the @command{gnatpp} switches below.
14210
14211 @command{gnatpp} cannot process sources that contain
14212 preprocessing directives.
14213
14214 The @command{gnatpp} command has the form
14215
14216 @smallexample
14217 @c $ gnatpp @ovar{switches} @var{filename}
14218 @c Expanding @ovar macro inline (explanation in macro def comments)
14219 $ gnatpp @r{[}@var{switches}@r{]} @var{filename} @r{[}-cargs @var{gcc_switches}@r{]}
14220 @end smallexample
14221
14222 @noindent
14223 where
14224 @itemize @bullet
14225 @item
14226 @var{switches} is an optional sequence of switches defining such properties as
14227 the formatting rules, the source search path, and the destination for the
14228 output source file
14229
14230 @item
14231 @var{filename} is the name (including the extension) of the source file to
14232 reformat; wildcards or several file names on the same gnatpp command are
14233 allowed. The file name may contain path information; it does not have to
14234 follow the GNAT file naming rules
14235
14236 @item
14237 @samp{@var{gcc_switches}} is a list of switches for
14238 @command{gcc}. They will be passed on to all compiler invocations made by
14239 @command{gnatpp} to generate the ASIS trees. Here you can provide
14240 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
14241 use the @option{-gnatec} switch to set the configuration file, etc.
14242 @end itemize
14243
14244 @node Switches for gnatpp
14245 @section Switches for @command{gnatpp}
14246
14247 @noindent
14248 The following subsections describe the various switches accepted by
14249 @command{gnatpp}, organized by category.
14250
14251 @ifclear vms
14252 You specify a switch by supplying a name and generally also a value.
14253 In many cases the values for a switch with a given name are incompatible with
14254 each other
14255 (for example the switch that controls the casing of a reserved word may have
14256 exactly one value: upper case, lower case, or
14257 mixed case) and thus exactly one such switch can be in effect for an
14258 invocation of @command{gnatpp}.
14259 If more than one is supplied, the last one is used.
14260 However, some values for the same switch are mutually compatible.
14261 You may supply several such switches to @command{gnatpp}, but then
14262 each must be specified in full, with both the name and the value.
14263 Abbreviated forms (the name appearing once, followed by each value) are
14264 not permitted.
14265 @end ifclear
14266
14267 @ifset vms
14268 In many cases the set of options for a given qualifier are incompatible with
14269 each other (for example the qualifier that controls the casing of a reserved
14270 word may have exactly one option, which specifies either upper case, lower
14271 case, or mixed case), and thus exactly one such option can be in effect for
14272 an invocation of @command{gnatpp}.
14273 If more than one is supplied, the last one is used.
14274 @end ifset
14275
14276 @menu
14277 * Alignment Control::
14278 * Casing Control::
14279 * General Text Layout Control::
14280 * Other Formatting Options::
14281 * Setting the Source Search Path::
14282 * Output File Control::
14283 * Other gnatpp Switches::
14284 @end menu
14285
14286 @node Alignment Control
14287 @subsection Alignment Control
14288 @cindex Alignment control in @command{gnatpp}
14289
14290 @noindent
14291 Programs can be easier to read if certain constructs are vertically aligned.
14292 By default alignment of the following constructs is set ON:
14293 @code{:} in declarations, @code{:=} in initializations in declarations
14294 @code{:=} in assignment statements, @code{=>} in associations, and
14295 @code{at} keywords in the component clauses in record
14296 representation clauses.
14297
14298 @table @option
14299 @cindex @option{^-A@var{n}^/ALIGN^} (@command{gnatpp})
14300
14301 @item ^-A0^/ALIGN=OFF^
14302 Set alignment to OFF
14303
14304 @item ^-A1^/ALIGN=ON^
14305 Set alignment to ON
14306 @end table
14307
14308 @node Casing Control
14309 @subsection Casing Control
14310 @cindex Casing control in @command{gnatpp}
14311
14312 @noindent
14313 @command{gnatpp} allows you to specify the casing for reserved words,
14314 pragma names, attribute designators and identifiers.
14315 For identifiers you may define a
14316 general rule for name casing but also override this rule
14317 via a set of dictionary files.
14318
14319 Three types of casing are supported: lower case, upper case, and mixed case.
14320 ``Mixed case'' means that the first letter, and also each letter immediately
14321 following an underscore, are converted to their uppercase forms;
14322 all the other letters are converted to their lowercase forms.
14323
14324 @table @option
14325 @cindex @option{^-a@var{x}^/ATTRIBUTE^} (@command{gnatpp})
14326 @item ^-aL^/ATTRIBUTE_CASING=LOWER_CASE^
14327 Attribute designators are lower case
14328
14329 @item ^-aU^/ATTRIBUTE_CASING=UPPER_CASE^
14330 Attribute designators are upper case
14331
14332 @item ^-aM^/ATTRIBUTE_CASING=MIXED_CASE^
14333 Attribute designators are mixed case (this is the default)
14334
14335 @cindex @option{^-k@var{x}^/KEYWORD_CASING^} (@command{gnatpp})
14336 @item ^-kL^/KEYWORD_CASING=LOWER_CASE^
14337 Keywords (technically, these are known in Ada as @emph{reserved words}) are
14338 lower case (this is the default)
14339
14340 @item ^-kU^/KEYWORD_CASING=UPPER_CASE^
14341 Keywords are upper case
14342
14343 @cindex @option{^-n@var{x}^/NAME_CASING^} (@command{gnatpp})
14344 @item ^-nD^/NAME_CASING=AS_DECLARED^
14345 Name casing for defining occurrences are as they appear in the source file
14346 (this is the default)
14347
14348 @item ^-nU^/NAME_CASING=UPPER_CASE^
14349 Names are in upper case
14350
14351 @item ^-nL^/NAME_CASING=LOWER_CASE^
14352 Names are in lower case
14353
14354 @item ^-nM^/NAME_CASING=MIXED_CASE^
14355 Names are in mixed case
14356
14357 @cindex @option{^-ne@var{x}^/ENUM_CASING^} (@command{gnatpp})
14358 @item ^-neD^/ENUM_CASING=AS_DECLARED^
14359 Enumeration literal casing for defining occurrences are as they appear in the
14360 source file. Overrides ^-n^/NAME_CASING^ casing setting.
14361
14362 @item ^-neU^/ENUM_CASING=UPPER_CASE^
14363 Enumeration literals are in upper case. Overrides ^-n^/NAME_CASING^ casing
14364 setting.
14365
14366 @item ^-neL^/ENUM_CASING=LOWER_CASE^
14367 Enumeration literals are in lower case. Overrides ^-n^/NAME_CASING^ casing
14368 setting.
14369
14370 @item ^-neM^/ENUM_CASING=MIXED_CASE^
14371 Enumeration literals are in mixed case. Overrides ^-n^/NAME_CASING^ casing
14372 setting.
14373
14374 @cindex @option{^-nt@var{x}^/TYPE_CASING^} (@command{gnatpp})
14375 @item ^-neD^/TYPE_CASING=AS_DECLARED^
14376 Names introduced by type and subtype declarations are always
14377 cased as they appear in the declaration in the source file.
14378 Overrides ^-n^/NAME_CASING^ casing setting.
14379
14380 @item ^-ntU^/TYPE_CASING=UPPER_CASE^
14381 Names introduced by type and subtype declarations are always in
14382 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
14383
14384 @item ^-ntL^/TYPE_CASING=LOWER_CASE^
14385 Names introduced by type and subtype declarations are always in
14386 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
14387
14388 @item ^-ntM^/TYPE_CASING=MIXED_CASE^
14389 Names introduced by type and subtype declarations are always in
14390 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
14391
14392 @item ^-nnU^/NUMBER_CASING=UPPER_CASE^
14393 Names introduced by number declarations are always in
14394 upper case. Overrides ^-n^/NAME_CASING^ casing setting.
14395
14396 @item ^-nnL^/NUMBER_CASING=LOWER_CASE^
14397 Names introduced by number declarations are always in
14398 lower case. Overrides ^-n^/NAME_CASING^ casing setting.
14399
14400 @item ^-nnM^/NUMBER_CASING=MIXED_CASE^
14401 Names introduced by number declarations are always in
14402 mixed case. Overrides ^-n^/NAME_CASING^ casing setting.
14403
14404 @cindex @option{^-p@var{x}^/PRAGMA_CASING^} (@command{gnatpp})
14405 @item ^-pL^/PRAGMA_CASING=LOWER_CASE^
14406 Pragma names are lower case
14407
14408 @item ^-pU^/PRAGMA_CASING=UPPER_CASE^
14409 Pragma names are upper case
14410
14411 @item ^-pM^/PRAGMA_CASING=MIXED_CASE^
14412 Pragma names are mixed case (this is the default)
14413
14414 @item ^-D@var{file}^/DICTIONARY=@var{file}^
14415 @cindex @option{^-D^/DICTIONARY^} (@command{gnatpp})
14416 Use @var{file} as a @emph{dictionary file} that defines
14417 the casing for a set of specified names,
14418 thereby overriding the effect on these names by
14419 any explicit or implicit
14420 ^-n^/NAME_CASING^ switch.
14421 To supply more than one dictionary file,
14422 use ^several @option{-D} switches^a list of files as options^.
14423
14424 @noindent
14425 @option{gnatpp} implicitly uses a @emph{default dictionary file}
14426 to define the casing for the Ada predefined names and
14427 the names declared in the GNAT libraries.
14428
14429 @item ^-D-^/SPECIFIC_CASING^
14430 @cindex @option{^-D-^/SPECIFIC_CASING^} (@command{gnatpp})
14431 Do not use the default dictionary file;
14432 instead, use the casing
14433 defined by a @option{^-n^/NAME_CASING^} switch and any explicit
14434 dictionary file(s)
14435 @end table
14436
14437 @noindent
14438 The structure of a dictionary file, and details on the conventions
14439 used in the default dictionary file, are defined in @ref{Name Casing}.
14440
14441 The @option{^-D-^/SPECIFIC_CASING^} and
14442 @option{^-D@var{file}^/DICTIONARY=@var{file}^} switches are mutually
14443 compatible.
14444
14445 @noindent
14446 This group of @command{gnatpp} switches controls the layout of comments and
14447 complex syntactic constructs. See @ref{Formatting Comments} for details
14448 on their effect.
14449
14450 @table @option
14451 @cindex @option{^-c@var{n}^/COMMENTS_LAYOUT^} (@command{gnatpp})
14452 @item ^-c0^/COMMENTS_LAYOUT=UNTOUCHED^
14453 All comments remain unchanged.
14454
14455 @item ^-c1^/COMMENTS_LAYOUT=DEFAULT^
14456 GNAT-style comment line indentation.
14457 This is the default.
14458
14459 @item ^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^
14460 GNAT-style comment beginning.
14461
14462 @item ^-c4^/COMMENTS_LAYOUT=REFORMAT^
14463 Fill comment blocks.
14464
14465 @item ^-c5^/COMMENTS_LAYOUT=KEEP_SPECIAL^
14466 Keep unchanged special form comments.
14467 This is the default.
14468
14469 @item --comments-only
14470 @cindex @option{--comments-only} @command{gnatpp}
14471 Format just the comments.
14472
14473 @cindex @option{^--no-separate-is^/NO_SEPARATE_IS^} (@command{gnatpp})
14474 @item ^--no-separate-is^/NO_SEPARATE_IS^
14475 Do not place the keyword @code{is} on a separate line in a subprogram body in
14476 case if the spec occupies more than one line.
14477
14478 @cindex @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} (@command{gnatpp})
14479 @item ^--separate-loop-then^/SEPARATE_LOOP_THEN^
14480 Place the keyword @code{loop} in FOR and WHILE loop statements and the
14481 keyword @code{then} in IF statements on a separate line.
14482
14483 @cindex @option{^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^} (@command{gnatpp})
14484 @item ^--no-separate-loop-then^/NO_SEPARATE_LOOP_THEN^
14485 Do not place the keyword @code{loop} in FOR and WHILE loop statements and the
14486 keyword @code{then} in IF statements on a separate line. This option is
14487 incompatible with @option{^--separate-loop-then^/SEPARATE_LOOP_THEN^} option.
14488
14489 @cindex @option{^--use-on-new-line^/USE_ON_NEW_LINE^} (@command{gnatpp})
14490 @item ^--use-on-new-line^/USE_ON_NEW_LINE^
14491 Start each USE clause in a context clause from a separate line.
14492
14493 @cindex @option{^--insert-blank-lines^/INSERT_BLANK_LINES^} (@command{gnatpp})
14494 @item ^--insert-blank-lines^/INSERT_BLANK_LINES^
14495 Insert blank lines where appropriate (between bodies and other large
14496 constructs).
14497
14498 @cindex @option{^--preserve-blank-lines^/PRESERVE_BLANK_LINES^} (@command{gnatpp})
14499 @item ^--preserve-blank-lines^/PRESERVE_BLANK_LINES^
14500 Preserve blank lines in the input. By default, gnatpp will squeeze
14501 multiple blank lines down to one.
14502
14503 @end table
14504
14505 @ifclear vms
14506 @noindent
14507 The @option{-c} switches are compatible with one another, except that
14508 the @option{-c0} switch disables all other comment formatting
14509 switches.
14510 @end ifclear
14511
14512 @ifset vms
14513 @noindent
14514 For the @option{/COMMENTS_LAYOUT} qualifier,
14515 The @option{GNAT_BEGINNING}, @option{REFORMAT}, and @option{DEFAULT}
14516 options are compatible with one another.
14517 @end ifset
14518
14519 @node General Text Layout Control
14520 @subsection General Text Layout Control
14521
14522 @noindent
14523 These switches allow control over line length and indentation.
14524
14525 @table @option
14526 @item ^-M@var{nnn}^/LINE_LENGTH_MAX=@var{nnn}^
14527 @cindex @option{^-M^/LINE_LENGTH^} (@command{gnatpp})
14528 Maximum line length, @var{nnn} from 32@dots{}256, the default value is 79
14529
14530 @item ^-i@var{nnn}^/INDENTATION_LEVEL=@var{nnn}^
14531 @cindex @option{^-i^/INDENTATION_LEVEL^} (@command{gnatpp})
14532 Indentation level, @var{nnn} from 1@dots{}9, the default value is 3
14533
14534 @item ^-cl@var{nnn}^/CONTINUATION_INDENT=@var{nnn}^
14535 @cindex @option{^-cl^/CONTINUATION_INDENT^} (@command{gnatpp})
14536 Indentation level for continuation lines (relative to the line being
14537 continued), @var{nnn} from 1@dots{}9.
14538 The default
14539 value is one less than the (normal) indentation level, unless the
14540 indentation is set to 1 (in which case the default value for continuation
14541 line indentation is also 1)
14542 @end table
14543
14544 @node Other Formatting Options
14545 @subsection Other Formatting Options
14546
14547 @noindent
14548 These switches control other formatting not listed above.
14549
14550 @table @option
14551 @item --decimal-grouping=@var{n}
14552 @cindex @option{--decimal-grouping} @command{gnatpp}
14553 Put underscores in decimal literals (numeric literals without a base)
14554 every @var{n} characters. If a literal already has one or more
14555 underscores, it is not modified. For example, with
14556 @code{--decimal-grouping=3}, @code{1000000} will be changed to
14557 @code{1_000_000}.
14558
14559 @item --based-grouping=@var{n}
14560 @cindex @option{--based-grouping} @command{gnatpp}
14561 Same as @code{--decimal-grouping}, but for based literals. For
14562 example, with @code{--based-grouping=4}, @code{16#0001FFFE#} will be
14563 changed to @code{16#0001_FFFE#}.
14564
14565 @item ^--RM-style-spacing^/RM_STYLE_SPACING^
14566 @cindex @option{^--RM-style-spacing^/RM_STYLE_SPACING^} (@command{gnatpp})
14567 Do not insert an extra blank before various occurrences of
14568 `(' and `:'. This also turns off alignment.
14569
14570 @item ^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^
14571 @cindex @option{^-ff^/FORM_FEED_AFTER_PRAGMA_PAGE^} (@command{gnatpp})
14572 Insert a Form Feed character after a pragma Page.
14573
14574 @item ^--call_threshold=@var{nnn}^/MAX_ACT=@var{nnn}^
14575 @cindex @option{^--call_threshold^/MAX_ACT^} (@command{gnatpp})
14576 If the number of parameter associations is greater than @var{nnn} and if at
14577 least one association uses named notation, start each association from
14578 a new line. If @var{nnn} is 0, no check for the number of associations
14579 is made; this is the default.
14580
14581 @item ^--par_threshold=@var{nnn}^/MAX_PAR=@var{nnn}^
14582 @cindex @option{^--par_threshold^/MAX_PAR^} (@command{gnatpp})
14583 If the number of parameter specifications is greater than @var{nnn}
14584 (or equal to @var{nnn} in case of a function), start each specification from
14585 a new line. This feature is disabled by default.
14586 @end table
14587
14588 @node Setting the Source Search Path
14589 @subsection Setting the Source Search Path
14590
14591 @noindent
14592 To define the search path for the input source file, @command{gnatpp}
14593 uses the same switches as the GNAT compiler, with the same effects:
14594
14595 @table @option
14596 @item ^-I^/SEARCH=^@var{dir}
14597 @cindex @option{^-I^/SEARCH^} (@command{gnatpp})
14598
14599 @item ^-I-^/NOCURRENT_DIRECTORY^
14600 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@command{gnatpp})
14601
14602 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE^=@var{path}
14603 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatpp})
14604
14605 @item ^--RTS^/RUNTIME_SYSTEM^=@var{path}
14606 @cindex @option{^--RTS^/RUNTIME_SYSTEM^} (@command{gnatpp})
14607
14608 @end table
14609
14610 @node Output File Control
14611 @subsection Output File Control
14612
14613 @noindent
14614 By default the output is sent to a file whose name is obtained by appending
14615 the ^@file{.pp}^@file{$PP}^ suffix to the name of the input file.
14616 If the file with this name already exists, it is overwritten.
14617 Thus if the input file is @file{^my_ada_proc.adb^MY_ADA_PROC.ADB^} then
14618 @command{gnatpp} will produce @file{^my_ada_proc.adb.pp^MY_ADA_PROC.ADB$PP^}
14619 as output file.
14620 The output may be redirected by the following switches:
14621
14622 @table @option
14623 @item ^--output-dir=@var{dir}^/OUTPUT_DIR=@var{dir}^
14624 @cindex @option{^--output-dir^/OUTPUT_DIR^} (@command{gnatpp})
14625 Generate output file in directory @file{dir} with the same name as the input
14626 file. If @file{dir} is the same as the directory containing the input file,
14627 the input file is not processed; use @option{^-rnb^/REPLACE_NO_BACKUP^}
14628 if you want to update the input file in place.
14629
14630 @item ^-pipe^/STANDARD_OUTPUT^
14631 @cindex @option{^-pipe^/STANDARD_OUTPUT^} (@command{gnatpp})
14632 Send the output to @code{Standard_Output}
14633
14634 @item ^-o @var{output_file}^/OUTPUT=@var{output_file}^
14635 @cindex @option{^-o^/OUTPUT^} (@code{gnatpp})
14636 Write the output into @var{output_file}.
14637 If @var{output_file} already exists, @command{gnatpp} terminates without
14638 reading or processing the input file.
14639
14640 @item ^-of ^/FORCED_OUTPUT=^@var{output_file}
14641 @cindex @option{^-of^/FORCED_OUTPUT^} (@command{gnatpp})
14642 Write the output into @var{output_file}, overwriting the existing file
14643 (if one is present).
14644
14645 @item ^-r^/REPLACE^
14646 @cindex @option{^-r^/REPLACE^} (@command{gnatpp})
14647 Replace the input source file with the reformatted output, and copy the
14648 original input source into the file whose name is obtained by appending the
14649 ^@file{.npp}^@file{$NPP}^ suffix to the name of the input file.
14650 If a file with this name already exists, @command{gnatpp} terminates without
14651 reading or processing the input file.
14652
14653 @item ^-rf^/OVERRIDING_REPLACE^
14654 @cindex @option{^-rf^/OVERRIDING_REPLACE^} (@code{gnatpp})
14655 Like @option{^-r^/REPLACE^} except that if the file with the specified name
14656 already exists, it is overwritten.
14657
14658 @item ^-rnb^/REPLACE_NO_BACKUP^
14659 @cindex @option{^-rnb^/REPLACE_NO_BACKUP^} (@command{gnatpp})
14660 Replace the input source file with the reformatted output without
14661 creating any backup copy of the input source.
14662
14663 @item ^--eol=@var{xxx}^/END_OF_LINE=@var{xxx}^
14664 @cindex @option{^--eol^/END_OF_LINE^} (@code{gnatpp})
14665 Specifies the line-ending style of the reformatted output file. The @var{xxx}
14666 ^string specified with the switch^option^ may be:
14667 @itemize @bullet
14668 @item ``@option{^dos^DOS^}'' MS DOS style, lines end with CR LF characters
14669 @item ``@option{^crlf^CRLF^}''
14670 the same as @option{^dos^DOS^}
14671 @item ``@option{^unix^UNIX^}'' UNIX style, lines end with LF character
14672 @item ``@option{^lf^LF^}''
14673 the same as @option{^unix^UNIX^}
14674 @end itemize
14675
14676 @item ^-W^/RESULT_ENCODING=^@var{e}
14677 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatpp})
14678 Specify the wide character encoding method for the input and output files.
14679 @var{e} is one of the following:
14680
14681 @itemize @bullet
14682
14683 @item ^h^HEX^
14684 Hex encoding
14685
14686 @item ^u^UPPER^
14687 Upper half encoding
14688
14689 @item ^s^SHIFT_JIS^
14690 Shift/JIS encoding
14691
14692 @item ^e^EUC^
14693 EUC encoding
14694
14695 @item ^8^UTF8^
14696 UTF-8 encoding
14697
14698 @item ^b^BRACKETS^
14699 Brackets encoding (default value)
14700 @end itemize
14701
14702 @end table
14703
14704 @noindent
14705 Options @option{^-o^/OUTPUT^} and
14706 @option{^-of^/FORCED_OUTPUT^} are allowed only if the call to gnatpp
14707 contains only one file to reformat.
14708 Option
14709 @option{^--eol^/END_OF_LINE^}
14710 and
14711 @option{^-W^/RESULT_ENCODING^}
14712 cannot be used together
14713 with @option{^-pipe^/STANDARD_OUTPUT^} option.
14714
14715 @node Other gnatpp Switches
14716 @subsection Other @code{gnatpp} Switches
14717
14718 @noindent
14719 The additional @command{gnatpp} switches are defined in this subsection.
14720
14721 @table @option
14722 @item --version
14723 @cindex @option{--version} @command{gnatpp}
14724 Display copyright and version, then exit disregarding all other options.
14725
14726 @item --help
14727 @cindex @option{--help} @command{gnatpp}
14728 Display usage, then exit disregarding all other options.
14729
14730 @item -P @var{file}
14731 @cindex @option{-P} @command{gnatpp}
14732 Indicates the name of the project file that describes the set of sources
14733 to be processed. The exact set of argument sources depends on other options
14734 specified; see below.
14735
14736 @item -U
14737 @cindex @option{-U} @command{gnatpp}
14738 If a project file is specified and no argument source is explicitly
14739 specified (either directly or by means of @option{-files} option), process
14740 all the units of the closure of the argument project. Otherwise this option
14741 has no effect.
14742
14743 @item -U @var{main_unit}
14744 If a project file is specified and no argument source is explicitly
14745 specified (either directly or by means of @option{-files} option), process
14746 the closure of units rooted at @var{main_unit}. Otherwise this option
14747 has no effect.
14748
14749 @item -X@var{name}=@var{value}
14750 @cindex @option{-X} @command{gnatpp}
14751 Indicates that external variable @var{name} in the argument project
14752 has the value @var{value}. Has no effect if no project is specified as
14753 tool argument.
14754
14755 @item --incremental
14756 @cindex @option{--incremental} @command{gnatpp}
14757 Incremental processing on a per-file basis. Source files are only
14758 processed if they have been modified, or if files they depend on have
14759 been modified. This is similar to the way gnatmake/gprbuild only
14760 compiles files that need to be recompiled.
14761
14762 @item --pp-off=@var{xxx}
14763 @cindex @option{--pp-off} @command{gnatpp}
14764 Use @code{--xxx} as the command to turn off pretty printing, instead
14765 of the default @code{--!pp off}.
14766
14767 @item --pp-on=@var{xxx}
14768 @cindex @option{--pp-on} @command{gnatpp}
14769 Use @code{--xxx} as the command to turn pretty printing back on, instead
14770 of the default @code{--!pp on}.
14771
14772 @item --pp-old
14773 @cindex @option{--pp-old} @command{gnatpp}
14774 Use the old formatting algorithms.
14775
14776 @item ^-files @var{filename}^/FILES=@var{filename}^
14777 @cindex @option{^-files^/FILES^} (@code{gnatpp})
14778 Take the argument source files from the specified file. This file should be an
14779 ordinary text file containing file names separated by spaces or
14780 line breaks. You can use this switch more than once in the same call to
14781 @command{gnatpp}. You also can combine this switch with an explicit list of
14782 files.
14783
14784 @item ^-j^/PROCESSES=^@var{n}
14785 @cindex @option{^-j^/PROCESSES^} (@command{gnatpp})
14786 Without @option{--incremental}, use @var{n} processes to carry out the
14787 tree creations (internal representations of the argument sources). On
14788 a multiprocessor machine this speeds up processing of big sets of
14789 argument sources. If @var{n} is 0, then the maximum number of parallel
14790 tree creations is the number of core processors on the platform. This
14791 option cannot be used together with @option{^-r^/REPLACE^},
14792 @option{^-rf^/OVERRIDING_REPLACE^} or
14793 @option{^-rnb^/REPLACE_NO_BACKUP^} option.
14794
14795 With @option{--incremental}, use @var{n} @command{gnatpp} processes to
14796 perform pretty-printing in parallel. @var{n} = 0 means the same as
14797 above. In this case, @option{^-r^/REPLACE^},
14798 @option{^-rf^/OVERRIDING_REPLACE^} or
14799 @option{^-rnb^/REPLACE_NO_BACKUP^} options are allowed.
14800
14801 @cindex @option{^-t^/TIME^} (@command{gnatpp})
14802 @item ^-t^/TIME^
14803 Print out execution time.
14804
14805 @item ^-v^/VERBOSE^
14806 @cindex @option{^-v^/VERBOSE^} (@command{gnatpp})
14807 Verbose mode
14808
14809 @item ^-q^/QUIET^
14810 @cindex @option{^-q^/QUIET^} (@command{gnatpp})
14811 Quiet mode
14812 @end table
14813
14814 @noindent
14815 If a project file is specified and no argument source is explicitly
14816 specified (either directly or by means of @option{-files} option), and no
14817 @option{-U} is specified, then the set of processed sources is
14818 all the immediate units of the argument project.
14819
14820
14821 @node Formatting Rules
14822 @section Formatting Rules
14823
14824 @noindent
14825 The following subsections show how @command{gnatpp} treats white space,
14826 comments, program layout, and name casing.
14827 They provide detailed descriptions of the switches shown above.
14828
14829 @menu
14830 * Disabling Pretty Printing::
14831 * White Space and Empty Lines::
14832 * Formatting Comments::
14833 * Name Casing::
14834 @end menu
14835
14836 @node Disabling Pretty Printing
14837 @subsection Disabling Pretty Printing
14838
14839 @noindent
14840 Pretty printing is highly heuristic in nature, and sometimes doesn't
14841 do exactly what you want. If you wish to format a certain region of
14842 code by hand, you can turn off pretty printing in that region by
14843 surrounding it with special comments that start with @code{--!pp off}
14844 and @code{--!pp on}. The text in that region will then be reproduced
14845 verbatim in the output with no formatting.
14846
14847 To disable pretty printing for the whole file, put @code{--!pp off} at
14848 the top, with no following @code{--!pp on}.
14849
14850 The comments must appear on a line by themselves, with nothing
14851 preceding except spaces. The initial text of the comment must be
14852 exactly @code{--!pp off} or @code{--!pp on} (case sensitive), but may
14853 be followed by arbitrary additional text. For example:
14854
14855 @smallexample @c ada
14856 @cartouche
14857 package Interrupts is
14858 --!pp off -- turn off pretty printing so "Interrupt_Kind" lines up
14859 type Interrupt_Kind is
14860 (Asynchronous_Interrupt_Kind,
14861 Synchronous_Interrupt_Kind,
14862 Green_Interrupt_Kind);
14863 --!pp on -- reenable pretty printing
14864
14865 ...
14866 @end cartouche
14867 @end smallexample
14868
14869 You can specify different comment strings using the @code{--pp-off}
14870 and @code{--pp-on} switches. For example, if you say @code{gnatpp
14871 --pp-off=' pp-' *.ad?} then gnatpp will recognize comments of the form
14872 @code{-- pp-} instead of @code{--!pp off} for disabling pretty
14873 printing. Note that the leading @code{--} of the comment is not
14874 included in the argument to these switches.
14875
14876 @node White Space and Empty Lines
14877 @subsection White Space and Empty Lines
14878
14879 @noindent
14880 @command{gnatpp} does not have an option to control space characters.
14881 It will add or remove spaces according to the style illustrated by the
14882 examples in the @cite{Ada Reference Manual}.
14883 The output file will contain no lines with trailing white space.
14884
14885 By default, a sequence of one or more blank lines in the input is
14886 converted to a single blank line in the output; multiple blank lines
14887 are squeezed down to one.
14888 The @option{^--preserve-blank-lines^/PRESERVE_BLANK_LINES^} option
14889 turns off the squeezing; each blank line in the input is copied
14890 to the output.
14891 The @option{^--insert-blank-lines^/INSERT_BLANK_LINES^} option
14892 causes additional blank lines to be inserted if not already
14893 present in the input (e.g. between bodies).
14894
14895 @node Formatting Comments
14896 @subsection Formatting Comments
14897
14898 @noindent
14899 Comments in Ada code are of two kinds:
14900 @itemize @bullet
14901 @item
14902 a @emph{whole-line comment}, which appears by itself (possibly preceded by
14903 white space) on a line
14904
14905 @item
14906 an @emph{end-of-line comment}, which follows some other Ada code on
14907 the same line.
14908 @end itemize
14909
14910 @noindent
14911 A whole-line comment is indented according to the surrounding code,
14912 with some exceptions.
14913 Comments that start in column 1 are kept there.
14914 If possible, comments are not moved so far to the right that the maximum
14915 line length is exceeded.
14916 The @option{^-c0^/COMMENTS_LAYOUT=UNTOUCHED^} option
14917 turns off comment formatting.
14918 Special-form comments such as SPARK-style @code{--#...} are left alone.
14919
14920 For an end-of-line comment, @command{gnatpp} tries to leave the same
14921 number of spaces between the end of the preceding Ada code and the
14922 beginning of the comment as appear in the original source.
14923
14924 @noindent
14925 The @option{^-c3^/COMMENTS_LAYOUT=GNAT_BEGINNING^} switch
14926 (GNAT style comment beginning) has the following
14927 effect:
14928
14929 @itemize @bullet
14930 @item
14931 For each whole-line comment that does not end with two hyphens,
14932 @command{gnatpp} inserts spaces if necessary after the starting two hyphens
14933 to ensure that there are at least two spaces between these hyphens and the
14934 first non-blank character of the comment.
14935 @end itemize
14936
14937 @noindent
14938 The @option{^-c4^/COMMENTS_LAYOUT=REFORMAT^} switch specifies that
14939 whole-line comments that form a paragraph will be filled in typical
14940 word processor style (that is, moving words between lines to make the
14941 lines other than the last similar in length ).
14942
14943 @noindent
14944 The @option{--comments-only} switch specifies that only the comments
14945 are formatted; the rest of the program text is left alone. The
14946 comments are formatted according to the -c3 and -c4 switches; other
14947 formatting switches are ignored. For example, @option{--comments-only
14948 -c4} means to fill comment paragraphs, and do nothing else. Likewise,
14949 @option{--comments-only -c3} ensures comments start with at least two
14950 spaces after @code{--}, and @option{--comments-only -c3 -c4} does
14951 both. If @option{--comments-only} is given without @option{-c3} or
14952 @option{-c4}, then gnatpp doesn't format anything.
14953
14954 @node Name Casing
14955 @subsection Name Casing
14956
14957 @noindent
14958 @command{gnatpp} always converts the usage occurrence of a (simple) name to
14959 the same casing as the corresponding defining identifier.
14960
14961 You control the casing for defining occurrences via the
14962 @option{^-n^/NAME_CASING^} switch.
14963 @ifclear vms
14964 With @option{-nD} (``as declared'', which is the default),
14965 @end ifclear
14966 @ifset vms
14967 With @option{/NAME_CASING=AS_DECLARED}, which is the default,
14968 @end ifset
14969 defining occurrences appear exactly as in the source file
14970 where they are declared.
14971 The other ^values for this switch^options for this qualifier^ ---
14972 @option{^-nU^UPPER_CASE^},
14973 @option{^-nL^LOWER_CASE^},
14974 @option{^-nM^MIXED_CASE^} ---
14975 result in
14976 ^upper, lower, or mixed case, respectively^the corresponding casing^.
14977 If @command{gnatpp} changes the casing of a defining
14978 occurrence, it analogously changes the casing of all the
14979 usage occurrences of this name.
14980
14981 If the defining occurrence of a name is not in the source compilation unit
14982 currently being processed by @command{gnatpp}, the casing of each reference to
14983 this name is changed according to the value of the @option{^-n^/NAME_CASING^}
14984 switch (subject to the dictionary file mechanism described below).
14985 Thus @command{gnatpp} acts as though the @option{^-n^/NAME_CASING^} switch
14986 had affected the
14987 casing for the defining occurrence of the name.
14988
14989 The options
14990 @option{^-a@var{x}^/ATTRIBUTE^},
14991 @option{^-k@var{x}^/KEYWORD_CASING^},
14992 @option{^-ne@var{x}^/ENUM_CASING^},
14993 @option{^-nt@var{x}^/TYPE_CASING^},
14994 @option{^-nn@var{x}^/NUMBER_CASING^}, and
14995 @option{^-p@var{x}^/PRAGMA_CASING^}
14996 allow finer-grained control over casing for
14997 attributes, keywords, enumeration literals,
14998 types, named numbers and pragmas, respectively.
14999 @option{^-nt@var{x}^/TYPE_CASING^} covers subtypes and
15000 task and protected bodies as well.
15001
15002 Some names may need to be spelled with casing conventions that are not
15003 covered by the upper-, lower-, and mixed-case transformations.
15004 You can arrange correct casing by placing such names in a
15005 @emph{dictionary file},
15006 and then supplying a @option{^-D^/DICTIONARY^} switch.
15007 The casing of names from dictionary files overrides
15008 any @option{^-n^/NAME_CASING^} switch.
15009
15010 To handle the casing of Ada predefined names and the names from GNAT libraries,
15011 @command{gnatpp} assumes a default dictionary file.
15012 The name of each predefined entity is spelled with the same casing as is used
15013 for the entity in the @cite{Ada Reference Manual} (usually mixed case).
15014 The name of each entity in the GNAT libraries is spelled with the same casing
15015 as is used in the declaration of that entity.
15016
15017 The @w{@option{^-D-^/SPECIFIC_CASING^}} switch suppresses the use of
15018 the default dictionary file. Instead, the casing for predefined and
15019 GNAT-defined names will be established by the
15020 @option{^-n^/NAME_CASING^} switch or explicit dictionary files. For
15021 example, by default the names @code{Ada.Text_IO} and
15022 @code{GNAT.OS_Lib} will appear as just shown, even in the presence of
15023 a @option{^-nU^/NAME_CASING=UPPER_CASE^} switch. To ensure that even
15024 such names are rendered in uppercase, additionally supply the
15025 @w{@option{^-D-^/SPECIFIC_CASING^}} switch (or else place these names
15026 in upper case in a dictionary file).
15027
15028 A dictionary file is a plain text file; each line in this file can be
15029 either a blank line (containing only space characters), an Ada comment
15030 line, or the specification of exactly one @emph{casing schema}.
15031
15032 A casing schema is a string that has the following syntax:
15033
15034 @smallexample
15035 @cartouche
15036 @var{casing_schema} ::= @var{identifier} | *@var{simple_identifier}*
15037
15038 @var{simple_identifier} ::= @var{letter}@{@var{letter_or_digit}@}
15039 @end cartouche
15040 @end smallexample
15041
15042 @noindent
15043 (See @cite{Ada Reference Manual}, Section 2.3) for the definition of the
15044 @var{identifier} lexical element and the @var{letter_or_digit} category.)
15045
15046 The casing schema string can be followed by white space and/or an Ada-style
15047 comment; any amount of white space is allowed before the string.
15048
15049 If a dictionary file is passed as
15050 @ifclear vms
15051 the value of a @option{-D@var{file}} switch
15052 @end ifclear
15053 @ifset vms
15054 an option to the @option{/DICTIONARY} qualifier
15055 @end ifset
15056 then for every
15057 simple name and every identifier, @command{gnatpp} checks if the dictionary
15058 defines the casing for the name or for some of its parts (the term ``subword''
15059 is used below to denote the part of a name which is delimited by ``_'' or by
15060 the beginning or end of the word and which does not contain any ``_'' inside):
15061
15062 @itemize @bullet
15063 @item
15064 if the whole name is in the dictionary, @command{gnatpp} uses for this name
15065 the casing defined by the dictionary; no subwords are checked for this word
15066
15067 @item
15068 for every subword @command{gnatpp} checks if the dictionary contains the
15069 corresponding string of the form @code{*@var{simple_identifier}*},
15070 and if it does, the casing of this @var{simple_identifier} is used
15071 for this subword
15072
15073 @item
15074 if the whole name does not contain any ``_'' inside, and if for this name
15075 the dictionary contains two entries - one of the form @var{identifier},
15076 and another - of the form *@var{simple_identifier}*, then the first one
15077 is applied to define the casing of this name
15078
15079 @item
15080 if more than one dictionary file is passed as @command{gnatpp} switches, each
15081 dictionary adds new casing exceptions and overrides all the existing casing
15082 exceptions set by the previous dictionaries
15083
15084 @item
15085 when @command{gnatpp} checks if the word or subword is in the dictionary,
15086 this check is not case sensitive
15087 @end itemize
15088
15089 @noindent
15090 For example, suppose we have the following source to reformat:
15091
15092 @smallexample @c ada
15093 @cartouche
15094 procedure test is
15095 name1 : integer := 1;
15096 name4_name3_name2 : integer := 2;
15097 name2_name3_name4 : Boolean;
15098 name1_var : Float;
15099 begin
15100 name2_name3_name4 := name4_name3_name2 > name1;
15101 end;
15102 @end cartouche
15103 @end smallexample
15104
15105 @noindent
15106 And suppose we have two dictionaries:
15107
15108 @smallexample
15109 @cartouche
15110 @i{dict1:}
15111 NAME1
15112 *NaMe3*
15113 *Name1*
15114 @end cartouche
15115
15116 @cartouche
15117 @i{dict2:}
15118 *NAME3*
15119 @end cartouche
15120 @end smallexample
15121
15122 @noindent
15123 If @command{gnatpp} is called with the following switches:
15124
15125 @smallexample
15126 @ifclear vms
15127 @command{gnatpp -nM -D dict1 -D dict2 test.adb}
15128 @end ifclear
15129 @ifset vms
15130 @command{gnatpp test.adb /NAME_CASING=MIXED_CASE /DICTIONARY=(dict1, dict2)}
15131 @end ifset
15132 @end smallexample
15133
15134 @noindent
15135 then we will get the following name casing in the @command{gnatpp} output:
15136
15137 @smallexample @c ada
15138 @cartouche
15139 procedure Test is
15140 NAME1 : Integer := 1;
15141 Name4_NAME3_Name2 : Integer := 2;
15142 Name2_NAME3_Name4 : Boolean;
15143 Name1_Var : Float;
15144 begin
15145 Name2_NAME3_Name4 := Name4_NAME3_Name2 > NAME1;
15146 end Test;
15147 @end cartouche
15148 @end smallexample
15149 @end ifclear
15150
15151 @ifclear FSFEDITION
15152 @ifclear vms
15153 @c *********************************
15154 @node The Ada-to-XML converter gnat2xml
15155 @chapter The Ada-to-XML converter @command{gnat2xml}
15156 @findex gnat2xml
15157 @cindex XML generation
15158
15159 @noindent
15160 The @command{gnat2xml} tool is an ASIS-based utility that converts
15161 Ada source code into XML.
15162
15163 @menu
15164 * Switches for gnat2xml::
15165 * Other Programs::
15166 * Structure of the XML::
15167 @end menu
15168
15169 @node Switches for gnat2xml
15170 @section Switches for @command{gnat2xml}
15171
15172 @noindent
15173 @command{gnat2xml} takes Ada source code as input, and produces XML
15174 that conforms to the schema.
15175
15176 Usage:
15177
15178 @smallexample
15179 gnat2xml [options] filenames [-files filename] [-cargs gcc_switches]
15180 @end smallexample
15181
15182 @noindent
15183 options:
15184 @smallexample
15185 -h
15186 --help -- generate usage information and quit, ignoring all other options
15187 --version -- print version and quit, ignoring all other options
15188
15189 -P @file{file} -- indicates the name of the project file that describes
15190 the set of sources to be processed. The exact set of argument
15191 sources depends on other options specified, see below.
15192
15193 -U -- if a project file is specified and no argument source is explicitly
15194 specified, process all the units of the closure of the argument project.
15195 Otherwise this option has no effect.
15196
15197 -U @var{main_unit} -- if a project file is specified and no argument source
15198 is explicitly specified (either directly or by means of @option{-files}
15199 option), process the closure of units rooted at @var{main_unit}.
15200 Otherwise this option has no effect.
15201
15202 -X@var{name}=@var{value} -- indicates that external variable @var{name} in
15203 the argument project has the value @var{value}. Has no effect if no
15204 project is specified as tool argument.
15205
15206 --incremental -- incremental processing on a per-file basis. Source files are
15207 only processed if they have been modified, or if files they depend
15208 on have been modified. This is similar to the way gnatmake/gprbuild
15209 only compiles files that need to be recompiled.
15210
15211 -j@var{n} -- In @option{--incremental} mode, use @var{n} @command{gnat2xml}
15212 processes to perform XML generation in parallel. If @var{n} is 0, then
15213 the maximum number of parallel tree creations is the number of core
15214 processors on the platform.
15215
15216 --output-dir=@var{dir} -- generate one .xml file for each Ada source file, in
15217 directory @file{dir}. (Default is to generate the XML to standard
15218 output.)
15219
15220 -I <include-dir>
15221 directories to search for dependencies
15222 You can also set the ADA_INCLUDE_PATH environment variable for this.
15223
15224 --compact -- debugging version, with interspersed source, and a more
15225 compact representation of "sloc". This version does not conform
15226 to any schema.
15227
15228 -files=filename - the name of a text file containing a list
15229 of Ada source files to process
15230
15231 -q -- quiet
15232 -v -- verbose
15233
15234 -cargs ... -- options to pass to gcc
15235 @end smallexample
15236
15237 @noindent
15238 If a project file is specified and no argument source is explicitly
15239 specified, and no @option{-U} is specified, then the set of processed
15240 sources is all the immediate units of the argument project.
15241
15242 Example:
15243
15244 @smallexample
15245 gnat2xml -v -output-dir=xml-files *.ad[sb]
15246 @end smallexample
15247
15248 @noindent
15249 The above will create *.xml files in the @file{xml-files} subdirectory.
15250 For example, if there is an Ada package Mumble.Dumble, whose spec and
15251 body source code lives in mumble-dumble.ads and mumble-dumble.adb,
15252 the above will produce xml-files/mumble-dumble.ads.xml and
15253 xml-files/mumble-dumble.adb.xml.
15254
15255 @node Other Programs
15256 @section Other Programs
15257
15258 @noindent
15259 The distribution includes two other programs that are related to
15260 @command{gnat2xml}:
15261
15262 @command{gnat2xsd} is the schema generator, which generates the schema
15263 to standard output, based on the structure of Ada as encoded by
15264 ASIS. You don't need to run @command{gnat2xsd} in order to use
15265 @command{gnat2xml}. To generate the schema, type:
15266
15267 @smallexample
15268 gnat2xsd > ada-schema.xsd
15269 @end smallexample
15270
15271 @noindent
15272 @command{gnat2xml} generates XML files that will validate against
15273 @file{ada-schema.xsd}.
15274
15275 @command{xml2gnat} is a back-translator that translates the XML back
15276 into Ada source code. The Ada generated by @command{xml2gnat} has
15277 identical semantics to the original Ada code passed to
15278 @command{gnat2xml}. It is not textually identical, however --- for
15279 example, no attempt is made to preserve the original indentation.
15280
15281 @node Structure of the XML
15282 @section Structure of the XML
15283
15284 @noindent
15285 The primary documentation for the structure of the XML generated by
15286 @command{gnat2xml} is the schema (see @command{gnat2xsd} above). The
15287 following documentation gives additional details needed to understand
15288 the schema and therefore the XML.
15289
15290 The elements listed under Defining Occurrences, Usage Occurrences, and
15291 Other Elements represent the syntactic structure of the Ada program.
15292 Element names are given in lower case, with the corresponding element
15293 type Capitalized_Like_This. The element and element type names are
15294 derived directly from the ASIS enumeration type Flat_Element_Kinds,
15295 declared in Asis.Extensions.Flat_Kinds, with the leading ``An_'' or ``A_''
15296 removed. For example, the ASIS enumeration literal
15297 An_Assignment_Statement corresponds to the XML element
15298 assignment_statement of XML type Assignment_Statement.
15299
15300 To understand the details of the schema and the corresponding XML, it is
15301 necessary to understand the ASIS standard, as well as the GNAT-specific
15302 extension to ASIS.
15303
15304 A defining occurrence is an identifier (or character literal or operator
15305 symbol) declared by a declaration. A usage occurrence is an identifier
15306 (or ...) that references such a declared entity. For example, in:
15307
15308 @smallexample
15309 type T is range 1..10;
15310 X, Y : constant T := 1;
15311 @end smallexample
15312
15313 @noindent
15314 The first ``T'' is the defining occurrence of a type. The ``X'' is the
15315 defining occurrence of a constant, as is the ``Y'', and the second ``T'' is
15316 a usage occurrence referring to the defining occurrence of T.
15317
15318 Each element has a 'sloc' (source location), and subelements for each
15319 syntactic subtree, reflecting the Ada grammar as implemented by ASIS.
15320 The types of subelements are as defined in the ASIS standard. For
15321 example, for the right-hand side of an assignment_statement we have
15322 the following comment in asis-statements.ads:
15323
15324 @smallexample
15325 ------------------------------------------------------------------------------
15326 -- 18.3 function Assignment_Expression
15327 ------------------------------------------------------------------------------
15328
15329 function Assignment_Expression
15330 (Statement : Asis.Statement)
15331 return Asis.Expression;
15332
15333 ------------------------------------------------------------------------------
15334 ...
15335 -- Returns the expression from the right hand side of the assignment.
15336 ...
15337 -- Returns Element_Kinds:
15338 -- An_Expression
15339 @end smallexample
15340
15341 @noindent
15342 The corresponding sub-element of type Assignment_Statement is:
15343
15344 @smallexample
15345 <xsd:element name="assignment_expression_q" type="Expression_Class"/>
15346 @end smallexample
15347
15348 @noindent
15349 where Expression_Class is defined by an xsd:choice of all the
15350 various kinds of expression.
15351
15352 The 'sloc' of each element indicates the starting and ending line and
15353 column numbers. Column numbers are character counts; that is, a tab
15354 counts as 1, not as however many spaces it might expand to.
15355
15356 Subelements of type Element have names ending in ``_q'' (for ASIS
15357 ``Query''), and those of type Element_List end in ``_ql'' (``Query returning
15358 List'').
15359
15360 Some subelements are ``Boolean''. For example, Private_Type_Definition
15361 has has_abstract_q and has_limited_q, to indicate whether those
15362 keywords are present, as in @code{type T is abstract limited
15363 private;}. False is represented by a Nil_Element. True is represented
15364 by an element type specific to that query (for example, Abstract and
15365 Limited).
15366
15367 The root of the tree is a Compilation_Unit, with attributes:
15368
15369 @itemize @bullet
15370 @item
15371 unit_kind, unit_class, and unit_origin. These are strings that match the
15372 enumeration literals of types Unit_Kinds, Unit_Classes, and Unit_Origins
15373 in package Asis.
15374
15375 @item
15376 unit_full_name is the full expanded name of the unit, starting from a
15377 root library unit. So for @code{package P.Q.R is ...},
15378 @code{unit_full_name="P.Q.R"}. Same for @code{separate (P.Q) package R is ...}.
15379
15380 @item
15381 def_name is the same as unit_full_name for library units; for subunits,
15382 it is just the simple name.
15383
15384 @item
15385 source_file is the name of the Ada source file. For example, for
15386 the spec of @code{P.Q.R}, @code{source_file="p-q-r.ads"}. This allows one to
15387 interpret the source locations --- the ``sloc'' of all elements
15388 within this Compilation_Unit refers to line and column numbers
15389 within the named file.
15390 @end itemize
15391
15392 @noindent
15393 Defining occurrences have these attributes:
15394
15395 @itemize @bullet
15396 @item
15397 def_name is the simple name of the declared entity, as written in the Ada
15398 source code.
15399
15400 @item
15401 def is a unique URI of the form:
15402
15403 ada://kind/fully/qualified/name
15404
15405 where:
15406
15407 kind indicates the kind of Ada entity being declared (see below), and
15408
15409 fully/qualified/name, is the fully qualified name of the Ada
15410 entity, with each of ``fully'', ``qualified'', and ``name'' being
15411 mangled for uniqueness. We do not document the mangling
15412 algorithm, which is subject to change; we just guarantee that the
15413 names are unique in the face of overloading.
15414
15415 @item
15416 type is the type of the declared object, or @code{null} for
15417 declarations of things other than objects.
15418 @end itemize
15419
15420 @noindent
15421 Usage occurrences have these attributes:
15422
15423 @itemize @bullet
15424 @item
15425 ref_name is the same as the def_name of the corresponding defining
15426 occurrence. This attribute is not of much use, because of
15427 overloading; use ref for lookups, instead.
15428
15429 @item
15430 ref is the same as the def of the corresponding defining
15431 occurrence.
15432 @end itemize
15433
15434 @noindent
15435 In summary, @code{def_name} and @code{ref_name} are as in the source
15436 code of the declaration, possibly overloaded, whereas @code{def} and
15437 @code{ref} are unique-ified.
15438
15439 Literal elements have this attribute:
15440
15441 @itemize @bullet
15442 @item
15443 lit_val is the value of the literal as written in the source text,
15444 appropriately escaped (e.g. @code{"} ---> @code{&quot;}). This applies
15445 only to numeric and string literals. Enumeration literals in Ada are
15446 not really "literals" in the usual sense; they are usage occurrences,
15447 and have ref_name and ref as described above. Note also that string
15448 literals used as operator symbols are treated as defining or usage
15449 occurrences, not as literals.
15450 @end itemize
15451
15452 @noindent
15453 Elements that can syntactically represent names and expressions (which
15454 includes usage occurrences, plus function calls and so forth) have this
15455 attribute:
15456
15457 @itemize @bullet
15458 @item
15459 type. If the element represents an expression or the name of an object,
15460 'type' is the 'def' for the defining occurrence of the type of that
15461 expression or name. Names of other kinds of entities, such as package
15462 names and type names, do not have a type in Ada; these have type="null"
15463 in the XML.
15464 @end itemize
15465
15466 @noindent
15467 Pragma elements have this attribute:
15468
15469 @itemize @bullet
15470 @item
15471 pragma_name is the name of the pragma. For language-defined pragmas, the
15472 pragma name is redundant with the element kind (for example, an
15473 assert_pragma element necessarily has pragma_name="Assert"). However, all
15474 implementation-defined pragmas are lumped together in ASIS as a single
15475 element kind (for example, the GNAT-specific pragma Unreferenced is
15476 represented by an implementation_defined_pragma element with
15477 pragma_name="Unreferenced").
15478 @end itemize
15479
15480 @noindent
15481 Defining occurrences of formal parameters and generic formal objects have this
15482 attribute:
15483
15484 @itemize @bullet
15485 @item
15486 mode indicates that the parameter is of mode 'in', 'in out', or 'out'.
15487 @end itemize
15488
15489 @noindent
15490 All elements other than Not_An_Element have this attribute:
15491
15492 @itemize @bullet
15493 @item
15494 checks is a comma-separated list of run-time checks that are needed
15495 for that element. The possible checks are: do_accessibility_check,
15496 do_discriminant_check,do_division_check,do_length_check,
15497 do_overflow_check,do_range_check,do_storage_check,do_tag_check.
15498 @end itemize
15499
15500 @noindent
15501 The "kind" part of the "def" and "ref" attributes is taken from the ASIS
15502 enumeration type Flat_Declaration_Kinds, declared in
15503 Asis.Extensions.Flat_Kinds, with the leading "An_" or "A_" removed, and
15504 any trailing "_Declaration" or "_Specification" removed. Thus, the
15505 possible kinds are as follows:
15506
15507 @smallexample
15508 ordinary_type
15509 task_type
15510 protected_type
15511 incomplete_type
15512 tagged_incomplete_type
15513 private_type
15514 private_extension
15515 subtype
15516 variable
15517 constant
15518 deferred_constant
15519 single_task
15520 single_protected
15521 integer_number
15522 real_number
15523 enumeration_literal
15524 discriminant
15525 component
15526 loop_parameter
15527 generalized_iterator
15528 element_iterator
15529 procedure
15530 function
15531 parameter
15532 procedure_body
15533 function_body
15534 return_variable
15535 return_constant
15536 null_procedure
15537 expression_function
15538 package
15539 package_body
15540 object_renaming
15541 exception_renaming
15542 package_renaming
15543 procedure_renaming
15544 function_renaming
15545 generic_package_renaming
15546 generic_procedure_renaming
15547 generic_function_renaming
15548 task_body
15549 protected_body
15550 entry
15551 entry_body
15552 entry_index
15553 procedure_body_stub
15554 function_body_stub
15555 package_body_stub
15556 task_body_stub
15557 protected_body_stub
15558 exception
15559 choice_parameter
15560 generic_procedure
15561 generic_function
15562 generic_package
15563 package_instantiation
15564 procedure_instantiation
15565 function_instantiation
15566 formal_object
15567 formal_type
15568 formal_incomplete_type
15569 formal_procedure
15570 formal_function
15571 formal_package
15572 formal_package_declaration_with_box
15573 @end smallexample
15574 @end ifclear
15575 @end ifclear
15576
15577
15578 @ifclear FSFEDITION
15579 @c *********************************
15580 @node The GNAT Metrics Tool gnatmetric
15581 @chapter The GNAT Metrics Tool @command{gnatmetric}
15582 @findex gnatmetric
15583 @cindex Metric tool
15584
15585 @noindent
15586 ^The @command{gnatmetric} tool^@command{GNAT METRIC}^ is an ASIS-based utility
15587 for computing various program metrics.
15588 It takes an Ada source file as input and generates a file containing the
15589 metrics data as output. Various switches control which
15590 metrics are computed and output.
15591
15592 @menu
15593 * Switches for gnatmetric::
15594 @end menu
15595
15596 To compute program metrics, @command{gnatmetric} invokes the Ada
15597 compiler and generates and uses the ASIS tree for the input source;
15598 thus the input must be legal Ada code, and the tool should have all the
15599 information needed to compile the input source. To provide this information,
15600 you may specify as a tool parameter the project file the input source belongs to
15601 (or you may call @command{gnatmetric}
15602 through the @command{gnat} driver (see @ref{The GNAT Driver and
15603 Project Files}). Another possibility is to specify the source search
15604 path and needed configuration files in @option{-cargs} section of @command{gnatmetric}
15605 call, see the description of the @command{gnatmetric} switches below.
15606
15607 The @command{gnatmetric} command has the form
15608
15609 @smallexample
15610 @c $ gnatmetric @ovar{switches} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15611 @c Expanding @ovar macro inline (explanation in macro def comments)
15612 $ gnatmetric @r{[}@var{switches}@r{]} @{@var{filename}@} @r{[}-cargs @var{gcc_switches}@r{]}
15613 @end smallexample
15614
15615 @noindent
15616 where
15617 @itemize @bullet
15618 @item
15619 @var{switches} specify the metrics to compute and define the destination for
15620 the output
15621
15622 @item
15623 Each @var{filename} is the name (including the extension) of a source
15624 file to process. ``Wildcards'' are allowed, and
15625 the file name may contain path information.
15626 If no @var{filename} is supplied, then the @var{switches} list must contain
15627 at least one
15628 @option{-files} switch (@pxref{Other gnatmetric Switches}).
15629 Including both a @option{-files} switch and one or more
15630 @var{filename} arguments is permitted.
15631
15632 @item
15633 @samp{@var{gcc_switches}} is a list of switches for
15634 @command{gcc}. They will be passed on to all compiler invocations made by
15635 @command{gnatmetric} to generate the ASIS trees. Here you can provide
15636 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
15637 and use the @option{-gnatec} switch to set the configuration file,
15638 use the @option{-gnat05} switch if sources should be compiled in
15639 Ada 2005 mode etc.
15640 @end itemize
15641
15642 @node Switches for gnatmetric
15643 @section Switches for @command{gnatmetric}
15644
15645 @noindent
15646 The following subsections describe the various switches accepted by
15647 @command{gnatmetric}, organized by category.
15648
15649 @menu
15650 * Output Files Control::
15651 * Disable Metrics For Local Units::
15652 * Specifying a set of metrics to compute::
15653 * Other gnatmetric Switches::
15654 @ignore
15655 * Generate project-wide metrics::
15656 @end ignore
15657 @end menu
15658
15659 @node Output Files Control
15660 @subsection Output File Control
15661 @cindex Output file control in @command{gnatmetric}
15662
15663 @noindent
15664 @command{gnatmetric} has two output formats. It can generate a
15665 textual (human-readable) form, and also XML. By default only textual
15666 output is generated.
15667
15668 When generating the output in textual form, @command{gnatmetric} creates
15669 for each Ada source file a corresponding text file
15670 containing the computed metrics, except for the case when the set of metrics
15671 specified by gnatmetric parameters consists only of metrics that are computed
15672 for the whole set of analyzed sources, but not for each Ada source.
15673 By default, the name of the file containing metric information for a source
15674 is obtained by appending the ^@file{.metrix}^@file{$METRIX}^ suffix to the
15675 name of the input source file. If not otherwise specified and no project file
15676 is specified as @command{gnatmetric} option this file is placed in the same
15677 directory as where the source file is located. If @command{gnatmetric} has a
15678 project file as its parameter, it places all the generated files in the
15679 object directory of the project (or in the project source directory if the
15680 project does not define an objects directory), if @option{--subdirs} option
15681 is specified, the files are placed in the subrirectory of this directory
15682 specified by this option.
15683
15684 All the output information generated in XML format is placed in a single
15685 file. By default the name of this file is ^@file{metrix.xml}^@file{METRIX$XML}^.
15686 If not otherwise specified and if no project file is specified
15687 as @command{gnatmetric} option this file is placed in the
15688 current directory.
15689
15690 Some of the computed metrics are summed over the units passed to
15691 @command{gnatmetric}; for example, the total number of lines of code.
15692 By default this information is sent to @file{stdout}, but a file
15693 can be specified with the @option{-og} switch.
15694
15695 The following switches control the @command{gnatmetric} output:
15696
15697 @table @option
15698 @cindex @option{^-x^/XML^} (@command{gnatmetric})
15699 @item ^-x^/XML^
15700 Generate the XML output
15701
15702 @cindex @option{^-xs^/XSD^} (@command{gnatmetric})
15703 @item ^-xs^/XSD^
15704 Generate the XML output and the XML schema file that describes the structure
15705 of the XML metric report, this schema is assigned to the XML file. The schema
15706 file has the same name as the XML output file with @file{.xml} suffix replaced
15707 with @file{.xsd}
15708
15709 @cindex @option{^-nt^/NO_TEXT^} (@command{gnatmetric})
15710 @item ^-nt^/NO_TEXT^
15711 Do not generate the output in text form (implies @option{^-x^/XML^})
15712
15713 @cindex @option{^-d^/DIRECTORY^} (@command{gnatmetric})
15714 @item ^-d @var{output_dir}^/DIRECTORY=@var{output_dir}^
15715 Put text files with detailed metrics into @var{output_dir}
15716
15717 @cindex @option{^-o^/SUFFIX_DETAILS^} (@command{gnatmetric})
15718 @item ^-o @var{file_suffix}^/SUFFIX_DETAILS=@var{file_suffix}^
15719 Use @var{file_suffix}, instead of ^@file{.metrix}^@file{$METRIX}^
15720 in the name of the output file.
15721
15722 @cindex @option{^-og^/GLOBAL_OUTPUT^} (@command{gnatmetric})
15723 @item ^-og @var{file_name}^/GLOBAL_OUTPUT=@var{file_name}^
15724 Put global metrics into @var{file_name}
15725
15726 @cindex @option{^-ox^/XML_OUTPUT^} (@command{gnatmetric})
15727 @item ^-ox @var{file_name}^/XML_OUTPUT=@var{file_name}^
15728 Put the XML output into @var{file_name} (also implies @option{^-x^/XML^})
15729
15730 @cindex @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} (@command{gnatmetric})
15731 @item ^-sfn^/SHORT_SOURCE_FILE_NAME^
15732 Use ``short'' source file names in the output. (The @command{gnatmetric}
15733 output includes the name(s) of the Ada source file(s) from which the metrics
15734 are computed. By default each name includes the absolute path. The
15735 @option{^-sfn^/SHORT_SOURCE_FILE_NAME^} switch causes @command{gnatmetric}
15736 to exclude all directory information from the file names that are output.)
15737
15738 @end table
15739
15740 @node Disable Metrics For Local Units
15741 @subsection Disable Metrics For Local Units
15742 @cindex Disable Metrics For Local Units in @command{gnatmetric}
15743
15744 @noindent
15745 @command{gnatmetric} relies on the GNAT compilation model @minus{}
15746 one compilation
15747 unit per one source file. It computes line metrics for the whole source
15748 file, and it also computes syntax
15749 and complexity metrics for the file's outermost unit.
15750
15751 By default, @command{gnatmetric} will also compute all metrics for certain
15752 kinds of locally declared program units:
15753
15754 @itemize @bullet
15755 @item
15756 subprogram (and generic subprogram) bodies;
15757
15758 @item
15759 package (and generic package) specs and bodies;
15760
15761 @item
15762 task object and type specifications and bodies;
15763
15764 @item
15765 protected object and type specifications and bodies.
15766 @end itemize
15767
15768 @noindent
15769 These kinds of entities will be referred to as
15770 @emph{eligible local program units}, or simply @emph{eligible local units},
15771 @cindex Eligible local unit (for @command{gnatmetric})
15772 in the discussion below.
15773
15774 Note that a subprogram declaration, generic instantiation,
15775 or renaming declaration only receives metrics
15776 computation when it appear as the outermost entity
15777 in a source file.
15778
15779 Suppression of metrics computation for eligible local units can be
15780 obtained via the following switch:
15781
15782 @table @option
15783 @cindex @option{^-nolocal^/SUPPRESS^} (@command{gnatmetric})
15784 @item ^-nolocal^/SUPPRESS=LOCAL_DETAILS^
15785 Do not compute detailed metrics for eligible local program units
15786
15787 @end table
15788
15789 @node Specifying a set of metrics to compute
15790 @subsection Specifying a set of metrics to compute
15791
15792 @noindent
15793 By default all the metrics are computed and reported. The switches
15794 described in this subsection allow you to control, on an individual
15795 basis, whether metrics are computed and
15796 reported. If at least one positive metric
15797 switch is specified (that is, a switch that defines that a given
15798 metric or set of metrics is to be computed), then only
15799 explicitly specified metrics are reported.
15800
15801 @menu
15802 * Line Metrics Control::
15803 * Syntax Metrics Control::
15804 * Complexity Metrics Control::
15805 * Coupling Metrics Control::
15806 @end menu
15807
15808 @node Line Metrics Control
15809 @subsubsection Line Metrics Control
15810 @cindex Line metrics control in @command{gnatmetric}
15811
15812 @noindent
15813 For any (legal) source file, and for each of its
15814 eligible local program units, @command{gnatmetric} computes the following
15815 metrics:
15816
15817 @itemize @bullet
15818 @item
15819 the total number of lines;
15820
15821 @item
15822 the total number of code lines (i.e., non-blank lines that are not comments)
15823
15824 @item
15825 the number of comment lines
15826
15827 @item
15828 the number of code lines containing end-of-line comments;
15829
15830 @item
15831 the comment percentage: the ratio between the number of lines that contain
15832 comments and the number of all non-blank lines, expressed as a percentage;
15833
15834 @item
15835 the number of empty lines and lines containing only space characters and/or
15836 format effectors (blank lines)
15837
15838 @item
15839 the average number of code lines in subprogram bodies, task bodies, entry
15840 bodies and statement sequences in package bodies (this metric is only computed
15841 across the whole set of the analyzed units)
15842
15843 @end itemize
15844
15845 @noindent
15846 @command{gnatmetric} sums the values of the line metrics for all the
15847 files being processed and then generates the cumulative results. The tool
15848 also computes for all the files being processed the average number of code
15849 lines in bodies.
15850
15851 You can use the following switches to select the specific line metrics
15852 to be computed and reported.
15853
15854 @table @option
15855 @cindex @option{^--lines@var{x}^/LINE_COUNT_METRICS^} (@command{gnatmetric})
15856
15857 @ifclear vms
15858 @cindex @option{--no-lines@var{x}}
15859 @end ifclear
15860
15861 @item ^--lines-all^/LINE_COUNT_METRICS=ALL^
15862 Report all the line metrics
15863
15864 @item ^--no-lines-all^/LINE_COUNT_METRICS=NONE^
15865 Do not report any of line metrics
15866
15867 @item ^--lines^/LINE_COUNT_METRICS=ALL_LINES^
15868 Report the number of all lines
15869
15870 @item ^--no-lines^/LINE_COUNT_METRICS=NOALL_LINES^
15871 Do not report the number of all lines
15872
15873 @item ^--lines-code^/LINE_COUNT_METRICS=CODE_LINES^
15874 Report the number of code lines
15875
15876 @item ^--no-lines-code^/LINE_COUNT_METRICS=NOCODE_LINES^
15877 Do not report the number of code lines
15878
15879 @item ^--lines-comment^/LINE_COUNT_METRICS=COMMENT_LINES^
15880 Report the number of comment lines
15881
15882 @item ^--no-lines-comment^/LINE_COUNT_METRICS=NOCOMMENT_LINES^
15883 Do not report the number of comment lines
15884
15885 @item ^--lines-eol-comment^/LINE_COUNT_METRICS=CODE_COMMENT_LINES^
15886 Report the number of code lines containing
15887 end-of-line comments
15888
15889 @item ^--no-lines-eol-comment^/LINE_COUNT_METRICS=NOCODE_COMMENT_LINES^
15890 Do not report the number of code lines containing
15891 end-of-line comments
15892
15893 @item ^--lines-ratio^/LINE_COUNT_METRICS=COMMENT_PERCENTAGE^
15894 Report the comment percentage in the program text
15895
15896 @item ^--no-lines-ratio^/LINE_COUNT_METRICS=NOCOMMENT_PERCENTAGE^
15897 Do not report the comment percentage in the program text
15898
15899 @item ^--lines-blank^/LINE_COUNT_METRICS=BLANK_LINES^
15900 Report the number of blank lines
15901
15902 @item ^--no-lines-blank^/LINE_COUNT_METRICS=NOBLANK_LINES^
15903 Do not report the number of blank lines
15904
15905 @item ^--lines-average^/LINE_COUNT_METRICS=AVERAGE_BODY_LINES^
15906 Report the average number of code lines in subprogram bodies, task bodies,
15907 entry bodies and statement sequences in package bodies. The metric is computed
15908 and reported for the whole set of processed Ada sources only.
15909
15910 @item ^--no-lines-average^/LINE_COUNT_METRICS=NOAVERAGE_BODY_LINES^
15911 Do not report the average number of code lines in subprogram bodies,
15912 task bodies, entry bodies and statement sequences in package bodies.
15913
15914 @end table
15915
15916 @node Syntax Metrics Control
15917 @subsubsection Syntax Metrics Control
15918 @cindex Syntax metrics control in @command{gnatmetric}
15919
15920 @noindent
15921 @command{gnatmetric} computes various syntactic metrics for the
15922 outermost unit and for each eligible local unit:
15923
15924 @table @emph
15925 @item LSLOC (``Logical Source Lines Of Code'')
15926 The total number of declarations and the total number of statements. Note
15927 that the definition of declarations is the one given in the reference
15928 manual:
15929
15930 @noindent
15931 ``Each of the following is defined to be a declaration: any basic_declaration;
15932 an enumeration_literal_specification; a discriminant_specification;
15933 a component_declaration; a loop_parameter_specification; a
15934 parameter_specification; a subprogram_body; an entry_declaration;
15935 an entry_index_specification; a choice_parameter_specification;
15936 a generic_formal_parameter_declaration.''
15937
15938 This means for example that each enumeration literal adds one to the count,
15939 as well as each subprogram parameter.
15940
15941 Thus the results from this metric will be significantly greater than might
15942 be expected from a naive view of counting semicolons.
15943
15944 @item Maximal static nesting level of inner program units
15945 According to
15946 @cite{Ada Reference Manual}, 10.1(1), ``A program unit is either a
15947 package, a task unit, a protected unit, a
15948 protected entry, a generic unit, or an explicitly declared subprogram other
15949 than an enumeration literal.''
15950
15951 @item Maximal nesting level of composite syntactic constructs
15952 This corresponds to the notion of the
15953 maximum nesting level in the GNAT built-in style checks
15954 (@pxref{Style Checking})
15955 @end table
15956
15957 @noindent
15958 For the outermost unit in the file, @command{gnatmetric} additionally computes
15959 the following metrics:
15960
15961 @table @emph
15962 @item Public subprograms
15963 This metric is computed for package specs. It is the
15964 number of subprograms and generic subprograms declared in the visible
15965 part (including the visible part of nested packages, protected objects, and
15966 protected types).
15967
15968 @item All subprograms
15969 This metric is computed for bodies and subunits. The
15970 metric is equal to a total number of subprogram bodies in the compilation
15971 unit.
15972 Neither generic instantiations nor renamings-as-a-body nor body stubs
15973 are counted. Any subprogram body is counted, independently of its nesting
15974 level and enclosing constructs. Generic bodies and bodies of protected
15975 subprograms are counted in the same way as ``usual'' subprogram bodies.
15976
15977 @item Public types
15978 This metric is computed for package specs and
15979 generic package declarations. It is the total number of types
15980 that can be referenced from outside this compilation unit, plus the
15981 number of types from all the visible parts of all the visible generic
15982 packages. Generic formal types are not counted. Only types, not subtypes,
15983 are included.
15984
15985 @noindent
15986 Along with the total number of public types, the following
15987 types are counted and reported separately:
15988
15989 @itemize @bullet
15990 @item
15991 Abstract types
15992
15993 @item
15994 Root tagged types (abstract, non-abstract, private, non-private). Type
15995 extensions are @emph{not} counted
15996
15997 @item
15998 Private types (including private extensions)
15999
16000 @item
16001 Task types
16002
16003 @item
16004 Protected types
16005
16006 @end itemize
16007
16008 @item All types
16009 This metric is computed for any compilation unit. It is equal to the total
16010 number of the declarations of different types given in the compilation unit.
16011 The private and the corresponding full type declaration are counted as one
16012 type declaration. Incomplete type declarations and generic formal types
16013 are not counted.
16014 No distinction is made among different kinds of types (abstract,
16015 private etc.); the total number of types is computed and reported.
16016
16017 @end table
16018
16019 @noindent
16020 By default, all the syntax metrics are computed and reported. You can use the
16021 following switches to select specific syntax metrics.
16022
16023 @table @option
16024
16025 @cindex @option{^--syntax@var{x}^/SYNTAX_METRICS^} (@command{gnatmetric})
16026
16027 @ifclear vms
16028 @cindex @option{--no-syntax@var{x}} (@command{gnatmetric})
16029 @end ifclear
16030
16031 @item ^--syntax-all^/SYNTAX_METRICS=ALL^
16032 Report all the syntax metrics
16033
16034 @item ^--no-syntax-all^/SYNTAX_METRICS=NONE^
16035 Do not report any of syntax metrics
16036
16037 @item ^--declarations^/SYNTAX_METRICS=DECLARATIONS^
16038 Report the total number of declarations
16039
16040 @item ^--no-declarations^/SYNTAX_METRICS=NODECLARATIONS^
16041 Do not report the total number of declarations
16042
16043 @item ^--statements^/SYNTAX_METRICS=STATEMENTS^
16044 Report the total number of statements
16045
16046 @item ^--no-statements^/SYNTAX_METRICS=NOSTATEMENTS^
16047 Do not report the total number of statements
16048
16049 @item ^--public-subprograms^/SYNTAX_METRICS=PUBLIC_SUBPROGRAMS^
16050 Report the number of public subprograms in a compilation unit
16051
16052 @item ^--no-public-subprograms^/SYNTAX_METRICS=NOPUBLIC_SUBPROGRAMS^
16053 Do not report the number of public subprograms in a compilation unit
16054
16055 @item ^--all-subprograms^/SYNTAX_METRICS=ALL_SUBPROGRAMS^
16056 Report the number of all the subprograms in a compilation unit
16057
16058 @item ^--no-all-subprograms^/SYNTAX_METRICS=NOALL_SUBPROGRAMS^
16059 Do not report the number of all the subprograms in a compilation unit
16060
16061 @item ^--public-types^/SYNTAX_METRICS=PUBLIC_TYPES^
16062 Report the number of public types in a compilation unit
16063
16064 @item ^--no-public-types^/SYNTAX_METRICS=NOPUBLIC_TYPES^
16065 Do not report the number of public types in a compilation unit
16066
16067 @item ^--all-types^/SYNTAX_METRICS=ALL_TYPES^
16068 Report the number of all the types in a compilation unit
16069
16070 @item ^--no-all-types^/SYNTAX_METRICS=NOALL_TYPES^
16071 Do not report the number of all the types in a compilation unit
16072
16073 @item ^--unit-nesting^/SYNTAX_METRICS=UNIT_NESTING^
16074 Report the maximal program unit nesting level
16075
16076 @item ^--no-unit-nesting^/SYNTAX_METRICS=UNIT_NESTING_OFF^
16077 Do not report the maximal program unit nesting level
16078
16079 @item ^--construct-nesting^/SYNTAX_METRICS=CONSTRUCT_NESTING^
16080 Report the maximal construct nesting level
16081
16082 @item ^--no-construct-nesting^/SYNTAX_METRICS=NOCONSTRUCT_NESTING^
16083 Do not report the maximal construct nesting level
16084
16085 @end table
16086
16087 @node Complexity Metrics Control
16088 @subsubsection Complexity Metrics Control
16089 @cindex Complexity metrics control in @command{gnatmetric}
16090
16091 @noindent
16092 For a program unit that is an executable body (a subprogram body (including
16093 generic bodies), task body, entry body or a package body containing
16094 its own statement sequence) @command{gnatmetric} computes the following
16095 complexity metrics:
16096
16097 @itemize @bullet
16098 @item
16099 McCabe cyclomatic complexity;
16100
16101 @item
16102 McCabe essential complexity;
16103
16104 @item
16105 maximal loop nesting level;
16106
16107 @item
16108 extra exit points (for subprograms);
16109 @end itemize
16110
16111 @noindent
16112 The McCabe cyclomatic complexity metric is defined
16113 in @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf}
16114
16115 According to McCabe, both control statements and short-circuit control forms
16116 should be taken into account when computing cyclomatic complexity.
16117 For Ada 2012 we have also take into account conditional expressions
16118 and quantified expressions. For each body, we compute three metric values:
16119
16120 @itemize @bullet
16121 @item
16122 the complexity introduced by control
16123 statements only, without taking into account short-circuit forms,
16124
16125 @item
16126 the complexity introduced by short-circuit control forms only, and
16127
16128 @item
16129 the total
16130 cyclomatic complexity, which is the sum of these two values.
16131 @end itemize
16132
16133 @noindent
16134
16135 The cyclomatic complexity is also computed for Ada 2012 expression functions.
16136 An expression function cannot have statements as its components, so only one
16137 metric value is computed as a cyclomatic complexity of an expression function.
16138
16139 The origin of cyclomatic complexity metric is the need to estimate the number
16140 of independent paths in the control flow graph that in turn gives the number
16141 of tests needed to satisfy paths coverage testing completeness criterion.
16142 Considered from the testing point of view, a static Ada @code{loop} (that is,
16143 the @code{loop} statement having static subtype in loop parameter
16144 specification) does not add to cyclomatic complexity. By providing
16145 @option{^--no-static-loop^NO_STATIC_LOOP^} option a user
16146 may specify that such loops should not be counted when computing the
16147 cyclomatic complexity metric
16148
16149 The Ada essential complexity metric is a McCabe cyclomatic complexity metric
16150 counted for the code that is reduced by excluding all the pure structural Ada
16151 control statements. An compound statement is considered as a non-structural
16152 if it contains a @code{raise} or @code{return} statement as it subcomponent,
16153 or if it contains a @code{goto} statement that transfers the control outside
16154 the operator. A selective accept statement with @code{terminate} alternative
16155 is considered as non-structural statement. When computing this metric,
16156 @code{exit} statements are treated in the same way as @code{goto}
16157 statements unless @option{^-ne^NO_EXITS_AS_GOTOS^} option is specified.
16158
16159 The Ada essential complexity metric defined here is intended to quantify
16160 the extent to which the software is unstructured. It is adapted from
16161 the McCabe essential complexity metric defined in
16162 @url{http://www.mccabe.com/pdf/mccabe-nist235r.pdf} but is modified to be more
16163 suitable for typical Ada usage. For example, short circuit forms
16164 are not penalized as unstructured in the Ada essential complexity metric.
16165
16166 When computing cyclomatic and essential complexity, @command{gnatmetric} skips
16167 the code in the exception handlers and in all the nested program units. The
16168 code of assertions and predicates (that is, subprogram preconditions and
16169 postconditions, subtype predicates and type invariants) is also skipped.
16170
16171 By default, all the complexity metrics are computed and reported.
16172 For more fine-grained control you can use
16173 the following switches:
16174
16175 @table @option
16176 @cindex @option{^-complexity@var{x}^/COMPLEXITY_METRICS^} (@command{gnatmetric})
16177
16178 @ifclear vms
16179 @cindex @option{--no-complexity@var{x}}
16180 @end ifclear
16181
16182 @item ^--complexity-all^/COMPLEXITY_METRICS=ALL^
16183 Report all the complexity metrics
16184
16185 @item ^--no-complexity-all^/COMPLEXITY_METRICS=NONE^
16186 Do not report any of complexity metrics
16187
16188 @item ^--complexity-cyclomatic^/COMPLEXITY_METRICS=CYCLOMATIC^
16189 Report the McCabe Cyclomatic Complexity
16190
16191 @item ^--no-complexity-cyclomatic^/COMPLEXITY_METRICS=NOCYCLOMATIC^
16192 Do not report the McCabe Cyclomatic Complexity
16193
16194 @item ^--complexity-essential^/COMPLEXITY_METRICS=ESSENTIAL^
16195 Report the Essential Complexity
16196
16197 @item ^--no-complexity-essential^/COMPLEXITY_METRICS=NOESSENTIAL^
16198 Do not report the Essential Complexity
16199
16200 @item ^--loop-nesting^/COMPLEXITY_METRICS=LOOP_NESTING_ON^
16201 Report maximal loop nesting level
16202
16203 @item ^--no-loop-nesting^/COMPLEXITY_METRICS=NOLOOP_NESTING^
16204 Do not report maximal loop nesting level
16205
16206 @item ^--complexity-average^/COMPLEXITY_METRICS=AVERAGE_COMPLEXITY^
16207 Report the average McCabe Cyclomatic Complexity for all the subprogram bodies,
16208 task bodies, entry bodies and statement sequences in package bodies.
16209 The metric is computed and reported for whole set of processed Ada sources
16210 only.
16211
16212 @item ^--no-complexity-average^/COMPLEXITY_METRICS=NOAVERAGE_COMPLEXITY^
16213 Do not report the average McCabe Cyclomatic Complexity for all the subprogram
16214 bodies, task bodies, entry bodies and statement sequences in package bodies
16215
16216 @cindex @option{^-ne^/NO_EXITS_AS_GOTOS^} (@command{gnatmetric})
16217 @item ^-ne^/NO_EXITS_AS_GOTOS^
16218 Do not consider @code{exit} statements as @code{goto}s when
16219 computing Essential Complexity
16220
16221 @cindex @option{^--no-static-loop^/NO_STATIC_LOOP^} (@command{gnatmetric})
16222 @item ^--no-static-loop^/NO_STATIC_LOOP^
16223 Do not consider static loops when computing cyclomatic complexity
16224
16225 @item ^--extra-exit-points^/EXTRA_EXIT_POINTS^
16226 Report the extra exit points for subprogram bodies. As an exit point, this
16227 metric counts @code{return} statements and raise statements in case when the
16228 raised exception is not handled in the same body. In case of a function this
16229 metric subtracts 1 from the number of exit points, because a function body
16230 must contain at least one @code{return} statement.
16231
16232 @item ^--no-extra-exit-points^/NOEXTRA_EXIT_POINTS^
16233 Do not report the extra exit points for subprogram bodies
16234 @end table
16235
16236
16237 @node Coupling Metrics Control
16238 @subsubsection Coupling Metrics Control
16239 @cindex Coupling metrics control in @command{gnatmetric}
16240
16241 @noindent
16242 @cindex Coupling metrics (in @command{gnatmetric})
16243 Coupling metrics measure the dependencies between a given entity and other
16244 entities in the program. This information is useful since high coupling
16245 may signal potential issues with maintainability as the program evolves.
16246
16247 @command{gnatmetric} computes the following coupling metrics:
16248
16249 @itemize @bullet
16250
16251 @item
16252 @emph{object-oriented coupling}, for classes in traditional object-oriented
16253 sense;
16254
16255 @item
16256 @emph{unit coupling}, for all the program units making up a program;
16257
16258 @item
16259 @emph{control coupling}, reflecting dependencies between a unit and
16260 other units that contain subprograms.
16261 @end itemize
16262
16263 @noindent
16264 Two kinds of coupling metrics are computed:
16265
16266 @itemize @bullet
16267 @item fan-out coupling (``efferent coupling''):
16268 @cindex fan-out coupling
16269 @cindex efferent coupling
16270 the number of entities the given entity depends upon. This metric
16271 reflects how the given entity depends on the changes in the
16272 ``external world''.
16273
16274 @item fan-in coupling (``afferent'' coupling):
16275 @cindex fan-in coupling
16276 @cindex afferent coupling
16277 the number of entities that depend on a given entity.
16278 This metric reflects how the ``external world'' depends on the changes in a
16279 given entity.
16280 @end itemize
16281
16282 @noindent
16283 Object-oriented coupling metrics measure the dependencies
16284 between a given class (or a group of classes) and the other classes in the
16285 program. In this subsection the term ``class'' is used in its traditional
16286 object-oriented programming sense (an instantiable module that contains data
16287 and/or method members). A @emph{category} (of classes) is a group of closely
16288 related classes that are reused and/or modified together.
16289
16290 A class @code{K}'s fan-out coupling is the number of classes
16291 that @code{K} depends upon.
16292 A category's fan-out coupling is the number of classes outside the
16293 category that the classes inside the category depend upon.
16294
16295 A class @code{K}'s fan-in coupling is the number of classes
16296 that depend upon @code{K}.
16297 A category's fan-in coupling is the number of classes outside the
16298 category that depend on classes belonging to the category.
16299
16300 Ada's object-oriented paradigm separates the instantiable entity
16301 (type) from the module (package), so the definition of the coupling
16302 metrics for Ada maps the class and class category notions
16303 onto Ada constructs.
16304
16305 For the coupling metrics, several kinds of modules that define a tagged type
16306 or an interface type -- library packages, library generic packages, and
16307 library generic package instantiations -- are considered to be classes.
16308 A category consists of a library package (or
16309 a library generic package) that defines a tagged or an interface type,
16310 together with all its descendant (generic) packages that define tagged
16311 or interface types. Thus a
16312 category is an Ada hierarchy of library-level program units. Class
16313 coupling in Ada is referred to as ``tagged coupling'', and category coupling
16314 is referred to as ``hierarchy coupling''.
16315
16316 For any package serving as a class, its body and subunits (if any) are
16317 considered together with its spec when computing dependencies, and coupling
16318 metrics are reported for spec units only. Dependencies between classes
16319 mean Ada semantic dependencies. For object-oriented coupling
16320 metrics, only dependencies on units treated as classes are
16321 considered.
16322
16323 Similarly, for unit and control coupling an entity is considered to be the
16324 conceptual construct consisting of the entity's specification, body, and
16325 any subunits (transitively).
16326 @command{gnatmetric} computes
16327 the dependencies of all these units as a whole, but
16328 metrics are only reported for spec
16329 units (or for a subprogram body unit in case if there is no
16330 separate spec for the given subprogram).
16331
16332 For unit coupling, dependencies are computed between all kinds of program
16333 units. For control coupling, the dependencies of a given unit are limited to
16334 those units that define subprograms. Thus control fan-out coupling is reported
16335 for all units, but control fan-in coupling is only reported for units
16336 that define subprograms.
16337
16338 The following simple example illustrates the difference between unit coupling
16339 and control coupling metrics:
16340
16341 @smallexample @c ada
16342 @group
16343 package Lib_1 is
16344 function F_1 (I : Integer) return Integer;
16345 end Lib_1;
16346 @end group
16347
16348 @group
16349 package Lib_2 is
16350 type T_2 is new Integer;
16351 end Lib_2;
16352 @end group
16353
16354 @group
16355 package body Lib_1 is
16356 function F_1 (I : Integer) return Integer is
16357 begin
16358 return I + 1;
16359 end F_1;
16360 end Lib_1;
16361 @end group
16362
16363 @group
16364 with Lib_2; use Lib_2;
16365 package Pack is
16366 Var : T_2;
16367 function Fun (I : Integer) return Integer;
16368 end Pack;
16369 @end group
16370
16371 @group
16372 with Lib_1; use Lib_1;
16373 package body Pack is
16374 function Fun (I : Integer) return Integer is
16375 begin
16376 return F_1 (I);
16377 end Fun;
16378 end Pack;
16379 @end group
16380 @end smallexample
16381
16382 @noindent
16383 If we apply @command{gnatmetric} with the @option{--coupling-all} option to
16384 these units, the result will be:
16385
16386 @smallexample
16387 @group
16388 Coupling metrics:
16389 =================
16390 Unit Lib_1 (C:\customers\662\L406-007\lib_1.ads)
16391 control fan-out coupling : 0
16392 control fan-in coupling : 1
16393 unit fan-out coupling : 0
16394 unit fan-in coupling : 1
16395 @end group
16396
16397 @group
16398 Unit Pack (C:\customers\662\L406-007\pack.ads)
16399 control fan-out coupling : 1
16400 control fan-in coupling : 0
16401 unit fan-out coupling : 2
16402 unit fan-in coupling : 0
16403 @end group
16404
16405 @group
16406 Unit Lib_2 (C:\customers\662\L406-007\lib_2.ads)
16407 control fan-out coupling : 0
16408 unit fan-out coupling : 0
16409 unit fan-in coupling : 1
16410 @end group
16411 @end smallexample
16412
16413 @noindent
16414 The result does not contain values for object-oriented
16415 coupling because none of the argument units contains a tagged type and
16416 therefore none of these units can be treated as a class.
16417
16418 The @code{Pack} package (spec and body) depends on two
16419 units -- @code{Lib_1} @code{and Lib_2} -- and so its unit fan-out coupling
16420 is 2. Since nothing depends on it, its unit fan-in coupling is 0, as
16421 is its control fan-in coupling. Only one of the units @code{Pack} depends
16422 upon defines a subprogram, so its control fan-out coupling is 1.
16423
16424 @code{Lib_2} depends on nothing, so its fan-out metrics are 0. It does
16425 not define any subprograms, so it has no control fan-in metric.
16426 One unit (@code{Pack}) depends on it , so its unit fan-in coupling is 1.
16427
16428 @code{Lib_1} is similar to @code{Lib_2}, but it does define a subprogram.
16429 Its control fan-in coupling is 1 (because there is one unit
16430 depending on it).
16431
16432 When computing coupling metrics, @command{gnatmetric} counts only
16433 dependencies between units that are arguments of the @command{gnatmetric}
16434 invocation. Coupling metrics are program-wide (or project-wide) metrics, so
16435 you should invoke @command{gnatmetric} for
16436 the complete set of sources comprising your program. This can be done
16437 by invoking @command{gnatmetric} with the corresponding project file
16438 and with the @option{-U} option.
16439
16440 By default, all the coupling metrics are disabled. You can use the following
16441 switches to specify the coupling metrics to be computed and reported:
16442
16443 @table @option
16444
16445 @ifclear vms
16446 @cindex @option{--tagged-coupling@var{x}} (@command{gnatmetric})
16447 @cindex @option{--hierarchy-coupling@var{x}} (@command{gnatmetric})
16448 @cindex @option{--unit-coupling@var{x}} (@command{gnatmetric})
16449 @cindex @option{--control-coupling@var{x}} (@command{gnatmetric})
16450 @end ifclear
16451
16452 @ifset vms
16453 @cindex @option{/COUPLING_METRICS} (@command{gnatmetric})
16454 @end ifset
16455
16456 @item ^--coupling-all^/COUPLING_METRICS=ALL^
16457 Report all the coupling metrics
16458
16459 @item ^--tagged-coupling-out^/COUPLING_METRICS=TAGGED_OUT^
16460 Report tagged (class) fan-out coupling
16461
16462 @item ^--tagged-coupling-in^/COUPLING_METRICS=TAGGED_IN^
16463 Report tagged (class) fan-in coupling
16464
16465 @item ^--hierarchy-coupling-out^/COUPLING_METRICS=HIERARCHY_OUT^
16466 Report hierarchy (category) fan-out coupling
16467
16468 @item ^--hierarchy-coupling-in^/COUPLING_METRICS=HIERARCHY_IN^
16469 Report hierarchy (category) fan-in coupling
16470
16471 @item ^--unit-coupling-out^/COUPLING_METRICS=UNIT_OUT^
16472 Report unit fan-out coupling
16473
16474 @item ^--unit-coupling-in^/COUPLING_METRICS=UNIT_IN^
16475 Report unit fan-in coupling
16476
16477 @item ^--control-coupling-out^/COUPLING_METRICS=CONTROL_OUT^
16478 Report control fan-out coupling
16479
16480 @item ^--control-coupling-in^/COUPLING_METRICS=CONTROL_IN^
16481 Report control fan-in coupling
16482 @end table
16483
16484 @node Other gnatmetric Switches
16485 @subsection Other @code{gnatmetric} Switches
16486
16487 @noindent
16488 Additional @command{gnatmetric} switches are as follows:
16489
16490 @table @option
16491 @item --version
16492 @cindex @option{--version} @command{gnatmetric}
16493 Display Copyright and version, then exit disregarding all other options.
16494
16495 @item --help
16496 @cindex @option{--help} @command{gnatmetric}
16497 Display usage, then exit disregarding all other options.
16498
16499 @item -P @var{file}
16500 @cindex @option{-P} @command{gnatmetric}
16501 Indicates the name of the project file that describes the set of sources
16502 to be processed. The exact set of argument sources depends on other options
16503 specified, see below.
16504
16505 @item -U
16506 @cindex @option{-U} @command{gnatmetric}
16507 If a project file is specified and no argument source is explicitly
16508 specified (either directly or by means of @option{-files} option), process
16509 all the units of the closure of the argument project. Otherwise this option
16510 has no effect.
16511
16512 @item -U @var{main_unit}
16513 If a project file is specified and no argument source is explicitly
16514 specified (either directly or by means of @option{-files} option), process
16515 the closure of units rooted at @var{main_unit}. Otherwise this option
16516 has no effect.
16517
16518 @item -X@var{name}=@var{value}
16519 @cindex @option{-X} @command{gnatmetric}
16520 Indicates that external variable @var{name} in the argument project
16521 has the value @var{value}. Has no effect if no project is specified as
16522 tool argument.
16523
16524 @item --subdirs=@var{dir}
16525 @cindex @option{--subdirs=@var{dir}} @command{gnatmetric}
16526 Use the specified subdirectory of the project objects file (or of the
16527 project file directory if the project does not specify an object directory)
16528 for tool output files. Has no effect if no project is specified as
16529 tool argument r if @option{--no_objects_dir} is specified.
16530
16531 @item --no_objects_dir
16532 @cindex @option{--no_objects_dir} @command{gnatmetric}
16533 Place all the result files into the current directory instead of
16534 project objects directory. This corresponds to the @command{gnatcheck}
16535 behavior when it is called with the project file from the
16536 GNAT driver. Has no effect if no project is specified.
16537
16538 @item ^-files @var{filename}^/FILES=@var{filename}^
16539 @cindex @option{^-files^/FILES^} (@code{gnatmetric})
16540 Take the argument source files from the specified file. This file should be an
16541 ordinary text file containing file names separated by spaces or
16542 line breaks. You can use this switch more than once in the same call to
16543 @command{gnatmetric}. You also can combine this switch with
16544 an explicit list of files.
16545
16546 @item ^-j^/PROCESSES=^@var{n}
16547 @cindex @option{^-j^/PROCESSES^} (@command{gnatmetric})
16548 Use @var{n} processes to carry out the tree creations (internal representations
16549 of the argument sources). On a multiprocessor machine this speeds up processing
16550 of big sets of argument sources. If @var{n} is 0, then the maximum number of
16551 parallel tree creations is the number of core processors on the platform.
16552
16553 @cindex @option{^-t^/TIME^} (@command{gnatmetric})
16554 @item ^-t^/TIME^
16555 Print out execution time.
16556
16557 @item ^-v^/VERBOSE^
16558 @cindex @option{^-v^/VERBOSE^} (@command{gnatmetric})
16559 Verbose mode;
16560 @command{gnatmetric} generates version information and then
16561 a trace of sources being processed.
16562
16563 @item ^-q^/QUIET^
16564 @cindex @option{^-q^/QUIET^} (@command{gnatmetric})
16565 Quiet mode.
16566 @end table
16567
16568 @noindent
16569 If a project file is specified and no argument source is explicitly
16570 specified (either directly or by means of @option{-files} option), and no
16571 @option{-U} is specified, then the set of processed sources is
16572 all the immediate units of the argument project.
16573
16574
16575 @ignore
16576 @node Generate project-wide metrics
16577 @subsection Generate project-wide metrics
16578
16579 In order to compute metrics on all units of a given project, you can use
16580 the @command{gnat} driver along with the @option{-P} option:
16581 @smallexample
16582 gnat metric -Pproj
16583 @end smallexample
16584
16585 @noindent
16586 If the project @code{proj} depends upon other projects, you can compute
16587 the metrics on the project closure using the @option{-U} option:
16588 @smallexample
16589 gnat metric -Pproj -U
16590 @end smallexample
16591
16592 @noindent
16593 Finally, if not all the units are relevant to a particular main
16594 program in the project closure, you can generate metrics for the set
16595 of units needed to create a given main program (unit closure) using
16596 the @option{-U} option followed by the name of the main unit:
16597 @smallexample
16598 gnat metric -Pproj -U main
16599 @end smallexample
16600 @end ignore
16601 @end ifclear
16602
16603
16604 @c ***********************************
16605 @node File Name Krunching with gnatkr
16606 @chapter File Name Krunching with @code{gnatkr}
16607 @findex gnatkr
16608
16609 @noindent
16610 This chapter discusses the method used by the compiler to shorten
16611 the default file names chosen for Ada units so that they do not
16612 exceed the maximum length permitted. It also describes the
16613 @code{gnatkr} utility that can be used to determine the result of
16614 applying this shortening.
16615 @menu
16616 * About gnatkr::
16617 * Using gnatkr::
16618 * Krunching Method::
16619 * Examples of gnatkr Usage::
16620 @end menu
16621
16622 @node About gnatkr
16623 @section About @code{gnatkr}
16624
16625 @noindent
16626 The default file naming rule in GNAT
16627 is that the file name must be derived from
16628 the unit name. The exact default rule is as follows:
16629 @itemize @bullet
16630 @item
16631 Take the unit name and replace all dots by hyphens.
16632 @item
16633 If such a replacement occurs in the
16634 second character position of a name, and the first character is
16635 ^@samp{a}, @samp{g}, @samp{s}, or @samp{i}, ^@samp{A}, @samp{G}, @samp{S}, or @samp{I},^
16636 then replace the dot by the character
16637 ^@samp{~} (tilde)^@samp{$} (dollar sign)^
16638 instead of a minus.
16639 @end itemize
16640 The reason for this exception is to avoid clashes
16641 with the standard names for children of System, Ada, Interfaces,
16642 and GNAT, which use the prefixes
16643 ^@samp{s-}, @samp{a-}, @samp{i-}, and @samp{g-},^@samp{S-}, @samp{A-}, @samp{I-}, and @samp{G-},^
16644 respectively.
16645
16646 The @option{^-gnatk^/FILE_NAME_MAX_LENGTH=^@var{nn}}
16647 switch of the compiler activates a ``krunching''
16648 circuit that limits file names to nn characters (where nn is a decimal
16649 integer). For example, using OpenVMS,
16650 where the maximum file name length is
16651 39, the value of nn is usually set to 39, but if you want to generate
16652 a set of files that would be usable if ported to a system with some
16653 different maximum file length, then a different value can be specified.
16654 The default value of 39 for OpenVMS need not be specified.
16655
16656 The @code{gnatkr} utility can be used to determine the krunched name for
16657 a given file, when krunched to a specified maximum length.
16658
16659 @node Using gnatkr
16660 @section Using @code{gnatkr}
16661
16662 @noindent
16663 The @code{gnatkr} command has the form
16664
16665 @ifclear vms
16666 @smallexample
16667 @c $ gnatkr @var{name} @ovar{length}
16668 @c Expanding @ovar macro inline (explanation in macro def comments)
16669 $ gnatkr @var{name} @r{[}@var{length}@r{]}
16670 @end smallexample
16671 @end ifclear
16672
16673 @ifset vms
16674 @smallexample
16675 $ gnatkr @var{name} /COUNT=nn
16676 @end smallexample
16677 @end ifset
16678
16679 @noindent
16680 @var{name} is the uncrunched file name, derived from the name of the unit
16681 in the standard manner described in the previous section (i.e., in particular
16682 all dots are replaced by hyphens). The file name may or may not have an
16683 extension (defined as a suffix of the form period followed by arbitrary
16684 characters other than period). If an extension is present then it will
16685 be preserved in the output. For example, when krunching @file{hellofile.ads}
16686 to eight characters, the result will be hellofil.ads.
16687
16688 Note: for compatibility with previous versions of @code{gnatkr} dots may
16689 appear in the name instead of hyphens, but the last dot will always be
16690 taken as the start of an extension. So if @code{gnatkr} is given an argument
16691 such as @file{Hello.World.adb} it will be treated exactly as if the first
16692 period had been a hyphen, and for example krunching to eight characters
16693 gives the result @file{hellworl.adb}.
16694
16695 Note that the result is always all lower case (except on OpenVMS where it is
16696 all upper case). Characters of the other case are folded as required.
16697
16698 @var{length} represents the length of the krunched name. The default
16699 when no argument is given is ^8^39^ characters. A length of zero stands for
16700 unlimited, in other words do not chop except for system files where the
16701 implied crunching length is always eight characters.
16702
16703 @noindent
16704 The output is the krunched name. The output has an extension only if the
16705 original argument was a file name with an extension.
16706
16707 @node Krunching Method
16708 @section Krunching Method
16709
16710 @noindent
16711 The initial file name is determined by the name of the unit that the file
16712 contains. The name is formed by taking the full expanded name of the
16713 unit and replacing the separating dots with hyphens and
16714 using ^lowercase^uppercase^
16715 for all letters, except that a hyphen in the second character position is
16716 replaced by a ^tilde^dollar sign^ if the first character is
16717 ^@samp{a}, @samp{i}, @samp{g}, or @samp{s}^@samp{A}, @samp{I}, @samp{G}, or @samp{S}^.
16718 The extension is @code{.ads} for a
16719 spec and @code{.adb} for a body.
16720 Krunching does not affect the extension, but the file name is shortened to
16721 the specified length by following these rules:
16722
16723 @itemize @bullet
16724 @item
16725 The name is divided into segments separated by hyphens, tildes or
16726 underscores and all hyphens, tildes, and underscores are
16727 eliminated. If this leaves the name short enough, we are done.
16728
16729 @item
16730 If the name is too long, the longest segment is located (left-most
16731 if there are two of equal length), and shortened by dropping
16732 its last character. This is repeated until the name is short enough.
16733
16734 As an example, consider the krunching of @*@file{our-strings-wide_fixed.adb}
16735 to fit the name into 8 characters as required by some operating systems.
16736
16737 @smallexample
16738 our-strings-wide_fixed 22
16739 our strings wide fixed 19
16740 our string wide fixed 18
16741 our strin wide fixed 17
16742 our stri wide fixed 16
16743 our stri wide fixe 15
16744 our str wide fixe 14
16745 our str wid fixe 13
16746 our str wid fix 12
16747 ou str wid fix 11
16748 ou st wid fix 10
16749 ou st wi fix 9
16750 ou st wi fi 8
16751 Final file name: oustwifi.adb
16752 @end smallexample
16753
16754 @item
16755 The file names for all predefined units are always krunched to eight
16756 characters. The krunching of these predefined units uses the following
16757 special prefix replacements:
16758
16759 @table @file
16760 @item ada-
16761 replaced by @file{^a^A^-}
16762
16763 @item gnat-
16764 replaced by @file{^g^G^-}
16765
16766 @item interfaces-
16767 replaced by @file{^i^I^-}
16768
16769 @item system-
16770 replaced by @file{^s^S^-}
16771 @end table
16772
16773 These system files have a hyphen in the second character position. That
16774 is why normal user files replace such a character with a
16775 ^tilde^dollar sign^, to
16776 avoid confusion with system file names.
16777
16778 As an example of this special rule, consider
16779 @*@file{ada-strings-wide_fixed.adb}, which gets krunched as follows:
16780
16781 @smallexample
16782 ada-strings-wide_fixed 22
16783 a- strings wide fixed 18
16784 a- string wide fixed 17
16785 a- strin wide fixed 16
16786 a- stri wide fixed 15
16787 a- stri wide fixe 14
16788 a- str wide fixe 13
16789 a- str wid fixe 12
16790 a- str wid fix 11
16791 a- st wid fix 10
16792 a- st wi fix 9
16793 a- st wi fi 8
16794 Final file name: a-stwifi.adb
16795 @end smallexample
16796 @end itemize
16797
16798 Of course no file shortening algorithm can guarantee uniqueness over all
16799 possible unit names, and if file name krunching is used then it is your
16800 responsibility to ensure that no name clashes occur. The utility
16801 program @code{gnatkr} is supplied for conveniently determining the
16802 krunched name of a file.
16803
16804 @node Examples of gnatkr Usage
16805 @section Examples of @code{gnatkr} Usage
16806
16807 @smallexample
16808 @iftex
16809 @leftskip=0cm
16810 @end iftex
16811 @ifclear vms
16812 $ gnatkr very_long_unit_name.ads --> velounna.ads
16813 $ gnatkr grandparent-parent-child.ads --> grparchi.ads
16814 $ gnatkr Grandparent.Parent.Child.ads --> grparchi.ads
16815 $ gnatkr grandparent-parent-child --> grparchi
16816 @end ifclear
16817 $ gnatkr very_long_unit_name.ads/count=6 --> vlunna.ads
16818 $ gnatkr very_long_unit_name.ads/count=0 --> very_long_unit_name.ads
16819 @end smallexample
16820
16821 @node Preprocessing with gnatprep
16822 @chapter Preprocessing with @code{gnatprep}
16823 @findex gnatprep
16824
16825 @noindent
16826 This chapter discusses how to use GNAT's @code{gnatprep} utility for simple
16827 preprocessing.
16828 Although designed for use with GNAT, @code{gnatprep} does not depend on any
16829 special GNAT features.
16830 For further discussion of conditional compilation in general, see
16831 @ref{Conditional Compilation}.
16832
16833 @menu
16834 * Preprocessing Symbols::
16835 * Using gnatprep::
16836 * Switches for gnatprep::
16837 * Form of Definitions File::
16838 * Form of Input Text for gnatprep::
16839 @end menu
16840
16841 @node Preprocessing Symbols
16842 @section Preprocessing Symbols
16843
16844 @noindent
16845 Preprocessing symbols are defined in definition files and referred to in
16846 sources to be preprocessed. A Preprocessing symbol is an identifier, following
16847 normal Ada (case-insensitive) rules for its syntax, with the restriction that
16848 all characters need to be in the ASCII set (no accented letters).
16849
16850 @node Using gnatprep
16851 @section Using @code{gnatprep}
16852
16853 @noindent
16854 To call @code{gnatprep} use
16855
16856 @smallexample
16857 @c $ gnatprep @ovar{switches} @var{infile} @var{outfile} @ovar{deffile}
16858 @c Expanding @ovar macro inline (explanation in macro def comments)
16859 $ gnatprep @r{[}@var{switches}@r{]} @var{infile} @var{outfile} @r{[}@var{deffile}@r{]}
16860 @end smallexample
16861
16862 @noindent
16863 where
16864 @table @var
16865 @item switches
16866 is an optional sequence of switches as described in the next section.
16867
16868 @item infile
16869 is the full name of the input file, which is an Ada source
16870 file containing preprocessor directives.
16871
16872 @item outfile
16873 is the full name of the output file, which is an Ada source
16874 in standard Ada form. When used with GNAT, this file name will
16875 normally have an ads or adb suffix.
16876
16877 @item deffile
16878 is the full name of a text file containing definitions of
16879 preprocessing symbols to be referenced by the preprocessor. This argument is
16880 optional, and can be replaced by the use of the @option{-D} switch.
16881
16882 @end table
16883
16884 @node Switches for gnatprep
16885 @section Switches for @code{gnatprep}
16886
16887 @table @option
16888 @c !sort!
16889
16890 @item ^-b^/BLANK_LINES^
16891 @cindex @option{^-b^/BLANK_LINES^} (@command{gnatprep})
16892 Causes both preprocessor lines and the lines deleted by
16893 preprocessing to be replaced by blank lines in the output source file,
16894 preserving line numbers in the output file.
16895
16896 @item ^-c^/COMMENTS^
16897 @cindex @option{^-c^/COMMENTS^} (@command{gnatprep})
16898 Causes both preprocessor lines and the lines deleted
16899 by preprocessing to be retained in the output source as comments marked
16900 with the special string @code{"--! "}. This option will result in line numbers
16901 being preserved in the output file.
16902
16903 @item ^-C^/REPLACE_IN_COMMENTS^
16904 @cindex @option{^-C^/REPLACE_IN_COMMENTS^} (@command{gnatprep})
16905 Causes comments to be scanned. Normally comments are ignored by gnatprep.
16906 If this option is specified, then comments are scanned and any $symbol
16907 substitutions performed as in program text. This is particularly useful
16908 when structured comments are used (e.g., when writing programs in the
16909 SPARK dialect of Ada). Note that this switch is not available when
16910 doing integrated preprocessing (it would be useless in this context
16911 since comments are ignored by the compiler in any case).
16912
16913 @item ^-Dsymbol=value^/ASSOCIATE="symbol=value"^
16914 @cindex @option{^-D^/ASSOCIATE^} (@command{gnatprep})
16915 Defines a new preprocessing symbol, associated with value. If no value is given
16916 on the command line, then symbol is considered to be @code{True}. This switch
16917 can be used in place of a definition file.
16918
16919 @ifset vms
16920 @item /REMOVE
16921 @cindex @option{/REMOVE} (@command{gnatprep})
16922 This is the default setting which causes lines deleted by preprocessing
16923 to be entirely removed from the output file.
16924 @end ifset
16925
16926 @item ^-r^/REFERENCE^
16927 @cindex @option{^-r^/REFERENCE^} (@command{gnatprep})
16928 Causes a @code{Source_Reference} pragma to be generated that
16929 references the original input file, so that error messages will use
16930 the file name of this original file. The use of this switch implies
16931 that preprocessor lines are not to be removed from the file, so its
16932 use will force @option{^-b^/BLANK_LINES^} mode if
16933 @option{^-c^/COMMENTS^}
16934 has not been specified explicitly.
16935
16936 Note that if the file to be preprocessed contains multiple units, then
16937 it will be necessary to @code{gnatchop} the output file from
16938 @code{gnatprep}. If a @code{Source_Reference} pragma is present
16939 in the preprocessed file, it will be respected by
16940 @code{gnatchop ^-r^/REFERENCE^}
16941 so that the final chopped files will correctly refer to the original
16942 input source file for @code{gnatprep}.
16943
16944 @item ^-s^/SYMBOLS^
16945 @cindex @option{^-s^/SYMBOLS^} (@command{gnatprep})
16946 Causes a sorted list of symbol names and values to be
16947 listed on the standard output file.
16948
16949 @item ^-u^/UNDEFINED^
16950 @cindex @option{^-u^/UNDEFINED^} (@command{gnatprep})
16951 Causes undefined symbols to be treated as having the value FALSE in the context
16952 of a preprocessor test. In the absence of this option, an undefined symbol in
16953 a @code{#if} or @code{#elsif} test will be treated as an error.
16954
16955 @end table
16956
16957 @ifclear vms
16958 @noindent
16959 Note: if neither @option{-b} nor @option{-c} is present,
16960 then preprocessor lines and
16961 deleted lines are completely removed from the output, unless -r is
16962 specified, in which case -b is assumed.
16963 @end ifclear
16964
16965 @node Form of Definitions File
16966 @section Form of Definitions File
16967
16968 @noindent
16969 The definitions file contains lines of the form
16970
16971 @smallexample
16972 symbol := value
16973 @end smallexample
16974
16975 @noindent
16976 where symbol is a preprocessing symbol, and value is one of the following:
16977
16978 @itemize @bullet
16979 @item
16980 Empty, corresponding to a null substitution
16981 @item
16982 A string literal using normal Ada syntax
16983 @item
16984 Any sequence of characters from the set
16985 (letters, digits, period, underline).
16986 @end itemize
16987
16988 @noindent
16989 Comment lines may also appear in the definitions file, starting with
16990 the usual @code{--},
16991 and comments may be added to the definitions lines.
16992
16993 @node Form of Input Text for gnatprep
16994 @section Form of Input Text for @code{gnatprep}
16995
16996 @noindent
16997 The input text may contain preprocessor conditional inclusion lines,
16998 as well as general symbol substitution sequences.
16999
17000 The preprocessor conditional inclusion commands have the form
17001
17002 @smallexample
17003 @group
17004 @cartouche
17005 #if @i{expression} @r{[}then@r{]}
17006 lines
17007 #elsif @i{expression} @r{[}then@r{]}
17008 lines
17009 #elsif @i{expression} @r{[}then@r{]}
17010 lines
17011 @dots{}
17012 #else
17013 lines
17014 #end if;
17015 @end cartouche
17016 @end group
17017 @end smallexample
17018
17019 @noindent
17020 In this example, @i{expression} is defined by the following grammar:
17021 @smallexample
17022 @i{expression} ::= <symbol>
17023 @i{expression} ::= <symbol> = "<value>"
17024 @i{expression} ::= <symbol> = <symbol>
17025 @i{expression} ::= <symbol> = <integer>
17026 @i{expression} ::= <symbol> > <integer>
17027 @i{expression} ::= <symbol> >= <integer>
17028 @i{expression} ::= <symbol> < <integer>
17029 @i{expression} ::= <symbol> <= <integer>
17030 @i{expression} ::= <symbol> 'Defined
17031 @i{expression} ::= not @i{expression}
17032 @i{expression} ::= @i{expression} and @i{expression}
17033 @i{expression} ::= @i{expression} or @i{expression}
17034 @i{expression} ::= @i{expression} and then @i{expression}
17035 @i{expression} ::= @i{expression} or else @i{expression}
17036 @i{expression} ::= ( @i{expression} )
17037 @end smallexample
17038
17039 The following restriction exists: it is not allowed to have "and" or "or"
17040 following "not" in the same expression without parentheses. For example, this
17041 is not allowed:
17042
17043 @smallexample
17044 not X or Y
17045 @end smallexample
17046
17047 This should be one of the following:
17048
17049 @smallexample
17050 (not X) or Y
17051 not (X or Y)
17052 @end smallexample
17053
17054 @noindent
17055 For the first test (@i{expression} ::= <symbol>) the symbol must have
17056 either the value true or false, that is to say the right-hand of the
17057 symbol definition must be one of the (case-insensitive) literals
17058 @code{True} or @code{False}. If the value is true, then the
17059 corresponding lines are included, and if the value is false, they are
17060 excluded.
17061
17062 When comparing a symbol to an integer, the integer is any non negative
17063 literal integer as defined in the Ada Reference Manual, such as 3, 16#FF# or
17064 2#11#. The symbol value must also be a non negative integer. Integer values
17065 in the range 0 .. 2**31-1 are supported.
17066
17067 The test (@i{expression} ::= <symbol> @code{'Defined}) is true only if
17068 the symbol has been defined in the definition file or by a @option{-D}
17069 switch on the command line. Otherwise, the test is false.
17070
17071 The equality tests are case insensitive, as are all the preprocessor lines.
17072
17073 If the symbol referenced is not defined in the symbol definitions file,
17074 then the effect depends on whether or not switch @option{-u}
17075 is specified. If so, then the symbol is treated as if it had the value
17076 false and the test fails. If this switch is not specified, then
17077 it is an error to reference an undefined symbol. It is also an error to
17078 reference a symbol that is defined with a value other than @code{True}
17079 or @code{False}.
17080
17081 The use of the @code{not} operator inverts the sense of this logical test.
17082 The @code{not} operator cannot be combined with the @code{or} or @code{and}
17083 operators, without parentheses. For example, "if not X or Y then" is not
17084 allowed, but "if (not X) or Y then" and "if not (X or Y) then" are.
17085
17086 The @code{then} keyword is optional as shown
17087
17088 The @code{#} must be the first non-blank character on a line, but
17089 otherwise the format is free form. Spaces or tabs may appear between
17090 the @code{#} and the keyword. The keywords and the symbols are case
17091 insensitive as in normal Ada code. Comments may be used on a
17092 preprocessor line, but other than that, no other tokens may appear on a
17093 preprocessor line. Any number of @code{elsif} clauses can be present,
17094 including none at all. The @code{else} is optional, as in Ada.
17095
17096 The @code{#} marking the start of a preprocessor line must be the first
17097 non-blank character on the line, i.e., it must be preceded only by
17098 spaces or horizontal tabs.
17099
17100 Symbol substitution outside of preprocessor lines is obtained by using
17101 the sequence
17102
17103 @smallexample
17104 $symbol
17105 @end smallexample
17106
17107 @noindent
17108 anywhere within a source line, except in a comment or within a
17109 string literal. The identifier
17110 following the @code{$} must match one of the symbols defined in the symbol
17111 definition file, and the result is to substitute the value of the
17112 symbol in place of @code{$symbol} in the output file.
17113
17114 Note that although the substitution of strings within a string literal
17115 is not possible, it is possible to have a symbol whose defined value is
17116 a string literal. So instead of setting XYZ to @code{hello} and writing:
17117
17118 @smallexample
17119 Header : String := "$XYZ";
17120 @end smallexample
17121
17122 @noindent
17123 you should set XYZ to @code{"hello"} and write:
17124
17125 @smallexample
17126 Header : String := $XYZ;
17127 @end smallexample
17128
17129 @noindent
17130 and then the substitution will occur as desired.
17131
17132 @node The GNAT Library Browser gnatls
17133 @chapter The GNAT Library Browser @code{gnatls}
17134 @findex gnatls
17135 @cindex Library browser
17136
17137 @noindent
17138 @code{gnatls} is a tool that outputs information about compiled
17139 units. It gives the relationship between objects, unit names and source
17140 files. It can also be used to check the source dependencies of a unit
17141 as well as various characteristics.
17142
17143 Note: to invoke @code{gnatls} with a project file, use the @code{gnat}
17144 driver (see @ref{The GNAT Driver and Project Files}).
17145
17146 @menu
17147 * Running gnatls::
17148 * Switches for gnatls::
17149 * Examples of gnatls Usage::
17150 @end menu
17151
17152 @node Running gnatls
17153 @section Running @code{gnatls}
17154
17155 @noindent
17156 The @code{gnatls} command has the form
17157
17158 @smallexample
17159 $ gnatls switches @var{object_or_ali_file}
17160 @end smallexample
17161
17162 @noindent
17163 The main argument is the list of object or @file{ali} files
17164 (@pxref{The Ada Library Information Files})
17165 for which information is requested.
17166
17167 In normal mode, without additional option, @code{gnatls} produces a
17168 four-column listing. Each line represents information for a specific
17169 object. The first column gives the full path of the object, the second
17170 column gives the name of the principal unit in this object, the third
17171 column gives the status of the source and the fourth column gives the
17172 full path of the source representing this unit.
17173 Here is a simple example of use:
17174
17175 @smallexample
17176 $ gnatls *.o
17177 ^./^[]^demo1.o demo1 DIF demo1.adb
17178 ^./^[]^demo2.o demo2 OK demo2.adb
17179 ^./^[]^hello.o h1 OK hello.adb
17180 ^./^[]^instr-child.o instr.child MOK instr-child.adb
17181 ^./^[]^instr.o instr OK instr.adb
17182 ^./^[]^tef.o tef DIF tef.adb
17183 ^./^[]^text_io_example.o text_io_example OK text_io_example.adb
17184 ^./^[]^tgef.o tgef DIF tgef.adb
17185 @end smallexample
17186
17187 @noindent
17188 The first line can be interpreted as follows: the main unit which is
17189 contained in
17190 object file @file{demo1.o} is demo1, whose main source is in
17191 @file{demo1.adb}. Furthermore, the version of the source used for the
17192 compilation of demo1 has been modified (DIF). Each source file has a status
17193 qualifier which can be:
17194
17195 @table @code
17196 @item OK (unchanged)
17197 The version of the source file used for the compilation of the
17198 specified unit corresponds exactly to the actual source file.
17199
17200 @item MOK (slightly modified)
17201 The version of the source file used for the compilation of the
17202 specified unit differs from the actual source file but not enough to
17203 require recompilation. If you use gnatmake with the qualifier
17204 @option{^-m (minimal recompilation)^/MINIMAL_RECOMPILATION^}, a file marked
17205 MOK will not be recompiled.
17206
17207 @item DIF (modified)
17208 No version of the source found on the path corresponds to the source
17209 used to build this object.
17210
17211 @item ??? (file not found)
17212 No source file was found for this unit.
17213
17214 @item HID (hidden, unchanged version not first on PATH)
17215 The version of the source that corresponds exactly to the source used
17216 for compilation has been found on the path but it is hidden by another
17217 version of the same source that has been modified.
17218
17219 @end table
17220
17221 @node Switches for gnatls
17222 @section Switches for @code{gnatls}
17223
17224 @noindent
17225 @code{gnatls} recognizes the following switches:
17226
17227 @table @option
17228 @c !sort!
17229 @cindex @option{--version} @command{gnatls}
17230 Display Copyright and version, then exit disregarding all other options.
17231
17232 @item --help
17233 @cindex @option{--help} @command{gnatls}
17234 If @option{--version} was not used, display usage, then exit disregarding
17235 all other options.
17236
17237 @item ^-a^/ALL_UNITS^
17238 @cindex @option{^-a^/ALL_UNITS^} (@code{gnatls})
17239 Consider all units, including those of the predefined Ada library.
17240 Especially useful with @option{^-d^/DEPENDENCIES^}.
17241
17242 @item ^-d^/DEPENDENCIES^
17243 @cindex @option{^-d^/DEPENDENCIES^} (@code{gnatls})
17244 List sources from which specified units depend on.
17245
17246 @item ^-h^/OUTPUT=OPTIONS^
17247 @cindex @option{^-h^/OUTPUT=OPTIONS^} (@code{gnatls})
17248 Output the list of options.
17249
17250 @item ^-o^/OUTPUT=OBJECTS^
17251 @cindex @option{^-o^/OUTPUT=OBJECTS^} (@code{gnatls})
17252 Only output information about object files.
17253
17254 @item ^-s^/OUTPUT=SOURCES^
17255 @cindex @option{^-s^/OUTPUT=SOURCES^} (@code{gnatls})
17256 Only output information about source files.
17257
17258 @item ^-u^/OUTPUT=UNITS^
17259 @cindex @option{^-u^/OUTPUT=UNITS^} (@code{gnatls})
17260 Only output information about compilation units.
17261
17262 @item ^-files^/FILES^=@var{file}
17263 @cindex @option{^-files^/FILES^} (@code{gnatls})
17264 Take as arguments the files listed in text file @var{file}.
17265 Text file @var{file} may contain empty lines that are ignored.
17266 Each nonempty line should contain the name of an existing file.
17267 Several such switches may be specified simultaneously.
17268
17269 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17270 @itemx ^-aI^/SOURCE_SEARCH=^@var{dir}
17271 @itemx ^-I^/SEARCH=^@var{dir}
17272 @itemx ^-I-^/NOCURRENT_DIRECTORY^
17273 @itemx -nostdinc
17274 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatls})
17275 @cindex @option{^-aI^/SOURCE_SEARCH^} (@code{gnatls})
17276 @cindex @option{^-I^/SEARCH^} (@code{gnatls})
17277 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatls})
17278 Source path manipulation. Same meaning as the equivalent @command{gnatmake}
17279 flags (@pxref{Switches for gnatmake}).
17280
17281 @item ^-aP^/ADD_PROJECT_SEARCH_DIR=^@var{dir}
17282 @cindex @option{^-aP^/ADD_PROJECT_SEARCH_DIR=^} (@code{gnatls})
17283 Add @var{dir} at the beginning of the project search dir.
17284
17285 @item --RTS=@var{rts-path}
17286 @cindex @option{--RTS} (@code{gnatls})
17287 Specifies the default location of the runtime library. Same meaning as the
17288 equivalent @command{gnatmake} flag (@pxref{Switches for gnatmake}).
17289
17290 @item ^-v^/OUTPUT=VERBOSE^
17291 @cindex @option{^-v^/OUTPUT=VERBOSE^} (@code{gnatls})
17292 Verbose mode. Output the complete source, object and project paths. Do not use
17293 the default column layout but instead use long format giving as much as
17294 information possible on each requested units, including special
17295 characteristics such as:
17296
17297 @table @code
17298 @item Preelaborable
17299 The unit is preelaborable in the Ada sense.
17300
17301 @item No_Elab_Code
17302 No elaboration code has been produced by the compiler for this unit.
17303
17304 @item Pure
17305 The unit is pure in the Ada sense.
17306
17307 @item Elaborate_Body
17308 The unit contains a pragma Elaborate_Body.
17309
17310 @item Remote_Types
17311 The unit contains a pragma Remote_Types.
17312
17313 @item Shared_Passive
17314 The unit contains a pragma Shared_Passive.
17315
17316 @item Predefined
17317 This unit is part of the predefined environment and cannot be modified
17318 by the user.
17319
17320 @item Remote_Call_Interface
17321 The unit contains a pragma Remote_Call_Interface.
17322
17323 @end table
17324
17325 @end table
17326
17327 @node Examples of gnatls Usage
17328 @section Example of @code{gnatls} Usage
17329 @ifclear vms
17330
17331 @noindent
17332 Example of using the verbose switch. Note how the source and
17333 object paths are affected by the -I switch.
17334
17335 @smallexample
17336 $ gnatls -v -I.. demo1.o
17337
17338 GNATLS 5.03w (20041123-34)
17339 Copyright 1997-2004 Free Software Foundation, Inc.
17340
17341 Source Search Path:
17342 <Current_Directory>
17343 ../
17344 /home/comar/local/adainclude/
17345
17346 Object Search Path:
17347 <Current_Directory>
17348 ../
17349 /home/comar/local/lib/gcc-lib/x86-linux/3.4.3/adalib/
17350
17351 Project Search Path:
17352 <Current_Directory>
17353 /home/comar/local/lib/gnat/
17354
17355 ./demo1.o
17356 Unit =>
17357 Name => demo1
17358 Kind => subprogram body
17359 Flags => No_Elab_Code
17360 Source => demo1.adb modified
17361 @end smallexample
17362
17363 @noindent
17364 The following is an example of use of the dependency list.
17365 Note the use of the -s switch
17366 which gives a straight list of source files. This can be useful for
17367 building specialized scripts.
17368
17369 @smallexample
17370 $ gnatls -d demo2.o
17371 ./demo2.o demo2 OK demo2.adb
17372 OK gen_list.ads
17373 OK gen_list.adb
17374 OK instr.ads
17375 OK instr-child.ads
17376
17377 $ gnatls -d -s -a demo1.o
17378 demo1.adb
17379 /home/comar/local/adainclude/ada.ads
17380 /home/comar/local/adainclude/a-finali.ads
17381 /home/comar/local/adainclude/a-filico.ads
17382 /home/comar/local/adainclude/a-stream.ads
17383 /home/comar/local/adainclude/a-tags.ads
17384 gen_list.ads
17385 gen_list.adb
17386 /home/comar/local/adainclude/gnat.ads
17387 /home/comar/local/adainclude/g-io.ads
17388 instr.ads
17389 /home/comar/local/adainclude/system.ads
17390 /home/comar/local/adainclude/s-exctab.ads
17391 /home/comar/local/adainclude/s-finimp.ads
17392 /home/comar/local/adainclude/s-finroo.ads
17393 /home/comar/local/adainclude/s-secsta.ads
17394 /home/comar/local/adainclude/s-stalib.ads
17395 /home/comar/local/adainclude/s-stoele.ads
17396 /home/comar/local/adainclude/s-stratt.ads
17397 /home/comar/local/adainclude/s-tasoli.ads
17398 /home/comar/local/adainclude/s-unstyp.ads
17399 /home/comar/local/adainclude/unchconv.ads
17400 @end smallexample
17401 @end ifclear
17402
17403 @ifset vms
17404 @smallexample
17405 GNAT LIST /DEPENDENCIES /OUTPUT=SOURCES /ALL_UNITS DEMO1.ADB
17406
17407 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]ada.ads
17408 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-finali.ads
17409 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-filico.ads
17410 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-stream.ads
17411 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]a-tags.ads
17412 demo1.adb
17413 gen_list.ads
17414 gen_list.adb
17415 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]gnat.ads
17416 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]g-io.ads
17417 instr.ads
17418 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]system.ads
17419 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-exctab.ads
17420 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finimp.ads
17421 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-finroo.ads
17422 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-secsta.ads
17423 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stalib.ads
17424 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stoele.ads
17425 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-stratt.ads
17426 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-tasoli.ads
17427 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]s-unstyp.ads
17428 GNU:[LIB.OPENVMS7_1.2_8_1.ADALIB]unchconv.ads
17429 @end smallexample
17430 @end ifset
17431
17432 @node Cleaning Up with gnatclean
17433 @chapter Cleaning Up with @code{gnatclean}
17434 @findex gnatclean
17435 @cindex Cleaning tool
17436
17437 @noindent
17438 @code{gnatclean} is a tool that allows the deletion of files produced by the
17439 compiler, binder and linker, including ALI files, object files, tree files,
17440 expanded source files, library files, interface copy source files, binder
17441 generated files and executable files.
17442
17443 @menu
17444 * Running gnatclean::
17445 * Switches for gnatclean::
17446 @c * Examples of gnatclean Usage::
17447 @end menu
17448
17449 @node Running gnatclean
17450 @section Running @code{gnatclean}
17451
17452 @noindent
17453 The @code{gnatclean} command has the form:
17454
17455 @smallexample
17456 $ gnatclean switches @var{names}
17457 @end smallexample
17458
17459 @noindent
17460 @var{names} is a list of source file names. Suffixes @code{.^ads^ADS^} and
17461 @code{^adb^ADB^} may be omitted. If a project file is specified using switch
17462 @code{^-P^/PROJECT_FILE=^}, then @var{names} may be completely omitted.
17463
17464 @noindent
17465 In normal mode, @code{gnatclean} delete the files produced by the compiler and,
17466 if switch @code{^-c^/COMPILER_FILES_ONLY^} is not specified, by the binder and
17467 the linker. In informative-only mode, specified by switch
17468 @code{^-n^/NODELETE^}, the list of files that would have been deleted in
17469 normal mode is listed, but no file is actually deleted.
17470
17471 @node Switches for gnatclean
17472 @section Switches for @code{gnatclean}
17473
17474 @noindent
17475 @code{gnatclean} recognizes the following switches:
17476
17477 @table @option
17478 @c !sort!
17479 @cindex @option{--version} @command{gnatclean}
17480 Display Copyright and version, then exit disregarding all other options.
17481
17482 @item --help
17483 @cindex @option{--help} @command{gnatclean}
17484 If @option{--version} was not used, display usage, then exit disregarding
17485 all other options.
17486
17487 @item ^--subdirs^/SUBDIRS^=subdir
17488 Actual object directory of each project file is the subdirectory subdir of the
17489 object directory specified or defaulted in the project file.
17490
17491 @item ^--unchecked-shared-lib-imports^/UNCHECKED_SHARED_LIB_IMPORTS^
17492 By default, shared library projects are not allowed to import static library
17493 projects. When this switch is used on the command line, this restriction is
17494 relaxed.
17495
17496 @item ^-c^/COMPILER_FILES_ONLY^
17497 @cindex @option{^-c^/COMPILER_FILES_ONLY^} (@code{gnatclean})
17498 Only attempt to delete the files produced by the compiler, not those produced
17499 by the binder or the linker. The files that are not to be deleted are library
17500 files, interface copy files, binder generated files and executable files.
17501
17502 @item ^-D ^/DIRECTORY_OBJECTS=^@var{dir}
17503 @cindex @option{^-D^/DIRECTORY_OBJECTS^} (@code{gnatclean})
17504 Indicate that ALI and object files should normally be found in directory
17505 @var{dir}.
17506
17507 @item ^-F^/FULL_PATH_IN_BRIEF_MESSAGES^
17508 @cindex @option{^-F^/FULL_PATH_IN_BRIEF_MESSAGES^} (@code{gnatclean})
17509 When using project files, if some errors or warnings are detected during
17510 parsing and verbose mode is not in effect (no use of switch
17511 ^-v^/VERBOSE^), then error lines start with the full path name of the project
17512 file, rather than its simple file name.
17513
17514 @item ^-h^/HELP^
17515 @cindex @option{^-h^/HELP^} (@code{gnatclean})
17516 Output a message explaining the usage of @code{^gnatclean^gnatclean^}.
17517
17518 @item ^-n^/NODELETE^
17519 @cindex @option{^-n^/NODELETE^} (@code{gnatclean})
17520 Informative-only mode. Do not delete any files. Output the list of the files
17521 that would have been deleted if this switch was not specified.
17522
17523 @item ^-P^/PROJECT_FILE=^@var{project}
17524 @cindex @option{^-P^/PROJECT_FILE^} (@code{gnatclean})
17525 Use project file @var{project}. Only one such switch can be used.
17526 When cleaning a project file, the files produced by the compilation of the
17527 immediate sources or inherited sources of the project files are to be
17528 deleted. This is not depending on the presence or not of executable names
17529 on the command line.
17530
17531 @item ^-q^/QUIET^
17532 @cindex @option{^-q^/QUIET^} (@code{gnatclean})
17533 Quiet output. If there are no errors, do not output anything, except in
17534 verbose mode (switch ^-v^/VERBOSE^) or in informative-only mode
17535 (switch ^-n^/NODELETE^).
17536
17537 @item ^-r^/RECURSIVE^
17538 @cindex @option{^-r^/RECURSIVE^} (@code{gnatclean})
17539 When a project file is specified (using switch ^-P^/PROJECT_FILE=^),
17540 clean all imported and extended project files, recursively. If this switch
17541 is not specified, only the files related to the main project file are to be
17542 deleted. This switch has no effect if no project file is specified.
17543
17544 @item ^-v^/VERBOSE^
17545 @cindex @option{^-v^/VERBOSE^} (@code{gnatclean})
17546 Verbose mode.
17547
17548 @item ^-vP^/MESSAGES_PROJECT_FILE=^@emph{x}
17549 @cindex @option{^-vP^/MESSAGES_PROJECT_FILE^} (@code{gnatclean})
17550 Indicates the verbosity of the parsing of GNAT project files.
17551 @xref{Switches Related to Project Files}.
17552
17553 @item ^-X^/EXTERNAL_REFERENCE=^@var{name=value}
17554 @cindex @option{^-X^/EXTERNAL_REFERENCE^} (@code{gnatclean})
17555 Indicates that external variable @var{name} has the value @var{value}.
17556 The Project Manager will use this value for occurrences of
17557 @code{external(name)} when parsing the project file.
17558 @xref{Switches Related to Project Files}.
17559
17560 @item ^-aO^/OBJECT_SEARCH=^@var{dir}
17561 @cindex @option{^-aO^/OBJECT_SEARCH^} (@code{gnatclean})
17562 When searching for ALI and object files, look in directory
17563 @var{dir}.
17564
17565 @item ^-I^/SEARCH=^@var{dir}
17566 @cindex @option{^-I^/SEARCH^} (@code{gnatclean})
17567 Equivalent to @option{^-aO^/OBJECT_SEARCH=^@var{dir}}.
17568
17569 @item ^-I-^/NOCURRENT_DIRECTORY^
17570 @cindex @option{^-I-^/NOCURRENT_DIRECTORY^} (@code{gnatclean})
17571 @cindex Source files, suppressing search
17572 Do not look for ALI or object files in the directory
17573 where @code{gnatclean} was invoked.
17574
17575 @end table
17576
17577 @c @node Examples of gnatclean Usage
17578 @c @section Examples of @code{gnatclean} Usage
17579
17580 @ifclear vms
17581 @node GNAT and Libraries
17582 @chapter GNAT and Libraries
17583 @cindex Library, building, installing, using
17584
17585 @noindent
17586 This chapter describes how to build and use libraries with GNAT, and also shows
17587 how to recompile the GNAT run-time library. You should be familiar with the
17588 Project Manager facility (@pxref{GNAT Project Manager}) before reading this
17589 chapter.
17590
17591 @menu
17592 * Introduction to Libraries in GNAT::
17593 * General Ada Libraries::
17594 * Stand-alone Ada Libraries::
17595 * Rebuilding the GNAT Run-Time Library::
17596 @end menu
17597
17598 @node Introduction to Libraries in GNAT
17599 @section Introduction to Libraries in GNAT
17600
17601 @noindent
17602 A library is, conceptually, a collection of objects which does not have its
17603 own main thread of execution, but rather provides certain services to the
17604 applications that use it. A library can be either statically linked with the
17605 application, in which case its code is directly included in the application,
17606 or, on platforms that support it, be dynamically linked, in which case
17607 its code is shared by all applications making use of this library.
17608
17609 GNAT supports both types of libraries.
17610 In the static case, the compiled code can be provided in different ways. The
17611 simplest approach is to provide directly the set of objects resulting from
17612 compilation of the library source files. Alternatively, you can group the
17613 objects into an archive using whatever commands are provided by the operating
17614 system. For the latter case, the objects are grouped into a shared library.
17615
17616 In the GNAT environment, a library has three types of components:
17617 @itemize @bullet
17618 @item
17619 Source files.
17620 @item
17621 @file{ALI} files.
17622 @xref{The Ada Library Information Files}.
17623 @item
17624 Object files, an archive or a shared library.
17625 @end itemize
17626
17627 @noindent
17628 A GNAT library may expose all its source files, which is useful for
17629 documentation purposes. Alternatively, it may expose only the units needed by
17630 an external user to make use of the library. That is to say, the specs
17631 reflecting the library services along with all the units needed to compile
17632 those specs, which can include generic bodies or any body implementing an
17633 inlined routine. In the case of @emph{stand-alone libraries} those exposed
17634 units are called @emph{interface units} (@pxref{Stand-alone Ada Libraries}).
17635
17636 All compilation units comprising an application, including those in a library,
17637 need to be elaborated in an order partially defined by Ada's semantics. GNAT
17638 computes the elaboration order from the @file{ALI} files and this is why they
17639 constitute a mandatory part of GNAT libraries.
17640 @emph{Stand-alone libraries} are the exception to this rule because a specific
17641 library elaboration routine is produced independently of the application(s)
17642 using the library.
17643
17644 @node General Ada Libraries
17645 @section General Ada Libraries
17646
17647 @menu
17648 * Building a library::
17649 * Installing a library::
17650 * Using a library::
17651 @end menu
17652
17653 @node Building a library
17654 @subsection Building a library
17655
17656 @noindent
17657 The easiest way to build a library is to use the Project Manager,
17658 which supports a special type of project called a @emph{Library Project}
17659 (@pxref{Library Projects}).
17660
17661 A project is considered a library project, when two project-level attributes
17662 are defined in it: @code{Library_Name} and @code{Library_Dir}. In order to
17663 control different aspects of library configuration, additional optional
17664 project-level attributes can be specified:
17665 @table @code
17666 @item Library_Kind
17667 This attribute controls whether the library is to be static or dynamic
17668
17669 @item Library_Version
17670 This attribute specifies the library version; this value is used
17671 during dynamic linking of shared libraries to determine if the currently
17672 installed versions of the binaries are compatible.
17673
17674 @item Library_Options
17675 @item Library_GCC
17676 These attributes specify additional low-level options to be used during
17677 library generation, and redefine the actual application used to generate
17678 library.
17679 @end table
17680
17681 @noindent
17682 The GNAT Project Manager takes full care of the library maintenance task,
17683 including recompilation of the source files for which objects do not exist
17684 or are not up to date, assembly of the library archive, and installation of
17685 the library (i.e., copying associated source, object and @file{ALI} files
17686 to the specified location).
17687
17688 Here is a simple library project file:
17689 @smallexample @c ada
17690 project My_Lib is
17691 for Source_Dirs use ("src1", "src2");
17692 for Object_Dir use "obj";
17693 for Library_Name use "mylib";
17694 for Library_Dir use "lib";
17695 for Library_Kind use "dynamic";
17696 end My_lib;
17697 @end smallexample
17698
17699 @noindent
17700 and the compilation command to build and install the library:
17701
17702 @smallexample @c ada
17703 $ gnatmake -Pmy_lib
17704 @end smallexample
17705
17706 @noindent
17707 It is not entirely trivial to perform manually all the steps required to
17708 produce a library. We recommend that you use the GNAT Project Manager
17709 for this task. In special cases where this is not desired, the necessary
17710 steps are discussed below.
17711
17712 There are various possibilities for compiling the units that make up the
17713 library: for example with a Makefile (@pxref{Using the GNU make Utility}) or
17714 with a conventional script. For simple libraries, it is also possible to create
17715 a dummy main program which depends upon all the packages that comprise the
17716 interface of the library. This dummy main program can then be given to
17717 @command{gnatmake}, which will ensure that all necessary objects are built.
17718
17719 After this task is accomplished, you should follow the standard procedure
17720 of the underlying operating system to produce the static or shared library.
17721
17722 Here is an example of such a dummy program:
17723 @smallexample @c ada
17724 @group
17725 with My_Lib.Service1;
17726 with My_Lib.Service2;
17727 with My_Lib.Service3;
17728 procedure My_Lib_Dummy is
17729 begin
17730 null;
17731 end;
17732 @end group
17733 @end smallexample
17734
17735 @noindent
17736 Here are the generic commands that will build an archive or a shared library.
17737
17738 @smallexample
17739 # compiling the library
17740 $ gnatmake -c my_lib_dummy.adb
17741
17742 # we don't need the dummy object itself
17743 $ rm my_lib_dummy.o my_lib_dummy.ali
17744
17745 # create an archive with the remaining objects
17746 $ ar rc libmy_lib.a *.o
17747 # some systems may require "ranlib" to be run as well
17748
17749 # or create a shared library
17750 $ gcc -shared -o libmy_lib.so *.o
17751 # some systems may require the code to have been compiled with -fPIC
17752
17753 # remove the object files that are now in the library
17754 $ rm *.o
17755
17756 # Make the ALI files read-only so that gnatmake will not try to
17757 # regenerate the objects that are in the library
17758 $ chmod -w *.ali
17759 @end smallexample
17760
17761 @noindent
17762 Please note that the library must have a name of the form @file{lib@var{xxx}.a}
17763 or @file{lib@var{xxx}.so} (or @file{lib@var{xxx}.dll} on Windows) in order to
17764 be accessed by the directive @option{-l@var{xxx}} at link time.
17765
17766 @node Installing a library
17767 @subsection Installing a library
17768 @cindex @code{ADA_PROJECT_PATH}
17769 @cindex @code{GPR_PROJECT_PATH}
17770
17771 @noindent
17772 If you use project files, library installation is part of the library build
17773 process (@pxref{Installing a library with project files}).
17774
17775 When project files are not an option, it is also possible, but not recommended,
17776 to install the library so that the sources needed to use the library are on the
17777 Ada source path and the ALI files & libraries be on the Ada Object path (see
17778 @ref{Search Paths and the Run-Time Library (RTL)}. Alternatively, the system
17779 administrator can place general-purpose libraries in the default compiler
17780 paths, by specifying the libraries' location in the configuration files
17781 @file{ada_source_path} and @file{ada_object_path}. These configuration files
17782 must be located in the GNAT installation tree at the same place as the gcc spec
17783 file. The location of the gcc spec file can be determined as follows:
17784 @smallexample
17785 $ gcc -v
17786 @end smallexample
17787
17788 @noindent
17789 The configuration files mentioned above have a simple format: each line
17790 must contain one unique directory name.
17791 Those names are added to the corresponding path
17792 in their order of appearance in the file. The names can be either absolute
17793 or relative; in the latter case, they are relative to where theses files
17794 are located.
17795
17796 The files @file{ada_source_path} and @file{ada_object_path} might not be
17797 present in a
17798 GNAT installation, in which case, GNAT will look for its run-time library in
17799 the directories @file{adainclude} (for the sources) and @file{adalib} (for the
17800 objects and @file{ALI} files). When the files exist, the compiler does not
17801 look in @file{adainclude} and @file{adalib}, and thus the
17802 @file{ada_source_path} file
17803 must contain the location for the GNAT run-time sources (which can simply
17804 be @file{adainclude}). In the same way, the @file{ada_object_path} file must
17805 contain the location for the GNAT run-time objects (which can simply
17806 be @file{adalib}).
17807
17808 You can also specify a new default path to the run-time library at compilation
17809 time with the switch @option{--RTS=rts-path}. You can thus choose / change
17810 the run-time library you want your program to be compiled with. This switch is
17811 recognized by @command{gcc}, @command{gnatmake}, @command{gnatbind},
17812 @command{gnatls}, @command{gnatfind} and @command{gnatxref}.
17813
17814 It is possible to install a library before or after the standard GNAT
17815 library, by reordering the lines in the configuration files. In general, a
17816 library must be installed before the GNAT library if it redefines
17817 any part of it.
17818
17819 @node Using a library
17820 @subsection Using a library
17821
17822 @noindent Once again, the project facility greatly simplifies the use of
17823 libraries. In this context, using a library is just a matter of adding a
17824 @code{with} clause in the user project. For instance, to make use of the
17825 library @code{My_Lib} shown in examples in earlier sections, you can
17826 write:
17827
17828 @smallexample @c projectfile
17829 with "my_lib";
17830 project My_Proj is
17831 @dots{}
17832 end My_Proj;
17833 @end smallexample
17834
17835 Even if you have a third-party, non-Ada library, you can still use GNAT's
17836 Project Manager facility to provide a wrapper for it. For example, the
17837 following project, when @code{with}ed by your main project, will link with the
17838 third-party library @file{liba.a}:
17839
17840 @smallexample @c projectfile
17841 @group
17842 project Liba is
17843 for Externally_Built use "true";
17844 for Source_Files use ();
17845 for Library_Dir use "lib";
17846 for Library_Name use "a";
17847 for Library_Kind use "static";
17848 end Liba;
17849 @end group
17850 @end smallexample
17851 This is an alternative to the use of @code{pragma Linker_Options}. It is
17852 especially interesting in the context of systems with several interdependent
17853 static libraries where finding a proper linker order is not easy and best be
17854 left to the tools having visibility over project dependence information.
17855
17856 @noindent
17857 In order to use an Ada library manually, you need to make sure that this
17858 library is on both your source and object path
17859 (see @ref{Search Paths and the Run-Time Library (RTL)}
17860 and @ref{Search Paths for gnatbind}). Furthermore, when the objects are grouped
17861 in an archive or a shared library, you need to specify the desired
17862 library at link time.
17863
17864 For example, you can use the library @file{mylib} installed in
17865 @file{/dir/my_lib_src} and @file{/dir/my_lib_obj} with the following commands:
17866
17867 @smallexample
17868 $ gnatmake -aI/dir/my_lib_src -aO/dir/my_lib_obj my_appl \
17869 -largs -lmy_lib
17870 @end smallexample
17871
17872 @noindent
17873 This can be expressed more simply:
17874 @smallexample
17875 $ gnatmake my_appl
17876 @end smallexample
17877 @noindent
17878 when the following conditions are met:
17879 @itemize @bullet
17880 @item
17881 @file{/dir/my_lib_src} has been added by the user to the environment
17882 variable @env{ADA_INCLUDE_PATH}, or by the administrator to the file
17883 @file{ada_source_path}
17884 @item
17885 @file{/dir/my_lib_obj} has been added by the user to the environment
17886 variable @env{ADA_OBJECTS_PATH}, or by the administrator to the file
17887 @file{ada_object_path}
17888 @item
17889 a pragma @code{Linker_Options} has been added to one of the sources.
17890 For example:
17891
17892 @smallexample @c ada
17893 pragma Linker_Options ("-lmy_lib");
17894 @end smallexample
17895 @end itemize
17896
17897 @node Stand-alone Ada Libraries
17898 @section Stand-alone Ada Libraries
17899 @cindex Stand-alone library, building, using
17900
17901 @menu
17902 * Introduction to Stand-alone Libraries::
17903 * Building a Stand-alone Library::
17904 * Creating a Stand-alone Library to be used in a non-Ada context::
17905 * Restrictions in Stand-alone Libraries::
17906 @end menu
17907
17908 @node Introduction to Stand-alone Libraries
17909 @subsection Introduction to Stand-alone Libraries
17910
17911 @noindent
17912 A Stand-alone Library (abbreviated ``SAL'') is a library that contains the
17913 necessary code to
17914 elaborate the Ada units that are included in the library. In contrast with
17915 an ordinary library, which consists of all sources, objects and @file{ALI}
17916 files of the
17917 library, a SAL may specify a restricted subset of compilation units
17918 to serve as a library interface. In this case, the fully
17919 self-sufficient set of files will normally consist of an objects
17920 archive, the sources of interface units' specs, and the @file{ALI}
17921 files of interface units.
17922 If an interface spec contains a generic unit or an inlined subprogram,
17923 the body's
17924 source must also be provided; if the units that must be provided in the source
17925 form depend on other units, the source and @file{ALI} files of those must
17926 also be provided.
17927
17928 The main purpose of a SAL is to minimize the recompilation overhead of client
17929 applications when a new version of the library is installed. Specifically,
17930 if the interface sources have not changed, client applications do not need to
17931 be recompiled. If, furthermore, a SAL is provided in the shared form and its
17932 version, controlled by @code{Library_Version} attribute, is not changed,
17933 then the clients do not need to be relinked.
17934
17935 SALs also allow the library providers to minimize the amount of library source
17936 text exposed to the clients. Such ``information hiding'' might be useful or
17937 necessary for various reasons.
17938
17939 Stand-alone libraries are also well suited to be used in an executable whose
17940 main routine is not written in Ada.
17941
17942 @node Building a Stand-alone Library
17943 @subsection Building a Stand-alone Library
17944
17945 @noindent
17946 GNAT's Project facility provides a simple way of building and installing
17947 stand-alone libraries; see @ref{Stand-alone Library Projects}.
17948 To be a Stand-alone Library Project, in addition to the two attributes
17949 that make a project a Library Project (@code{Library_Name} and
17950 @code{Library_Dir}; see @ref{Library Projects}), the attribute
17951 @code{Library_Interface} must be defined. For example:
17952
17953 @smallexample @c projectfile
17954 @group
17955 for Library_Dir use "lib_dir";
17956 for Library_Name use "dummy";
17957 for Library_Interface use ("int1", "int1.child");
17958 @end group
17959 @end smallexample
17960
17961 @noindent
17962 Attribute @code{Library_Interface} has a non-empty string list value,
17963 each string in the list designating a unit contained in an immediate source
17964 of the project file.
17965
17966 When a Stand-alone Library is built, first the binder is invoked to build
17967 a package whose name depends on the library name
17968 (@file{^b~dummy.ads/b^B$DUMMY.ADS/B^} in the example above).
17969 This binder-generated package includes initialization and
17970 finalization procedures whose
17971 names depend on the library name (@code{dummyinit} and @code{dummyfinal}
17972 in the example
17973 above). The object corresponding to this package is included in the library.
17974
17975 You must ensure timely (e.g., prior to any use of interfaces in the SAL)
17976 calling of these procedures if a static SAL is built, or if a shared SAL
17977 is built
17978 with the project-level attribute @code{Library_Auto_Init} set to
17979 @code{"false"}.
17980
17981 For a Stand-Alone Library, only the @file{ALI} files of the Interface Units
17982 (those that are listed in attribute @code{Library_Interface}) are copied to
17983 the Library Directory. As a consequence, only the Interface Units may be
17984 imported from Ada units outside of the library. If other units are imported,
17985 the binding phase will fail.
17986
17987 @noindent
17988 It is also possible to build an encapsulated library where not only
17989 the code to elaborate and finalize the library is embedded but also
17990 ensuring that the library is linked only against static
17991 libraries. So an encapsulated library only depends on system
17992 libraries, all other code, including the GNAT runtime, is embedded. To
17993 build an encapsulated library the attribute
17994 @code{Library_Standalone} must be set to @code{encapsulated}:
17995
17996 @smallexample @c projectfile
17997 @group
17998 for Library_Dir use "lib_dir";
17999 for Library_Name use "dummy";
18000 for Library_Kind use "dynamic";
18001 for Library_Interface use ("int1", "int1.child");
18002 for Library_Standalone use "encapsulated";
18003 @end group
18004 @end smallexample
18005
18006 @noindent
18007 The default value for this attribute is @code{standard} in which case
18008 a stand-alone library is built.
18009
18010 The attribute @code{Library_Src_Dir} may be specified for a
18011 Stand-Alone Library. @code{Library_Src_Dir} is a simple attribute that has a
18012 single string value. Its value must be the path (absolute or relative to the
18013 project directory) of an existing directory. This directory cannot be the
18014 object directory or one of the source directories, but it can be the same as
18015 the library directory. The sources of the Interface
18016 Units of the library that are needed by an Ada client of the library will be
18017 copied to the designated directory, called the Interface Copy directory.
18018 These sources include the specs of the Interface Units, but they may also
18019 include bodies and subunits, when pragmas @code{Inline} or @code{Inline_Always}
18020 are used, or when there is a generic unit in the spec. Before the sources
18021 are copied to the Interface Copy directory, an attempt is made to delete all
18022 files in the Interface Copy directory.
18023
18024 Building stand-alone libraries by hand is somewhat tedious, but for those
18025 occasions when it is necessary here are the steps that you need to perform:
18026 @itemize @bullet
18027 @item
18028 Compile all library sources.
18029
18030 @item
18031 Invoke the binder with the switch @option{-n} (No Ada main program),
18032 with all the @file{ALI} files of the interfaces, and
18033 with the switch @option{-L} to give specific names to the @code{init}
18034 and @code{final} procedures. For example:
18035 @smallexample
18036 gnatbind -n int1.ali int2.ali -Lsal1
18037 @end smallexample
18038
18039 @item
18040 Compile the binder generated file:
18041 @smallexample
18042 gcc -c b~int2.adb
18043 @end smallexample
18044
18045 @item
18046 Link the dynamic library with all the necessary object files,
18047 indicating to the linker the names of the @code{init} (and possibly
18048 @code{final}) procedures for automatic initialization (and finalization).
18049 The built library should be placed in a directory different from
18050 the object directory.
18051
18052 @item
18053 Copy the @code{ALI} files of the interface to the library directory,
18054 add in this copy an indication that it is an interface to a SAL
18055 (i.e., add a word @option{SL} on the line in the @file{ALI} file that starts
18056 with letter ``P'') and make the modified copy of the @file{ALI} file
18057 read-only.
18058 @end itemize
18059
18060 @noindent
18061 Using SALs is not different from using other libraries
18062 (see @ref{Using a library}).
18063
18064 @node Creating a Stand-alone Library to be used in a non-Ada context
18065 @subsection Creating a Stand-alone Library to be used in a non-Ada context
18066
18067 @noindent
18068 It is easy to adapt the SAL build procedure discussed above for use of a SAL in
18069 a non-Ada context.
18070
18071 The only extra step required is to ensure that library interface subprograms
18072 are compatible with the main program, by means of @code{pragma Export}
18073 or @code{pragma Convention}.
18074
18075 Here is an example of simple library interface for use with C main program:
18076
18077 @smallexample @c ada
18078 package My_Package is
18079
18080 procedure Do_Something;
18081 pragma Export (C, Do_Something, "do_something");
18082
18083 procedure Do_Something_Else;
18084 pragma Export (C, Do_Something_Else, "do_something_else");
18085
18086 end My_Package;
18087 @end smallexample
18088
18089 @noindent
18090 On the foreign language side, you must provide a ``foreign'' view of the
18091 library interface; remember that it should contain elaboration routines in
18092 addition to interface subprograms.
18093
18094 The example below shows the content of @code{mylib_interface.h} (note
18095 that there is no rule for the naming of this file, any name can be used)
18096 @smallexample
18097 /* the library elaboration procedure */
18098 extern void mylibinit (void);
18099
18100 /* the library finalization procedure */
18101 extern void mylibfinal (void);
18102
18103 /* the interface exported by the library */
18104 extern void do_something (void);
18105 extern void do_something_else (void);
18106 @end smallexample
18107
18108 @noindent
18109 Libraries built as explained above can be used from any program, provided
18110 that the elaboration procedures (named @code{mylibinit} in the previous
18111 example) are called before the library services are used. Any number of
18112 libraries can be used simultaneously, as long as the elaboration
18113 procedure of each library is called.
18114
18115 Below is an example of a C program that uses the @code{mylib} library.
18116
18117 @smallexample
18118 #include "mylib_interface.h"
18119
18120 int
18121 main (void)
18122 @{
18123 /* First, elaborate the library before using it */
18124 mylibinit ();
18125
18126 /* Main program, using the library exported entities */
18127 do_something ();
18128 do_something_else ();
18129
18130 /* Library finalization at the end of the program */
18131 mylibfinal ();
18132 return 0;
18133 @}
18134 @end smallexample
18135
18136 @noindent
18137 Note that invoking any library finalization procedure generated by
18138 @code{gnatbind} shuts down the Ada run-time environment.
18139 Consequently, the
18140 finalization of all Ada libraries must be performed at the end of the program.
18141 No call to these libraries or to the Ada run-time library should be made
18142 after the finalization phase.
18143
18144 @node Restrictions in Stand-alone Libraries
18145 @subsection Restrictions in Stand-alone Libraries
18146
18147 @noindent
18148 The pragmas listed below should be used with caution inside libraries,
18149 as they can create incompatibilities with other Ada libraries:
18150 @itemize @bullet
18151 @item pragma @code{Locking_Policy}
18152 @item pragma @code{Partition_Elaboration_Policy}
18153 @item pragma @code{Queuing_Policy}
18154 @item pragma @code{Task_Dispatching_Policy}
18155 @item pragma @code{Unreserve_All_Interrupts}
18156 @end itemize
18157
18158 @noindent
18159 When using a library that contains such pragmas, the user must make sure
18160 that all libraries use the same pragmas with the same values. Otherwise,
18161 @code{Program_Error} will
18162 be raised during the elaboration of the conflicting
18163 libraries. The usage of these pragmas and its consequences for the user
18164 should therefore be well documented.
18165
18166 Similarly, the traceback in the exception occurrence mechanism should be
18167 enabled or disabled in a consistent manner across all libraries.
18168 Otherwise, Program_Error will be raised during the elaboration of the
18169 conflicting libraries.
18170
18171 If the @code{Version} or @code{Body_Version}
18172 attributes are used inside a library, then you need to
18173 perform a @code{gnatbind} step that specifies all @file{ALI} files in all
18174 libraries, so that version identifiers can be properly computed.
18175 In practice these attributes are rarely used, so this is unlikely
18176 to be a consideration.
18177
18178 @node Rebuilding the GNAT Run-Time Library
18179 @section Rebuilding the GNAT Run-Time Library
18180 @cindex GNAT Run-Time Library, rebuilding
18181 @cindex Building the GNAT Run-Time Library
18182 @cindex Rebuilding the GNAT Run-Time Library
18183 @cindex Run-Time Library, rebuilding
18184
18185 @noindent
18186 It may be useful to recompile the GNAT library in various contexts, the
18187 most important one being the use of partition-wide configuration pragmas
18188 such as @code{Normalize_Scalars}. A special Makefile called
18189 @code{Makefile.adalib} is provided to that effect and can be found in
18190 the directory containing the GNAT library. The location of this
18191 directory depends on the way the GNAT environment has been installed and can
18192 be determined by means of the command:
18193
18194 @smallexample
18195 $ gnatls -v
18196 @end smallexample
18197
18198 @noindent
18199 The last entry in the object search path usually contains the
18200 gnat library. This Makefile contains its own documentation and in
18201 particular the set of instructions needed to rebuild a new library and
18202 to use it.
18203
18204 @node Using the GNU make Utility
18205 @chapter Using the GNU @code{make} Utility
18206 @findex make
18207
18208 @noindent
18209 This chapter offers some examples of makefiles that solve specific
18210 problems. It does not explain how to write a makefile (@pxref{Top,, GNU
18211 make, make, GNU @code{make}}), nor does it try to replace the
18212 @command{gnatmake} utility (@pxref{The GNAT Make Program gnatmake}).
18213
18214 All the examples in this section are specific to the GNU version of
18215 make. Although @command{make} is a standard utility, and the basic language
18216 is the same, these examples use some advanced features found only in
18217 @code{GNU make}.
18218
18219 @menu
18220 * Using gnatmake in a Makefile::
18221 * Automatically Creating a List of Directories::
18222 * Generating the Command Line Switches::
18223 * Overcoming Command Line Length Limits::
18224 @end menu
18225
18226 @node Using gnatmake in a Makefile
18227 @section Using gnatmake in a Makefile
18228 @findex makefile
18229 @cindex GNU make
18230
18231 @noindent
18232 Complex project organizations can be handled in a very powerful way by
18233 using GNU make combined with gnatmake. For instance, here is a Makefile
18234 which allows you to build each subsystem of a big project into a separate
18235 shared library. Such a makefile allows you to significantly reduce the link
18236 time of very big applications while maintaining full coherence at
18237 each step of the build process.
18238
18239 The list of dependencies are handled automatically by
18240 @command{gnatmake}. The Makefile is simply used to call gnatmake in each of
18241 the appropriate directories.
18242
18243 Note that you should also read the example on how to automatically
18244 create the list of directories
18245 (@pxref{Automatically Creating a List of Directories})
18246 which might help you in case your project has a lot of subdirectories.
18247
18248 @smallexample
18249 @iftex
18250 @leftskip=0cm
18251 @font@heightrm=cmr8
18252 @heightrm
18253 @end iftex
18254 ## This Makefile is intended to be used with the following directory
18255 ## configuration:
18256 ## - The sources are split into a series of csc (computer software components)
18257 ## Each of these csc is put in its own directory.
18258 ## Their name are referenced by the directory names.
18259 ## They will be compiled into shared library (although this would also work
18260 ## with static libraries
18261 ## - The main program (and possibly other packages that do not belong to any
18262 ## csc is put in the top level directory (where the Makefile is).
18263 ## toplevel_dir __ first_csc (sources) __ lib (will contain the library)
18264 ## \_ second_csc (sources) __ lib (will contain the library)
18265 ## \_ @dots{}
18266 ## Although this Makefile is build for shared library, it is easy to modify
18267 ## to build partial link objects instead (modify the lines with -shared and
18268 ## gnatlink below)
18269 ##
18270 ## With this makefile, you can change any file in the system or add any new
18271 ## file, and everything will be recompiled correctly (only the relevant shared
18272 ## objects will be recompiled, and the main program will be re-linked).
18273
18274 # The list of computer software component for your project. This might be
18275 # generated automatically.
18276 CSC_LIST=aa bb cc
18277
18278 # Name of the main program (no extension)
18279 MAIN=main
18280
18281 # If we need to build objects with -fPIC, uncomment the following line
18282 #NEED_FPIC=-fPIC
18283
18284 # The following variable should give the directory containing libgnat.so
18285 # You can get this directory through 'gnatls -v'. This is usually the last
18286 # directory in the Object_Path.
18287 GLIB=@dots{}
18288
18289 # The directories for the libraries
18290 # (This macro expands the list of CSC to the list of shared libraries, you
18291 # could simply use the expanded form:
18292 # LIB_DIR=aa/lib/libaa.so bb/lib/libbb.so cc/lib/libcc.so
18293 LIB_DIR=$@{foreach dir,$@{CSC_LIST@},$@{dir@}/lib/lib$@{dir@}.so@}
18294
18295 $@{MAIN@}: objects $@{LIB_DIR@}
18296 gnatbind $@{MAIN@} $@{CSC_LIST:%=-aO%/lib@} -shared
18297 gnatlink $@{MAIN@} $@{CSC_LIST:%=-l%@}
18298
18299 objects::
18300 # recompile the sources
18301 gnatmake -c -i $@{MAIN@}.adb $@{NEED_FPIC@} $@{CSC_LIST:%=-I%@}
18302
18303 # Note: In a future version of GNAT, the following commands will be simplified
18304 # by a new tool, gnatmlib
18305 $@{LIB_DIR@}:
18306 mkdir -p $@{dir $@@ @}
18307 cd $@{dir $@@ @} && gcc -shared -o $@{notdir $@@ @} ../*.o -L$@{GLIB@} -lgnat
18308 cd $@{dir $@@ @} && cp -f ../*.ali .
18309
18310 # The dependencies for the modules
18311 # Note that we have to force the expansion of *.o, since in some cases
18312 # make won't be able to do it itself.
18313 aa/lib/libaa.so: $@{wildcard aa/*.o@}
18314 bb/lib/libbb.so: $@{wildcard bb/*.o@}
18315 cc/lib/libcc.so: $@{wildcard cc/*.o@}
18316
18317 # Make sure all of the shared libraries are in the path before starting the
18318 # program
18319 run::
18320 LD_LIBRARY_PATH=`pwd`/aa/lib:`pwd`/bb/lib:`pwd`/cc/lib ./$@{MAIN@}
18321
18322 clean::
18323 $@{RM@} -rf $@{CSC_LIST:%=%/lib@}
18324 $@{RM@} $@{CSC_LIST:%=%/*.ali@}
18325 $@{RM@} $@{CSC_LIST:%=%/*.o@}
18326 $@{RM@} *.o *.ali $@{MAIN@}
18327 @end smallexample
18328
18329 @node Automatically Creating a List of Directories
18330 @section Automatically Creating a List of Directories
18331
18332 @noindent
18333 In most makefiles, you will have to specify a list of directories, and
18334 store it in a variable. For small projects, it is often easier to
18335 specify each of them by hand, since you then have full control over what
18336 is the proper order for these directories, which ones should be
18337 included.
18338
18339 However, in larger projects, which might involve hundreds of
18340 subdirectories, it might be more convenient to generate this list
18341 automatically.
18342
18343 The example below presents two methods. The first one, although less
18344 general, gives you more control over the list. It involves wildcard
18345 characters, that are automatically expanded by @command{make}. Its
18346 shortcoming is that you need to explicitly specify some of the
18347 organization of your project, such as for instance the directory tree
18348 depth, whether some directories are found in a separate tree, @enddots{}
18349
18350 The second method is the most general one. It requires an external
18351 program, called @command{find}, which is standard on all Unix systems. All
18352 the directories found under a given root directory will be added to the
18353 list.
18354
18355 @smallexample
18356 @iftex
18357 @leftskip=0cm
18358 @font@heightrm=cmr8
18359 @heightrm
18360 @end iftex
18361 # The examples below are based on the following directory hierarchy:
18362 # All the directories can contain any number of files
18363 # ROOT_DIRECTORY -> a -> aa -> aaa
18364 # -> ab
18365 # -> ac
18366 # -> b -> ba -> baa
18367 # -> bb
18368 # -> bc
18369 # This Makefile creates a variable called DIRS, that can be reused any time
18370 # you need this list (see the other examples in this section)
18371
18372 # The root of your project's directory hierarchy
18373 ROOT_DIRECTORY=.
18374
18375 ####
18376 # First method: specify explicitly the list of directories
18377 # This allows you to specify any subset of all the directories you need.
18378 ####
18379
18380 DIRS := a/aa/ a/ab/ b/ba/
18381
18382 ####
18383 # Second method: use wildcards
18384 # Note that the argument(s) to wildcard below should end with a '/'.
18385 # Since wildcards also return file names, we have to filter them out
18386 # to avoid duplicate directory names.
18387 # We thus use make's @code{dir} and @code{sort} functions.
18388 # It sets DIRs to the following value (note that the directories aaa and baa
18389 # are not given, unless you change the arguments to wildcard).
18390 # DIRS= ./a/a/ ./b/ ./a/aa/ ./a/ab/ ./a/ac/ ./b/ba/ ./b/bb/ ./b/bc/
18391 ####
18392
18393 DIRS := $@{sort $@{dir $@{wildcard $@{ROOT_DIRECTORY@}/*/
18394 $@{ROOT_DIRECTORY@}/*/*/@}@}@}
18395
18396 ####
18397 # Third method: use an external program
18398 # This command is much faster if run on local disks, avoiding NFS slowdowns.
18399 # This is the most complete command: it sets DIRs to the following value:
18400 # DIRS= ./a ./a/aa ./a/aa/aaa ./a/ab ./a/ac ./b ./b/ba ./b/ba/baa ./b/bb ./b/bc
18401 ####
18402
18403 DIRS := $@{shell find $@{ROOT_DIRECTORY@} -type d -print@}
18404
18405 @end smallexample
18406
18407 @node Generating the Command Line Switches
18408 @section Generating the Command Line Switches
18409
18410 @noindent
18411 Once you have created the list of directories as explained in the
18412 previous section (@pxref{Automatically Creating a List of Directories}),
18413 you can easily generate the command line arguments to pass to gnatmake.
18414
18415 For the sake of completeness, this example assumes that the source path
18416 is not the same as the object path, and that you have two separate lists
18417 of directories.
18418
18419 @smallexample
18420 # see "Automatically creating a list of directories" to create
18421 # these variables
18422 SOURCE_DIRS=
18423 OBJECT_DIRS=
18424
18425 GNATMAKE_SWITCHES := $@{patsubst %,-aI%,$@{SOURCE_DIRS@}@}
18426 GNATMAKE_SWITCHES += $@{patsubst %,-aO%,$@{OBJECT_DIRS@}@}
18427
18428 all:
18429 gnatmake $@{GNATMAKE_SWITCHES@} main_unit
18430 @end smallexample
18431
18432 @node Overcoming Command Line Length Limits
18433 @section Overcoming Command Line Length Limits
18434
18435 @noindent
18436 One problem that might be encountered on big projects is that many
18437 operating systems limit the length of the command line. It is thus hard to give
18438 gnatmake the list of source and object directories.
18439
18440 This example shows how you can set up environment variables, which will
18441 make @command{gnatmake} behave exactly as if the directories had been
18442 specified on the command line, but have a much higher length limit (or
18443 even none on most systems).
18444
18445 It assumes that you have created a list of directories in your Makefile,
18446 using one of the methods presented in
18447 @ref{Automatically Creating a List of Directories}.
18448 For the sake of completeness, we assume that the object
18449 path (where the ALI files are found) is different from the sources patch.
18450
18451 Note a small trick in the Makefile below: for efficiency reasons, we
18452 create two temporary variables (SOURCE_LIST and OBJECT_LIST), that are
18453 expanded immediately by @code{make}. This way we overcome the standard
18454 make behavior which is to expand the variables only when they are
18455 actually used.
18456
18457 On Windows, if you are using the standard Windows command shell, you must
18458 replace colons with semicolons in the assignments to these variables.
18459
18460 @smallexample
18461 @iftex
18462 @leftskip=0cm
18463 @font@heightrm=cmr8
18464 @heightrm
18465 @end iftex
18466 # In this example, we create both ADA_INCLUDE_PATH and ADA_OBJECTS_PATH.
18467 # This is the same thing as putting the -I arguments on the command line.
18468 # (the equivalent of using -aI on the command line would be to define
18469 # only ADA_INCLUDE_PATH, the equivalent of -aO is ADA_OBJECTS_PATH).
18470 # You can of course have different values for these variables.
18471 #
18472 # Note also that we need to keep the previous values of these variables, since
18473 # they might have been set before running 'make' to specify where the GNAT
18474 # library is installed.
18475
18476 # see "Automatically creating a list of directories" to create these
18477 # variables
18478 SOURCE_DIRS=
18479 OBJECT_DIRS=
18480
18481 empty:=
18482 space:=$@{empty@} $@{empty@}
18483 SOURCE_LIST := $@{subst $@{space@},:,$@{SOURCE_DIRS@}@}
18484 OBJECT_LIST := $@{subst $@{space@},:,$@{OBJECT_DIRS@}@}
18485 ADA_INCLUDE_PATH += $@{SOURCE_LIST@}
18486 ADA_OBJECTS_PATH += $@{OBJECT_LIST@}
18487 export ADA_INCLUDE_PATH
18488 export ADA_OBJECTS_PATH
18489
18490 all:
18491 gnatmake main_unit
18492 @end smallexample
18493 @end ifclear
18494
18495 @node Memory Management Issues
18496 @chapter Memory Management Issues
18497
18498 @noindent
18499 This chapter describes some useful memory pools provided in the GNAT library
18500 and in particular the GNAT Debug Pool facility, which can be used to detect
18501 incorrect uses of access values (including ``dangling references'').
18502 @ifclear vms
18503 @ifclear FSFEDITION
18504 It also describes the @command{gnatmem} tool, which can be used to track down
18505 ``memory leaks''.
18506 @end ifclear
18507 @end ifclear
18508
18509 @menu
18510 * Some Useful Memory Pools::
18511 * The GNAT Debug Pool Facility::
18512 @ifclear vms
18513 @ifclear FSFEDITION
18514 * The gnatmem Tool::
18515 @end ifclear
18516 @end ifclear
18517 @end menu
18518
18519 @node Some Useful Memory Pools
18520 @section Some Useful Memory Pools
18521 @findex Memory Pool
18522 @cindex storage, pool
18523
18524 @noindent
18525 The @code{System.Pool_Global} package offers the Unbounded_No_Reclaim_Pool
18526 storage pool. Allocations use the standard system call @code{malloc} while
18527 deallocations use the standard system call @code{free}. No reclamation is
18528 performed when the pool goes out of scope. For performance reasons, the
18529 standard default Ada allocators/deallocators do not use any explicit storage
18530 pools but if they did, they could use this storage pool without any change in
18531 behavior. That is why this storage pool is used when the user
18532 manages to make the default implicit allocator explicit as in this example:
18533 @smallexample @c ada
18534 type T1 is access Something;
18535 -- no Storage pool is defined for T2
18536 type T2 is access Something_Else;
18537 for T2'Storage_Pool use T1'Storage_Pool;
18538 -- the above is equivalent to
18539 for T2'Storage_Pool use System.Pool_Global.Global_Pool_Object;
18540 @end smallexample
18541
18542 @noindent
18543 The @code{System.Pool_Local} package offers the Unbounded_Reclaim_Pool storage
18544 pool. The allocation strategy is similar to @code{Pool_Local}'s
18545 except that the all
18546 storage allocated with this pool is reclaimed when the pool object goes out of
18547 scope. This pool provides a explicit mechanism similar to the implicit one
18548 provided by several Ada 83 compilers for allocations performed through a local
18549 access type and whose purpose was to reclaim memory when exiting the
18550 scope of a given local access. As an example, the following program does not
18551 leak memory even though it does not perform explicit deallocation:
18552
18553 @smallexample @c ada
18554 with System.Pool_Local;
18555 procedure Pooloc1 is
18556 procedure Internal is
18557 type A is access Integer;
18558 X : System.Pool_Local.Unbounded_Reclaim_Pool;
18559 for A'Storage_Pool use X;
18560 v : A;
18561 begin
18562 for I in 1 .. 50 loop
18563 v := new Integer;
18564 end loop;
18565 end Internal;
18566 begin
18567 for I in 1 .. 100 loop
18568 Internal;
18569 end loop;
18570 end Pooloc1;
18571 @end smallexample
18572
18573 @noindent
18574 The @code{System.Pool_Size} package implements the Stack_Bounded_Pool used when
18575 @code{Storage_Size} is specified for an access type.
18576 The whole storage for the pool is
18577 allocated at once, usually on the stack at the point where the access type is
18578 elaborated. It is automatically reclaimed when exiting the scope where the
18579 access type is defined. This package is not intended to be used directly by the
18580 user and it is implicitly used for each such declaration:
18581
18582 @smallexample @c ada
18583 type T1 is access Something;
18584 for T1'Storage_Size use 10_000;
18585 @end smallexample
18586
18587 @node The GNAT Debug Pool Facility
18588 @section The GNAT Debug Pool Facility
18589 @findex Debug Pool
18590 @cindex storage, pool, memory corruption
18591
18592 @noindent
18593 The use of unchecked deallocation and unchecked conversion can easily
18594 lead to incorrect memory references. The problems generated by such
18595 references are usually difficult to tackle because the symptoms can be
18596 very remote from the origin of the problem. In such cases, it is
18597 very helpful to detect the problem as early as possible. This is the
18598 purpose of the Storage Pool provided by @code{GNAT.Debug_Pools}.
18599
18600 In order to use the GNAT specific debugging pool, the user must
18601 associate a debug pool object with each of the access types that may be
18602 related to suspected memory problems. See Ada Reference Manual 13.11.
18603 @smallexample @c ada
18604 type Ptr is access Some_Type;
18605 Pool : GNAT.Debug_Pools.Debug_Pool;
18606 for Ptr'Storage_Pool use Pool;
18607 @end smallexample
18608
18609 @noindent
18610 @code{GNAT.Debug_Pools} is derived from a GNAT-specific kind of
18611 pool: the @code{Checked_Pool}. Such pools, like standard Ada storage pools,
18612 allow the user to redefine allocation and deallocation strategies. They
18613 also provide a checkpoint for each dereference, through the use of
18614 the primitive operation @code{Dereference} which is implicitly called at
18615 each dereference of an access value.
18616
18617 Once an access type has been associated with a debug pool, operations on
18618 values of the type may raise four distinct exceptions,
18619 which correspond to four potential kinds of memory corruption:
18620 @itemize @bullet
18621 @item
18622 @code{GNAT.Debug_Pools.Accessing_Not_Allocated_Storage}
18623 @item
18624 @code{GNAT.Debug_Pools.Accessing_Deallocated_Storage}
18625 @item
18626 @code{GNAT.Debug_Pools.Freeing_Not_Allocated_Storage}
18627 @item
18628 @code{GNAT.Debug_Pools.Freeing_Deallocated_Storage }
18629 @end itemize
18630
18631 @noindent
18632 For types associated with a Debug_Pool, dynamic allocation is performed using
18633 the standard GNAT allocation routine. References to all allocated chunks of
18634 memory are kept in an internal dictionary. Several deallocation strategies are
18635 provided, whereupon the user can choose to release the memory to the system,
18636 keep it allocated for further invalid access checks, or fill it with an easily
18637 recognizable pattern for debug sessions. The memory pattern is the old IBM
18638 hexadecimal convention: @code{16#DEADBEEF#}.
18639
18640 See the documentation in the file g-debpoo.ads for more information on the
18641 various strategies.
18642
18643 Upon each dereference, a check is made that the access value denotes a
18644 properly allocated memory location. Here is a complete example of use of
18645 @code{Debug_Pools}, that includes typical instances of memory corruption:
18646 @smallexample @c ada
18647 @iftex
18648 @leftskip=0cm
18649 @end iftex
18650 with Gnat.Io; use Gnat.Io;
18651 with Unchecked_Deallocation;
18652 with Unchecked_Conversion;
18653 with GNAT.Debug_Pools;
18654 with System.Storage_Elements;
18655 with Ada.Exceptions; use Ada.Exceptions;
18656 procedure Debug_Pool_Test is
18657
18658 type T is access Integer;
18659 type U is access all T;
18660
18661 P : GNAT.Debug_Pools.Debug_Pool;
18662 for T'Storage_Pool use P;
18663
18664 procedure Free is new Unchecked_Deallocation (Integer, T);
18665 function UC is new Unchecked_Conversion (U, T);
18666 A, B : aliased T;
18667
18668 procedure Info is new GNAT.Debug_Pools.Print_Info(Put_Line);
18669
18670 begin
18671 Info (P);
18672 A := new Integer;
18673 B := new Integer;
18674 B := A;
18675 Info (P);
18676 Free (A);
18677 begin
18678 Put_Line (Integer'Image(B.all));
18679 exception
18680 when E : others => Put_Line ("raised: " & Exception_Name (E));
18681 end;
18682 begin
18683 Free (B);
18684 exception
18685 when E : others => Put_Line ("raised: " & Exception_Name (E));
18686 end;
18687 B := UC(A'Access);
18688 begin
18689 Put_Line (Integer'Image(B.all));
18690 exception
18691 when E : others => Put_Line ("raised: " & Exception_Name (E));
18692 end;
18693 begin
18694 Free (B);
18695 exception
18696 when E : others => Put_Line ("raised: " & Exception_Name (E));
18697 end;
18698 Info (P);
18699 end Debug_Pool_Test;
18700 @end smallexample
18701
18702 @noindent
18703 The debug pool mechanism provides the following precise diagnostics on the
18704 execution of this erroneous program:
18705 @smallexample
18706 Debug Pool info:
18707 Total allocated bytes : 0
18708 Total deallocated bytes : 0
18709 Current Water Mark: 0
18710 High Water Mark: 0
18711
18712 Debug Pool info:
18713 Total allocated bytes : 8
18714 Total deallocated bytes : 0
18715 Current Water Mark: 8
18716 High Water Mark: 8
18717
18718 raised: GNAT.DEBUG_POOLS.ACCESSING_DEALLOCATED_STORAGE
18719 raised: GNAT.DEBUG_POOLS.FREEING_DEALLOCATED_STORAGE
18720 raised: GNAT.DEBUG_POOLS.ACCESSING_NOT_ALLOCATED_STORAGE
18721 raised: GNAT.DEBUG_POOLS.FREEING_NOT_ALLOCATED_STORAGE
18722 Debug Pool info:
18723 Total allocated bytes : 8
18724 Total deallocated bytes : 4
18725 Current Water Mark: 4
18726 High Water Mark: 8
18727 @end smallexample
18728
18729 @ifclear vms
18730 @ifclear FSFEDITION
18731 @node The gnatmem Tool
18732 @section The @command{gnatmem} Tool
18733 @findex gnatmem
18734
18735 @noindent
18736 The @code{gnatmem} utility monitors dynamic allocation and
18737 deallocation activity in a program, and displays information about
18738 incorrect deallocations and possible sources of memory leaks.
18739 It is designed to work in association with a static runtime library
18740 only and in this context provides three types of information:
18741 @itemize @bullet
18742 @item
18743 General information concerning memory management, such as the total
18744 number of allocations and deallocations, the amount of allocated
18745 memory and the high water mark, i.e.@: the largest amount of allocated
18746 memory in the course of program execution.
18747
18748 @item
18749 Backtraces for all incorrect deallocations, that is to say deallocations
18750 which do not correspond to a valid allocation.
18751
18752 @item
18753 Information on each allocation that is potentially the origin of a memory
18754 leak.
18755 @end itemize
18756
18757 @menu
18758 * Running gnatmem::
18759 * Switches for gnatmem::
18760 * Example of gnatmem Usage::
18761 @end menu
18762
18763 @node Running gnatmem
18764 @subsection Running @code{gnatmem}
18765
18766 @noindent
18767 @code{gnatmem} makes use of the output created by the special version of
18768 allocation and deallocation routines that record call information. This
18769 allows to obtain accurate dynamic memory usage history at a minimal cost to
18770 the execution speed. Note however, that @code{gnatmem} is not supported on
18771 all platforms (currently, it is supported on AIX, HP-UX, GNU/Linux,
18772 Solaris and Windows NT/2000/XP (x86).
18773
18774 @noindent
18775 The @code{gnatmem} command has the form
18776
18777 @smallexample
18778 @c $ gnatmem @ovar{switches} user_program
18779 @c Expanding @ovar macro inline (explanation in macro def comments)
18780 $ gnatmem @r{[}@var{switches}@r{]} @var{user_program}
18781 @end smallexample
18782
18783 @noindent
18784 The program must have been linked with the instrumented version of the
18785 allocation and deallocation routines. This is done by linking with the
18786 @file{libgmem.a} library. For correct symbolic backtrace information,
18787 the user program should be compiled with debugging options
18788 (see @ref{Switches for gcc}). For example to build @file{my_program}:
18789
18790 @smallexample
18791 $ gnatmake -g my_program -largs -lgmem
18792 @end smallexample
18793
18794 @noindent
18795 As library @file{libgmem.a} contains an alternate body for package
18796 @code{System.Memory}, @file{s-memory.adb} should not be compiled and linked
18797 when an executable is linked with library @file{libgmem.a}. It is then not
18798 recommended to use @command{gnatmake} with switch @option{^-a^/ALL_FILES^}.
18799
18800 @noindent
18801 When @file{my_program} is executed, the file @file{gmem.out} is produced.
18802 This file contains information about all allocations and deallocations
18803 performed by the program. It is produced by the instrumented allocations and
18804 deallocations routines and will be used by @code{gnatmem}.
18805
18806 In order to produce symbolic backtrace information for allocations and
18807 deallocations performed by the GNAT run-time library, you need to use a
18808 version of that library that has been compiled with the @option{-g} switch
18809 (see @ref{Rebuilding the GNAT Run-Time Library}).
18810
18811 Gnatmem must be supplied with the @file{gmem.out} file and the executable to
18812 examine. If the location of @file{gmem.out} file was not explicitly supplied by
18813 @option{-i} switch, gnatmem will assume that this file can be found in the
18814 current directory. For example, after you have executed @file{my_program},
18815 @file{gmem.out} can be analyzed by @code{gnatmem} using the command:
18816
18817 @smallexample
18818 $ gnatmem my_program
18819 @end smallexample
18820
18821 @noindent
18822 This will produce the output with the following format:
18823
18824 *************** debut cc
18825 @smallexample
18826 $ gnatmem my_program
18827
18828 Global information
18829 ------------------
18830 Total number of allocations : 45
18831 Total number of deallocations : 6
18832 Final Water Mark (non freed mem) : 11.29 Kilobytes
18833 High Water Mark : 11.40 Kilobytes
18834
18835 .
18836 .
18837 .
18838 Allocation Root # 2
18839 -------------------
18840 Number of non freed allocations : 11
18841 Final Water Mark (non freed mem) : 1.16 Kilobytes
18842 High Water Mark : 1.27 Kilobytes
18843 Backtrace :
18844 my_program.adb:23 my_program.alloc
18845 .
18846 .
18847 .
18848 @end smallexample
18849
18850 The first block of output gives general information. In this case, the
18851 Ada construct ``@code{@b{new}}'' was executed 45 times, and only 6 calls to an
18852 Unchecked_Deallocation routine occurred.
18853
18854 @noindent
18855 Subsequent paragraphs display information on all allocation roots.
18856 An allocation root is a specific point in the execution of the program
18857 that generates some dynamic allocation, such as a ``@code{@b{new}}''
18858 construct. This root is represented by an execution backtrace (or subprogram
18859 call stack). By default the backtrace depth for allocations roots is 1, so
18860 that a root corresponds exactly to a source location. The backtrace can
18861 be made deeper, to make the root more specific.
18862
18863 @node Switches for gnatmem
18864 @subsection Switches for @code{gnatmem}
18865
18866 @noindent
18867 @code{gnatmem} recognizes the following switches:
18868
18869 @table @option
18870
18871 @item -q
18872 @cindex @option{-q} (@code{gnatmem})
18873 Quiet. Gives the minimum output needed to identify the origin of the
18874 memory leaks. Omits statistical information.
18875
18876 @item @var{N}
18877 @cindex @var{N} (@code{gnatmem})
18878 N is an integer literal (usually between 1 and 10) which controls the
18879 depth of the backtraces defining allocation root. The default value for
18880 N is 1. The deeper the backtrace, the more precise the localization of
18881 the root. Note that the total number of roots can depend on this
18882 parameter. This parameter must be specified @emph{before} the name of the
18883 executable to be analyzed, to avoid ambiguity.
18884
18885 @item -b n
18886 @cindex @option{-b} (@code{gnatmem})
18887 This switch has the same effect as just depth parameter.
18888
18889 @item -i @var{file}
18890 @cindex @option{-i} (@code{gnatmem})
18891 Do the @code{gnatmem} processing starting from @file{file}, rather than
18892 @file{gmem.out} in the current directory.
18893
18894 @item -m n
18895 @cindex @option{-m} (@code{gnatmem})
18896 This switch causes @code{gnatmem} to mask the allocation roots that have less
18897 than n leaks. The default value is 1. Specifying the value of 0 will allow to
18898 examine even the roots that didn't result in leaks.
18899
18900 @item -s order
18901 @cindex @option{-s} (@code{gnatmem})
18902 This switch causes @code{gnatmem} to sort the allocation roots according to the
18903 specified order of sort criteria, each identified by a single letter. The
18904 currently supported criteria are @code{n, h, w} standing respectively for
18905 number of unfreed allocations, high watermark, and final watermark
18906 corresponding to a specific root. The default order is @code{nwh}.
18907
18908 @end table
18909
18910 @node Example of gnatmem Usage
18911 @subsection Example of @code{gnatmem} Usage
18912
18913 @noindent
18914 The following example shows the use of @code{gnatmem}
18915 on a simple memory-leaking program.
18916 Suppose that we have the following Ada program:
18917
18918 @smallexample @c ada
18919 @group
18920 @cartouche
18921 with Unchecked_Deallocation;
18922 procedure Test_Gm is
18923
18924 type T is array (1..1000) of Integer;
18925 type Ptr is access T;
18926 procedure Free is new Unchecked_Deallocation (T, Ptr);
18927 A : Ptr;
18928
18929 procedure My_Alloc is
18930 begin
18931 A := new T;
18932 end My_Alloc;
18933
18934 procedure My_DeAlloc is
18935 B : Ptr := A;
18936 begin
18937 Free (B);
18938 end My_DeAlloc;
18939
18940 begin
18941 My_Alloc;
18942 for I in 1 .. 5 loop
18943 for J in I .. 5 loop
18944 My_Alloc;
18945 end loop;
18946 My_Dealloc;
18947 end loop;
18948 end;
18949 @end cartouche
18950 @end group
18951 @end smallexample
18952
18953 @noindent
18954 The program needs to be compiled with debugging option and linked with
18955 @code{gmem} library:
18956
18957 @smallexample
18958 $ gnatmake -g test_gm -largs -lgmem
18959 @end smallexample
18960
18961 @noindent
18962 Then we execute the program as usual:
18963
18964 @smallexample
18965 $ test_gm
18966 @end smallexample
18967
18968 @noindent
18969 Then @code{gnatmem} is invoked simply with
18970 @smallexample
18971 $ gnatmem test_gm
18972 @end smallexample
18973
18974 @noindent
18975 which produces the following output (result may vary on different platforms):
18976
18977 @smallexample
18978 Global information
18979 ------------------
18980 Total number of allocations : 18
18981 Total number of deallocations : 5
18982 Final Water Mark (non freed mem) : 53.00 Kilobytes
18983 High Water Mark : 56.90 Kilobytes
18984
18985 Allocation Root # 1
18986 -------------------
18987 Number of non freed allocations : 11
18988 Final Water Mark (non freed mem) : 42.97 Kilobytes
18989 High Water Mark : 46.88 Kilobytes
18990 Backtrace :
18991 test_gm.adb:11 test_gm.my_alloc
18992
18993 Allocation Root # 2
18994 -------------------
18995 Number of non freed allocations : 1
18996 Final Water Mark (non freed mem) : 10.02 Kilobytes
18997 High Water Mark : 10.02 Kilobytes
18998 Backtrace :
18999 s-secsta.adb:81 system.secondary_stack.ss_init
19000
19001 Allocation Root # 3
19002 -------------------
19003 Number of non freed allocations : 1
19004 Final Water Mark (non freed mem) : 12 Bytes
19005 High Water Mark : 12 Bytes
19006 Backtrace :
19007 s-secsta.adb:181 system.secondary_stack.ss_init
19008 @end smallexample
19009
19010 @noindent
19011 Note that the GNAT run time contains itself a certain number of
19012 allocations that have no corresponding deallocation,
19013 as shown here for root #2 and root
19014 #3. This is a normal behavior when the number of non-freed allocations
19015 is one, it allocates dynamic data structures that the run time needs for
19016 the complete lifetime of the program. Note also that there is only one
19017 allocation root in the user program with a single line back trace:
19018 test_gm.adb:11 test_gm.my_alloc, whereas a careful analysis of the
19019 program shows that 'My_Alloc' is called at 2 different points in the
19020 source (line 21 and line 24). If those two allocation roots need to be
19021 distinguished, the backtrace depth parameter can be used:
19022
19023 @smallexample
19024 $ gnatmem 3 test_gm
19025 @end smallexample
19026
19027 @noindent
19028 which will give the following output:
19029
19030 @smallexample
19031 Global information
19032 ------------------
19033 Total number of allocations : 18
19034 Total number of deallocations : 5
19035 Final Water Mark (non freed mem) : 53.00 Kilobytes
19036 High Water Mark : 56.90 Kilobytes
19037
19038 Allocation Root # 1
19039 -------------------
19040 Number of non freed allocations : 10
19041 Final Water Mark (non freed mem) : 39.06 Kilobytes
19042 High Water Mark : 42.97 Kilobytes
19043 Backtrace :
19044 test_gm.adb:11 test_gm.my_alloc
19045 test_gm.adb:24 test_gm
19046 b_test_gm.c:52 main
19047
19048 Allocation Root # 2
19049 -------------------
19050 Number of non freed allocations : 1
19051 Final Water Mark (non freed mem) : 10.02 Kilobytes
19052 High Water Mark : 10.02 Kilobytes
19053 Backtrace :
19054 s-secsta.adb:81 system.secondary_stack.ss_init
19055 s-secsta.adb:283 <system__secondary_stack___elabb>
19056 b_test_gm.c:33 adainit
19057
19058 Allocation Root # 3
19059 -------------------
19060 Number of non freed allocations : 1
19061 Final Water Mark (non freed mem) : 3.91 Kilobytes
19062 High Water Mark : 3.91 Kilobytes
19063 Backtrace :
19064 test_gm.adb:11 test_gm.my_alloc
19065 test_gm.adb:21 test_gm
19066 b_test_gm.c:52 main
19067
19068 Allocation Root # 4
19069 -------------------
19070 Number of non freed allocations : 1
19071 Final Water Mark (non freed mem) : 12 Bytes
19072 High Water Mark : 12 Bytes
19073 Backtrace :
19074 s-secsta.adb:181 system.secondary_stack.ss_init
19075 s-secsta.adb:283 <system__secondary_stack___elabb>
19076 b_test_gm.c:33 adainit
19077 @end smallexample
19078
19079 @noindent
19080 The allocation root #1 of the first example has been split in 2 roots #1
19081 and #3 thanks to the more precise associated backtrace.
19082 @end ifclear
19083 @end ifclear
19084
19085 @node Stack Related Facilities
19086 @chapter Stack Related Facilities
19087
19088 @noindent
19089 This chapter describes some useful tools associated with stack
19090 checking and analysis. In
19091 particular, it deals with dynamic and static stack usage measurements.
19092
19093 @menu
19094 * Stack Overflow Checking::
19095 * Static Stack Usage Analysis::
19096 * Dynamic Stack Usage Analysis::
19097 @end menu
19098
19099 @node Stack Overflow Checking
19100 @section Stack Overflow Checking
19101 @cindex Stack Overflow Checking
19102 @cindex -fstack-check
19103
19104 @noindent
19105 For most operating systems, @command{gcc} does not perform stack overflow
19106 checking by default. This means that if the main environment task or
19107 some other task exceeds the available stack space, then unpredictable
19108 behavior will occur. Most native systems offer some level of protection by
19109 adding a guard page at the end of each task stack. This mechanism is usually
19110 not enough for dealing properly with stack overflow situations because
19111 a large local variable could ``jump'' above the guard page.
19112 Furthermore, when the
19113 guard page is hit, there may not be any space left on the stack for executing
19114 the exception propagation code. Enabling stack checking avoids
19115 such situations.
19116
19117 To activate stack checking, compile all units with the gcc option
19118 @option{-fstack-check}. For example:
19119
19120 @smallexample
19121 gcc -c -fstack-check package1.adb
19122 @end smallexample
19123
19124 @noindent
19125 Units compiled with this option will generate extra instructions to check
19126 that any use of the stack (for procedure calls or for declaring local
19127 variables in declare blocks) does not exceed the available stack space.
19128 If the space is exceeded, then a @code{Storage_Error} exception is raised.
19129
19130 For declared tasks, the stack size is controlled by the size
19131 given in an applicable @code{Storage_Size} pragma or by the value specified
19132 at bind time with @option{-d} (@pxref{Switches for gnatbind}) or is set to
19133 the default size as defined in the GNAT runtime otherwise.
19134
19135 For the environment task, the stack size depends on
19136 system defaults and is unknown to the compiler. Stack checking
19137 may still work correctly if a fixed
19138 size stack is allocated, but this cannot be guaranteed.
19139 @ifclear vms
19140 To ensure that a clean exception is signalled for stack
19141 overflow, set the environment variable
19142 @env{GNAT_STACK_LIMIT} to indicate the maximum
19143 stack area that can be used, as in:
19144 @cindex GNAT_STACK_LIMIT
19145
19146 @smallexample
19147 SET GNAT_STACK_LIMIT 1600
19148 @end smallexample
19149
19150 @noindent
19151 The limit is given in kilobytes, so the above declaration would
19152 set the stack limit of the environment task to 1.6 megabytes.
19153 Note that the only purpose of this usage is to limit the amount
19154 of stack used by the environment task. If it is necessary to
19155 increase the amount of stack for the environment task, then this
19156 is an operating systems issue, and must be addressed with the
19157 appropriate operating systems commands.
19158 @end ifclear
19159 @ifset vms
19160 To have a fixed size stack in the environment task, the stack must be put
19161 in the P0 address space and its size specified. Use these switches to
19162 create a p0 image:
19163
19164 @smallexample
19165 gnatmake my_progs -largs "-Wl,--opt=STACK=4000,/p0image"
19166 @end smallexample
19167
19168 @noindent
19169 The quotes are required to keep case. The number after @samp{STACK=} is the
19170 size of the environmental task stack in pagelets (512 bytes). In this example
19171 the stack size is about 2 megabytes.
19172
19173 @noindent
19174 A consequence of the @option{/p0image} qualifier is also to makes RMS buffers
19175 be placed in P0 space. Refer to @cite{HP OpenVMS Linker Utility Manual} for
19176 more details about the @option{/p0image} qualifier and the @option{stack}
19177 option.
19178
19179 @noindent
19180 On Itanium platforms, you can instead assign the @samp{GNAT_STACK_SIZE} and
19181 @samp{GNAT_RBS_SIZE} logicals to the size of the primary and register
19182 stack in kilobytes. For example:
19183
19184 @smallexample
19185 $ define GNAT_RBS_SIZE 1024 ! Limit the RBS size to 1MB.
19186 @end smallexample
19187 @end ifset
19188
19189 @node Static Stack Usage Analysis
19190 @section Static Stack Usage Analysis
19191 @cindex Static Stack Usage Analysis
19192 @cindex -fstack-usage
19193
19194 @noindent
19195 A unit compiled with @option{-fstack-usage} will generate an extra file
19196 that specifies
19197 the maximum amount of stack used, on a per-function basis.
19198 The file has the same
19199 basename as the target object file with a @file{.su} extension.
19200 Each line of this file is made up of three fields:
19201
19202 @itemize
19203 @item
19204 The name of the function.
19205 @item
19206 A number of bytes.
19207 @item
19208 One or more qualifiers: @code{static}, @code{dynamic}, @code{bounded}.
19209 @end itemize
19210
19211 The second field corresponds to the size of the known part of the function
19212 frame.
19213
19214 The qualifier @code{static} means that the function frame size
19215 is purely static.
19216 It usually means that all local variables have a static size.
19217 In this case, the second field is a reliable measure of the function stack
19218 utilization.
19219
19220 The qualifier @code{dynamic} means that the function frame size is not static.
19221 It happens mainly when some local variables have a dynamic size. When this
19222 qualifier appears alone, the second field is not a reliable measure
19223 of the function stack analysis. When it is qualified with @code{bounded}, it
19224 means that the second field is a reliable maximum of the function stack
19225 utilization.
19226
19227 A unit compiled with @option{-Wstack-usage} will issue a warning for each
19228 subprogram whose stack usage might be larger than the specified amount of
19229 bytes. The wording is in keeping with the qualifier documented above.
19230
19231 @node Dynamic Stack Usage Analysis
19232 @section Dynamic Stack Usage Analysis
19233
19234 @noindent
19235 It is possible to measure the maximum amount of stack used by a task, by
19236 adding a switch to @command{gnatbind}, as:
19237
19238 @smallexample
19239 $ gnatbind -u0 file
19240 @end smallexample
19241
19242 @noindent
19243 With this option, at each task termination, its stack usage is output on
19244 @file{stderr}.
19245 It is not always convenient to output the stack usage when the program
19246 is still running. Hence, it is possible to delay this output until program
19247 termination. for a given number of tasks specified as the argument of the
19248 @option{-u} option. For instance:
19249
19250 @smallexample
19251 $ gnatbind -u100 file
19252 @end smallexample
19253
19254 @noindent
19255 will buffer the stack usage information of the first 100 tasks to terminate and
19256 output this info at program termination. Results are displayed in four
19257 columns:
19258
19259 @noindent
19260 Index | Task Name | Stack Size | Stack Usage
19261
19262 @noindent
19263 where:
19264
19265 @table @emph
19266 @item Index
19267 is a number associated with each task.
19268
19269 @item Task Name
19270 is the name of the task analyzed.
19271
19272 @item Stack Size
19273 is the maximum size for the stack.
19274
19275 @item Stack Usage
19276 is the measure done by the stack analyzer. In order to prevent overflow, the stack
19277 is not entirely analyzed, and it's not possible to know exactly how
19278 much has actually been used.
19279
19280 @end table
19281
19282 @noindent
19283 The environment task stack, e.g., the stack that contains the main unit, is
19284 only processed when the environment variable GNAT_STACK_LIMIT is set.
19285
19286 @noindent
19287 The package @code{GNAT.Task_Stack_Usage} provides facilities to get
19288 stack usage reports at run-time. See its body for the details.
19289
19290 @ifclear FSFEDITION
19291 @c *********************************
19292 @c * GNATCHECK *
19293 @c *********************************
19294 @node Verifying Properties with gnatcheck
19295 @chapter Verifying Properties with @command{gnatcheck}
19296 @findex gnatcheck
19297 @cindex @command{gnatcheck}
19298
19299 @noindent
19300 The @command{gnatcheck} tool is an ASIS-based utility that checks properties
19301 of Ada source files according to a given set of semantic rules.
19302 @cindex ASIS
19303
19304 In order to check compliance with a given rule, @command{gnatcheck} has to
19305 semantically analyze the Ada sources.
19306 Therefore, checks can only be performed on
19307 legal Ada units. Moreover, when a unit depends semantically upon units located
19308 outside the current directory, the source search path has to be provided when
19309 calling @command{gnatcheck}, either through a specified project file or
19310 through @command{gnatcheck} switches.
19311
19312 For full details, refer to @cite{GNATcheck Reference Manual} document.
19313 @end ifclear
19314
19315 @ifclear FSFEDITION
19316 @c *********************************
19317 @node Creating Sample Bodies with gnatstub
19318 @chapter Creating Sample Bodies with @command{gnatstub}
19319 @findex gnatstub
19320
19321 @noindent
19322 @command{gnatstub} creates body stubs, that is, empty but compilable bodies
19323 for library unit declarations.
19324
19325 To create a body stub, @command{gnatstub} invokes the Ada
19326 compiler and generates and uses the ASIS tree for the input source;
19327 thus the input must be legal Ada code, and the tool should have all the
19328 information needed to compile the input source. To provide this information,
19329 you may specify as a tool parameter the project file the input source belongs to
19330 (or you may call @command{gnatstub}
19331 through the @command{gnat} driver (see @ref{The GNAT Driver and
19332 Project Files}). Another possibility is to specify the source search
19333 path and needed configuration files in @option{-cargs} section of @command{gnatstub}
19334 call, see the description of the @command{gnatstub} switches below.
19335
19336 By default, all the program unit body stubs generated by @code{gnatstub}
19337 raise the predefined @code{Program_Error} exception, which will catch
19338 accidental calls of generated stubs. This behavior can be changed with
19339 option @option{^--no-exception^/NO_EXCEPTION^} (see below).
19340
19341 @menu
19342 * Running gnatstub::
19343 * Switches for gnatstub::
19344 @end menu
19345
19346 @node Running gnatstub
19347 @section Running @command{gnatstub}
19348
19349 @noindent
19350 @command{gnatstub} has a command-line interface of the form:
19351
19352 @smallexample
19353 @c $ gnatstub @ovar{switches} @var{filename} @ovar{directory}
19354 @c Expanding @ovar macro inline (explanation in macro def comments)
19355 $ gnatstub @r{[}@var{switches}@r{]} @var{filename} @r{[}@var{directory}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19356 @end smallexample
19357
19358 @noindent
19359 where
19360 @table @var
19361 @item filename
19362 is the name of the source file that contains a library unit declaration
19363 for which a body must be created. The file name may contain the path
19364 information.
19365 The file name does not have to follow the GNAT file name conventions. If the
19366 name
19367 does not follow GNAT file naming conventions, the name of the body file must
19368 be provided
19369 explicitly as the value of the @option{^-o^/BODY=^@var{body-name}} option.
19370 If the file name follows the GNAT file naming
19371 conventions and the name of the body file is not provided,
19372 @command{gnatstub}
19373 creates the name
19374 of the body file from the argument file name by replacing the @file{.ads}
19375 suffix
19376 with the @file{.adb} suffix.
19377
19378 @item directory
19379 indicates the directory in which the body stub is to be placed (the default
19380 is the
19381 current directory)
19382
19383 @item @samp{@var{gcc_switches}} is a list of switches for
19384 @command{gcc}. They will be passed on to all compiler invocations made by
19385 @command{gnatstub} to generate the ASIS trees. Here you can provide
19386 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19387 use the @option{-gnatec} switch to set the configuration file,
19388 use the @option{-gnat05} switch if sources should be compiled in
19389 Ada 2005 mode etc.
19390
19391 @item switches
19392 is an optional sequence of switches as described in the next section
19393 @end table
19394
19395 @node Switches for gnatstub
19396 @section Switches for @command{gnatstub}
19397
19398 @table @option
19399 @c !sort!
19400
19401 @item --version
19402 @cindex @option{--version} @command{gnatstub}
19403 Display Copyright and version, then exit disregarding all other options.
19404
19405 @item --help
19406 @cindex @option{--help} @command{gnatstub}
19407 Display usage, then exit disregarding all other options.
19408
19409 @item -P @var{file}
19410 @cindex @option{-P} @command{gnatstub}
19411 Indicates the name of the project file that describes the set of sources
19412 to be processed.
19413
19414 @item -X@var{name}=@var{value}
19415 @cindex @option{-X} @command{gnatstub}
19416 Indicates that external variable @var{name} in the argument project
19417 has the value @var{value}. Has no effect if no project is specified as
19418 tool argument.
19419
19420 @item ^-f^/FULL^
19421 @cindex @option{^-f^/FULL^} (@command{gnatstub})
19422 If the destination directory already contains a file with the name of the
19423 body file
19424 for the argument spec file, replace it with the generated body stub.
19425
19426 @item ^-hs^/HEADER=SPEC^
19427 @cindex @option{^-hs^/HEADER=SPEC^} (@command{gnatstub})
19428 Put the comment header (i.e., all the comments preceding the
19429 compilation unit) from the source of the library unit declaration
19430 into the body stub.
19431
19432 @item ^-hg^/HEADER=GENERAL^
19433 @cindex @option{^-hg^/HEADER=GENERAL^} (@command{gnatstub})
19434 Put a sample comment header into the body stub.
19435
19436 @item ^--header-file=@var{filename}^/FROM_HEADER_FILE=@var{filename}^
19437 @cindex @option{^--header-file^/FROM_HEADER_FILE=^} (@command{gnatstub})
19438 Use the content of the file as the comment header for a generated body stub.
19439
19440 @ifclear vms
19441 @item -IDIR
19442 @cindex @option{-IDIR} (@command{gnatstub})
19443 @itemx -I-
19444 @cindex @option{-I-} (@command{gnatstub})
19445 @end ifclear
19446 @ifset vms
19447 @item /NOCURRENT_DIRECTORY
19448 @cindex @option{/NOCURRENT_DIRECTORY} (@command{gnatstub})
19449 @end ifset
19450 ^These switches have ^This switch has^ the same meaning as in calls to
19451 @command{gcc}.
19452 ^They define ^It defines ^ the source search path in the call to
19453 @command{gcc} issued
19454 by @command{gnatstub} to compile an argument source file.
19455
19456 @item ^-gnatec^/CONFIGURATION_PRAGMAS_FILE=^@var{PATH}
19457 @cindex @option{^-gnatec^/CONFIGURATION_PRAGMAS_FILE^} (@command{gnatstub})
19458 This switch has the same meaning as in calls to @command{gcc}.
19459 It defines the additional configuration file to be passed to the call to
19460 @command{gcc} issued
19461 by @command{gnatstub} to compile an argument source file.
19462
19463 @item ^-gnatyM^/MAX_LINE_LENGTH=^@var{n}
19464 @cindex @option{^-gnatyM^/MAX_LINE_LENGTH^} (@command{gnatstub})
19465 (@var{n} is a non-negative integer). Set the maximum line length that is
19466 allowed in a source file. The default is 79. The maximum value that can be
19467 specified is 32767. Note that in the special case of configuration
19468 pragma files, the maximum is always 32767 regardless of whether or
19469 not this switch appears.
19470
19471 @item ^-gnaty^/STYLE_CHECKS=^@var{n}
19472 @cindex @option{^-gnaty^/STYLE_CHECKS=^} (@command{gnatstub})
19473 (@var{n} is a non-negative integer from 1 to 9). Set the indentation level in
19474 the generated body sample to @var{n}.
19475 The default indentation is 3.
19476
19477 @item ^-gnatyo^/ORDERED_SUBPROGRAMS^
19478 @cindex @option{^-gnatyo^/ORDERED_SUBPROGRAMS^} (@command{gnatstub})
19479 Order local bodies alphabetically. (By default local bodies are ordered
19480 in the same way as the corresponding local specs in the argument spec file.)
19481
19482 @item ^-i^/INDENTATION=^@var{n}
19483 @cindex @option{^-i^/INDENTATION^} (@command{gnatstub})
19484 Same as @option{^-gnaty^/STYLE_CHECKS=^@var{n}}
19485
19486 @item ^-k^/TREE_FILE=SAVE^
19487 @cindex @option{^-k^/TREE_FILE=SAVE^} (@command{gnatstub})
19488 Do not remove the tree file (i.e., the snapshot of the compiler internal
19489 structures used by @command{gnatstub}) after creating the body stub.
19490
19491 @item ^-l^/LINE_LENGTH=^@var{n}
19492 @cindex @option{^-l^/LINE_LENGTH^} (@command{gnatstub})
19493 Same as @option{^-gnatyM^/MAX_LINE_LENGTH=^@var{n}}
19494
19495 @item ^--no-exception^/NO_EXCEPTION^
19496 @cindex @option{^--no-exception^/NO_EXCEPTION^} (@command{gnatstub})
19497 Avoid raising PROGRAM_ERROR in the generated bodies of program unit stubs.
19498 This is not always possible for function stubs.
19499
19500 @item ^--no-local-header^/NO_LOCAL_HEADER^
19501 @cindex @option{^--no-local-header^/NO_LOCAL_HEADER^} (@command{gnatstub})
19502 Do not place local comment header with unit name before body stub for a
19503 unit.
19504
19505 @item ^-o ^/BODY=^@var{body-name}
19506 @cindex @option{^-o^/BODY^} (@command{gnatstub})
19507 Body file name. This should be set if the argument file name does not
19508 follow
19509 the GNAT file naming
19510 conventions. If this switch is omitted the default name for the body will be
19511 obtained
19512 from the argument file name according to the GNAT file naming conventions.
19513
19514 @item ^-W^/RESULT_ENCODING=^@var{e}
19515 @cindex @option{^-W^/RESULT_ENCODING=^} (@command{gnatstub})
19516 Specify the wide character encoding method for the output body file.
19517 @var{e} is one of the following:
19518
19519 @itemize @bullet
19520
19521 @item ^h^HEX^
19522 Hex encoding
19523
19524 @item ^u^UPPER^
19525 Upper half encoding
19526
19527 @item ^s^SHIFT_JIS^
19528 Shift/JIS encoding
19529
19530 @item ^e^EUC^
19531 EUC encoding
19532
19533 @item ^8^UTF8^
19534 UTF-8 encoding
19535
19536 @item ^b^BRACKETS^
19537 Brackets encoding (default value)
19538 @end itemize
19539
19540 @item ^-q^/QUIET^
19541 @cindex @option{^-q^/QUIET^} (@command{gnatstub})
19542 Quiet mode: do not generate a confirmation when a body is
19543 successfully created, and do not generate a message when a body is not
19544 required for an
19545 argument unit.
19546
19547 @item ^-r^/TREE_FILE=REUSE^
19548 @cindex @option{^-r^/TREE_FILE=REUSE^} (@command{gnatstub})
19549 Reuse the tree file (if it exists) instead of creating it. Instead of
19550 creating the tree file for the library unit declaration, @command{gnatstub}
19551 tries to find it in the current directory and use it for creating
19552 a body. If the tree file is not found, no body is created. This option
19553 also implies @option{^-k^/SAVE^}, whether or not
19554 the latter is set explicitly.
19555
19556 @item ^-t^/TREE_FILE=OVERWRITE^
19557 @cindex @option{^-t^/TREE_FILE=OVERWRITE^} (@command{gnatstub})
19558 Overwrite the existing tree file. If the current directory already
19559 contains the file which, according to the GNAT file naming rules should
19560 be considered as a tree file for the argument source file,
19561 @command{gnatstub}
19562 will refuse to create the tree file needed to create a sample body
19563 unless this option is set.
19564
19565 @item ^-v^/VERBOSE^
19566 @cindex @option{^-v^/VERBOSE^} (@command{gnatstub})
19567 Verbose mode: generate version information.
19568
19569 @end table
19570 @end ifclear
19571
19572 @ifclear FSFEDITION
19573 @c *********************************
19574 @node Creating Unit Tests with gnattest
19575 @chapter Creating Unit Tests with @command{gnattest}
19576 @findex gnattest
19577
19578 @noindent
19579 @command{gnattest} is an ASIS-based utility that creates unit-test skeletons
19580 as well as a test driver infrastructure (harness). @command{gnattest} creates
19581 a skeleton for each visible subprogram in the packages under consideration when
19582 they do not exist already.
19583
19584 In order to process source files from a project, @command{gnattest} has to
19585 semantically analyze the sources. Therefore, test skeletons can only be
19586 generated for legal Ada units. If a unit is dependent on other units,
19587 those units should be among the source files of the project or of other projects
19588 imported by this one.
19589
19590 Generated skeletons and harnesses are based on the AUnit testing framework.
19591 AUnit is an Ada adaptation of the xxxUnit testing frameworks, similar to JUnit
19592 for Java or CppUnit for C++. While it is advised that gnattest users read
19593 the AUnit manual, deep knowledge of AUnit is not necessary for using gnattest.
19594 For correct operation of @command{gnattest}, AUnit should be installed and
19595 aunit.gpr must be on the project path. This happens automatically when Aunit
19596 is installed at its default location.
19597 @menu
19598 * Running gnattest::
19599 * Switches for gnattest::
19600 * Project Attributes for gnattest::
19601 * Simple Example::
19602 * Setting Up and Tearing Down the Testing Environment::
19603 * Regenerating Tests::
19604 * Default Test Behavior::
19605 * Testing Primitive Operations of Tagged Types::
19606 * Testing Inheritance::
19607 * Tagged Types Substitutability Testing::
19608 * Testing with Contracts::
19609 * Additional Tests::
19610 @ifclear vms
19611 * Support for other platforms/run-times::
19612 @end ifclear
19613 * Current Limitations::
19614 @end menu
19615
19616 @node Running gnattest
19617 @section Running @command{gnattest}
19618
19619 @noindent
19620 @command{gnattest} has a command-line interface of the form
19621
19622 @smallexample
19623 @c $ gnattest @var{-Pprojname} @ovar{switches} @ovar{filename} @ovar{directory}
19624 @c Expanding @ovar macro inline (explanation in macro def comments)
19625 $ gnattest @var{-Pprojname} @r{[}@var{--harness-dir=dirname}@r{]} @r{[}@var{switches}@r{]} @r{[}@var{filename}@r{]} @r{[}-cargs @var{gcc_switches}@r{]}
19626 @end smallexample
19627
19628 @noindent
19629 where
19630 @table @var
19631
19632 @item -Pprojname
19633 specifies the project defining the location of source files. When no
19634 file names are provided on the command line, all sources in the project
19635 are used as input. This switch is required.
19636
19637 @item filename
19638 is the name of the source file containing the library unit package declaration
19639 for which a test package will be created. The file name may be given with a
19640 path.
19641
19642 @item @samp{@var{gcc_switches}}
19643 is a list of switches for
19644 @command{gcc}. These switches will be passed on to all compiler invocations
19645 made by @command{gnattest} to generate a set of ASIS trees. Here you can provide
19646 @option{^-I^/INCLUDE_DIRS=^} switches to form the source search path,
19647 use the @option{-gnatec} switch to set the configuration file,
19648 use the @option{-gnat05} switch if sources should be compiled in
19649 Ada 2005 mode, etc.
19650
19651 @item switches
19652 is an optional sequence of switches as described in the next section.
19653
19654 @end table
19655
19656 @command{gnattest} results can be found in two different places.
19657
19658 @itemize @bullet
19659 @item automatic harness:
19660 the harness code, which is located by default in "gnattest/harness" directory
19661 that is created in the object directory of corresponding project file. All of
19662 this code is generated completely automatically and can be destroyed and
19663 regenerated at will. It is not recommended to modify this code manually, since
19664 it could easily be overridden by mistake. The entry point in the harness code is
19665 the project file named @command{test_driver.gpr}. Tests can be compiled and run
19666 using a command such as:
19667
19668 @smallexample
19669 gnatmake -P<harness-dir>/test_driver
19670 test_runner
19671 @end smallexample
19672
19673 Note that you might need to specify the necessary values of scenario variables
19674 when you are not using the AUnit defaults.
19675
19676 @item actual unit test skeletons:
19677 a test skeleton for each visible subprogram is created in a separate file, if it
19678 doesn't exist already. By default, those separate test files are located in a
19679 "gnattest/tests" directory that is created in the object directory of
19680 corresponding project file. For example, if a source file my_unit.ads in
19681 directory src contains a visible subprogram Proc, then the corresponding unit
19682 test will be found in file src/tests/my_unit-test_data-tests-proc_<code>.adb.
19683 <code> is a signature encoding used to differentiate test names in case of
19684 overloading.
19685
19686 Note that if the project already has both my_unit.ads and my_unit-test_data.ads,
19687 this will cause a name conflict with the generated test package.
19688 @end itemize
19689
19690 @node Switches for gnattest
19691 @section Switches for @command{gnattest}
19692
19693 @table @option
19694 @c !sort!
19695
19696 @item --harness-only
19697 @cindex @option{--harness-only} (@command{gnattest})
19698 When this option is given, @command{gnattest} creates a harness for all
19699 sources, treating them as test packages.
19700
19701 @item --additional-tests=@var{projname}
19702 @cindex @option{--additional-tests} (@command{gnattest})
19703 Sources described in @var{projname} are considered potential additional
19704 manual tests to be added to the test suite.
19705
19706 @item -r
19707 @cindex @option{-r} (@command{gnattest})
19708 Recursively consider all sources from all projects.
19709
19710 @item -X@var{name=value}
19711 @cindex @option{-X} (@command{gnattest})
19712 Indicate that external variable @var{name} has the value @var{value}.
19713
19714 @item -q
19715 @cindex @option{-q} (@command{gnattest})
19716 Suppresses noncritical output messages.
19717
19718 @item -v
19719 @cindex @option{-v} (@command{gnattest})
19720 Verbose mode: generates version information.
19721
19722 @item --validate-type-extensions
19723 @cindex @option{--validate-type-extensions} (@command{gnattest})
19724 Enables substitution check: run all tests from all parents in order
19725 to check substitutability.
19726
19727 @item --skeleton-default=@var{val}
19728 @cindex @option{--skeleton-default} (@command{gnattest})
19729 Specifies the default behavior of generated skeletons. @var{val} can be either
19730 "fail" or "pass", "fail" being the default.
19731
19732 @item --passed-tests=@var{val}
19733 @cindex @option{--skeleton-default} (@command{gnattest})
19734 Specifies whether or not passed tests should be shown. @var{val} can be either
19735 "show" or "hide", "show" being the default.
19736
19737
19738 @item --tests-root=@var{dirname}
19739 @cindex @option{--tests-root} (@command{gnattest})
19740 The directory hierarchy of tested sources is recreated in the @var{dirname}
19741 directory, and test packages are placed in corresponding directories.
19742 If the @var{dirname} is a relative path, it is considered relative to the object
19743 directory of the project file. When all sources from all projects are taken
19744 recursively from all projects, directory hierarchies of tested sources are
19745 recreated for each project in their object directories and test packages are
19746 placed accordingly.
19747
19748 @item --subdir=@var{dirname}
19749 @cindex @option{--subdir} (@command{gnattest})
19750 Test packages are placed in subdirectories.
19751
19752 @item --tests-dir=@var{dirname}
19753 @cindex @option{--tests-dir} (@command{gnattest})
19754 All test packages are placed in the @var{dirname} directory.
19755 If the @var{dirname} is a relative path, it is considered relative to the object
19756 directory of the project file. When all sources from all projects are taken
19757 recursively from all projects, @var{dirname} directories are created for each
19758 project in their object directories and test packages are placed accordingly.
19759
19760 @item --harness-dir=@var{dirname}
19761 @cindex @option{--harness-dir} (@command{gnattest})
19762 specifies the directory that will hold the harness packages and project file
19763 for the test driver. If the @var{dirname} is a relative path, it is considered
19764 relative to the object directory of the project file.
19765
19766 @item --separates
19767 @cindex @option{--separates} (@command{gnattest})
19768 Bodies of all test routines are generated as separates. Note that this mode is
19769 kept for compatibility reasons only and it is not advised to use it due to
19770 possible problems with hash in names of test skeletons when using an
19771 inconsistent casing. Separate test skeletons can be incorporated to monolith
19772 test package with improved hash being used by using @option{--transition}
19773 switch.
19774
19775
19776 @item --transition
19777 @cindex @option{--transition} (@command{gnattest})
19778 This allows transition from separate test routines to monolith test packages.
19779 All matching test routines are overwritten with contents of corresponding
19780 separates. Note that if separate test routines had any manually added with
19781 clauses they will be moved to the test package body as is and have to be moved
19782 by hand.
19783
19784 @end table
19785
19786 @option{--tests_root}, @option{--subdir} and @option{--tests-dir} switches are
19787 mutually exclusive.
19788
19789 @node Project Attributes for gnattest
19790 @section Project Attributes for @command{gnattest}
19791
19792 @noindent
19793
19794 Most of the command-line options can also be passed to the tool by adding
19795 special attributes to the project file. Those attributes should be put in
19796 package gnattest. Here is the list of attributes:
19797
19798 @itemize @bullet
19799
19800 @item Tests_Root
19801 is used to select the same output mode as with the --tests-root option.
19802 This attribute cannot be used together with Subdir or Tests_Dir.
19803
19804 @item Subdir
19805 is used to select the same output mode as with the --subdir option.
19806 This attribute cannot be used together with Tests_Root or Tests_Dir.
19807
19808 @item Tests_Dir
19809 is used to select the same output mode as with the --tests-dir option.
19810 This attribute cannot be used together with Subdir or Tests_Root.
19811
19812 @item Harness_Dir
19813 is used to specify the directory in which to place harness packages and project
19814 file for the test driver, otherwise specified by --harness-dir.
19815
19816 @item Additional_Tests
19817 is used to specify the project file, otherwise given by
19818 --additional-tests switch.
19819
19820 @item Skeletons_Default
19821 is used to specify the default behaviour of test skeletons, otherwise
19822 specified by --skeleton-default option. The value of this attribute
19823 should be either "pass" or "fail".
19824
19825 @end itemize
19826
19827 Each of those attributes can be overridden from the command line if needed.
19828 Other @command{gnattest} switches can also be passed via the project
19829 file as an attribute list called GNATtest_Switches.
19830
19831 @node Simple Example
19832 @section Simple Example
19833
19834 @noindent
19835
19836 Let's take a very simple example using the first @command{gnattest} example
19837 located in:
19838
19839 @smallexample
19840 <install_prefix>/share/examples/gnattest/simple
19841 @end smallexample
19842
19843 This project contains a simple package containing one subprogram. By running gnattest:
19844
19845 @smallexample
19846 $ gnattest --harness-dir=driver -Psimple.gpr
19847 @end smallexample
19848
19849 a test driver is created in directory "driver". It can be compiled and run:
19850
19851 @smallexample
19852 $ cd obj/driver
19853 $ gnatmake -Ptest_driver
19854 $ test_runner
19855 @end smallexample
19856
19857 One failed test with diagnosis "test not implemented" is reported.
19858 Since no special output option was specified, the test package Simple.Tests
19859 is located in:
19860
19861 @smallexample
19862 <install_prefix>/share/examples/gnattest/simple/obj/gnattest/tests
19863 @end smallexample
19864
19865 For each package containing visible subprograms, a child test package is
19866 generated. It contains one test routine per tested subprogram. Each
19867 declaration of a test subprogram has a comment specifying which tested
19868 subprogram it corresponds to. Bodies of test routines are placed in test package
19869 bodies and are surrounded by special comment sections. Those comment sections
19870 should not be removed or modified in order for gnattest to be able to regenerate
19871 test packages and keep already written tests in place.
19872 The test routine Test_Inc_5eaee3 located at simple-test_data-tests.adb contains
19873 a single statement: a call to procedure Assert. It has two arguments:
19874 the Boolean expression we want to check and the diagnosis message to display if
19875 the condition is false.
19876
19877 That is where actual testing code should be written after a proper setup.
19878 An actual check can be performed by replacing the Assert call with:
19879
19880 @smallexample @c ada
19881 Assert (Inc (1) = 2, "wrong incrementation");
19882 @end smallexample
19883
19884 After recompiling and running the test driver, one successfully passed test
19885 is reported.
19886
19887 @node Setting Up and Tearing Down the Testing Environment
19888 @section Setting Up and Tearing Down the Testing Environment
19889
19890 @noindent
19891
19892 Besides test routines themselves, each test package has a parent package
19893 Test_Data that has two procedures: Set_Up and Tear_Down. This package is never
19894 overwritten by the tool. Set_Up is called before each test routine of the
19895 package and Tear_Down is called after each test routine. Those two procedures
19896 can be used to perform necessary initialization and finalization,
19897 memory allocation, etc. Test type declared in Test_Data package is parent type
19898 for the test type of test package and can have user-defined components whose
19899 values can be set by Set_Up routine and used in test routines afterwards.
19900
19901 @node Regenerating Tests
19902 @section Regenerating Tests
19903
19904 @noindent
19905
19906 Bodies of test routines and test_data packages are never overridden after they
19907 have been created once. As long as the name of the subprogram, full expanded Ada
19908 names, and the order of its parameters is the same, and comment sections are
19909 intact the old test routine will fit in its place and no test skeleton will be
19910 generated for the subprogram.
19911
19912 This can be demonstrated with the previous example. By uncommenting declaration
19913 and body of function Dec in simple.ads and simple.adb, running
19914 @command{gnattest} on the project, and then running the test driver:
19915
19916 @smallexample
19917 gnattest --harness-dir=driver -Psimple.gpr
19918 cd obj/driver
19919 gnatmake -Ptest_driver
19920 test_runner
19921 @end smallexample
19922
19923 the old test is not replaced with a stub, nor is it lost, but a new test
19924 skeleton is created for function Dec.
19925
19926 The only way of regenerating tests skeletons is to remove the previously created
19927 tests together with corresponding comment sections.
19928
19929 @node Default Test Behavior
19930 @section Default Test Behavior
19931
19932 @noindent
19933
19934 The generated test driver can treat unimplemented tests in two ways:
19935 either count them all as failed (this is useful to see which tests are still
19936 left to implement) or as passed (to sort out unimplemented ones from those
19937 actually failing).
19938
19939 The test driver accepts a switch to specify this behavior:
19940 --skeleton-default=val, where val is either "pass" or "fail" (exactly as for
19941 @command{gnattest}).
19942
19943 The default behavior of the test driver is set with the same switch
19944 as passed to gnattest when generating the test driver.
19945
19946 Passing it to the driver generated on the first example:
19947
19948 @smallexample
19949 test_runner --skeleton-default=pass
19950 @end smallexample
19951
19952 makes both tests pass, even the unimplemented one.
19953
19954 @node Testing Primitive Operations of Tagged Types
19955 @section Testing Primitive Operations of Tagged Types
19956
19957 @noindent
19958
19959 Creation of test skeletons for primitive operations of tagged types entails
19960 a number of features. Test routines for all primitives of a given tagged type
19961 are placed in a separate child package named according to the tagged type. For
19962 example, if you have tagged type T in package P, all tests for primitives
19963 of T will be in P.T_Test_Data.T_Tests.
19964
19965 Consider running gnattest on the second example (note: actual tests for this
19966 example already exist, so there's no need to worry if the tool reports that
19967 no new stubs were generated):
19968
19969 @smallexample
19970 cd <install_prefix>/share/examples/gnattest/tagged_rec
19971 gnattest --harness-dir=driver -Ptagged_rec.gpr
19972 @end smallexample
19973
19974 Taking a closer look at the test type declared in the test package
19975 Speed1.Controller_Test_Data is necessary. It is declared in:
19976
19977 @smallexample
19978 <install_prefix>/share/examples/gnattest/tagged_rec/obj/gnattest/tests
19979 @end smallexample
19980
19981 Test types are direct or indirect descendants of
19982 AUnit.Test_Fixtures.Test_Fixture type. In the case of nonprimitive tested
19983 subprograms, the user doesn't need to be concerned with them. However,
19984 when generating test packages for primitive operations, there are some things
19985 the user needs to know.
19986
19987 Type Test_Controller has components that allow assignment of various
19988 derivations of type Controller. And if you look at the specification of
19989 package Speed2.Auto_Controller, you will see that Test_Auto_Controller
19990 actually derives from Test_Controller rather than AUnit type Test_Fixture.
19991 Thus, test types mirror the hierarchy of tested types.
19992
19993 The Set_Up procedure of Test_Data package corresponding to a test package
19994 of primitive operations of type T assigns to Fixture a reference to an
19995 object of that exact type T. Notice, however, that if the tagged type has
19996 discriminants, the Set_Up only has a commented template for setting
19997 up the fixture, since filling the discriminant with actual value is up
19998 to the user.
19999
20000 The knowledge of the structure of test types allows additional testing
20001 without additional effort. Those possibilities are described below.
20002
20003 @node Testing Inheritance
20004 @section Testing Inheritance
20005
20006 @noindent
20007
20008 Since the test type hierarchy mimics the hierarchy of tested types, the
20009 inheritance of tests takes place. An example of such inheritance can be
20010 seen by running the test driver generated for the second example. As previously
20011 mentioned, actual tests are already written for this example.
20012
20013 @smallexample
20014 cd obj/driver
20015 gnatmake -Ptest_driver
20016 test_runner
20017 @end smallexample
20018
20019 There are 6 passed tests while there are only 5 testable subprograms. The test
20020 routine for function Speed has been inherited and run against objects of the
20021 derived type.
20022
20023 @node Tagged Types Substitutability Testing
20024 @section Tagged Types Substitutability Testing
20025
20026 @noindent
20027
20028 Tagged Types Substitutability Testing is a way of verifying the global type
20029 consistency by testing. Global type consistency is a principle stating that if
20030 S is a subtype of T (in Ada, S is a derived type of tagged type T),
20031 then objects of type T may be replaced with objects of type S (that is,
20032 objects of type S may be substituted for objects of type T), without
20033 altering any of the desirable properties of the program. When the properties
20034 of the program are expressed in the form of subprogram preconditions and
20035 postconditions (let's call them pre and post), the principle is formulated as
20036 relations between the pre and post of primitive operations and the pre and post
20037 of their derived operations. The pre of a derived operation should not be
20038 stronger than the original pre, and the post of the derived operation should
20039 not be weaker than the original post. Those relations ensure that verifying if
20040 a dispatching call is safe can be done just by using the pre and post of the
20041 root operation.
20042
20043 Verifying global type consistency by testing consists of running all the unit
20044 tests associated with the primitives of a given tagged type with objects of its
20045 derived types.
20046
20047 In the example used in the previous section, there was clearly a violation of
20048 type consistency. The overriding primitive Adjust_Speed in package Speed2
20049 removes the functionality of the overridden primitive and thus doesn't respect
20050 the consistency principle.
20051 Gnattest has a special option to run overridden parent tests against objects
20052 of the type which have overriding primitives:
20053
20054 @smallexample
20055 gnattest --harness-dir=driver --validate-type-extensions -Ptagged_rec.gpr
20056 cd obj/driver
20057 gnatmake -Ptest_driver
20058 test_runner
20059 @end smallexample
20060
20061 While all the tests pass by themselves, the parent test for Adjust_Speed fails
20062 against objects of the derived type.
20063
20064 Non-overridden tests are already inherited for derived test types, so the
20065 --validate-type-extensions enables the application of overriden tests to objects
20066 of derived types.
20067
20068 @node Testing with Contracts
20069 @section Testing with Contracts
20070
20071 @noindent
20072
20073 @command{gnattest} supports pragmas Precondition, Postcondition, and Test_Case,
20074 as well as corresponding aspects.
20075 Test routines are generated, one per each Test_Case associated with a tested
20076 subprogram. Those test routines have special wrappers for tested functions
20077 that have composition of pre- and postcondition of the subprogram with
20078 "requires" and "ensures" of the Test_Case (depending on the mode, pre and post
20079 either count for Nominal mode or do not count for Robustness mode).
20080
20081 The third example demonstrates how this works:
20082
20083 @smallexample
20084 cd <install_prefix>/share/examples/gnattest/contracts
20085 gnattest --harness-dir=driver -Pcontracts.gpr
20086 @end smallexample
20087
20088 Putting actual checks within the range of the contract does not cause any
20089 error reports. For example, for the test routine which corresponds to
20090 test case 1:
20091
20092 @smallexample @c ada
20093 Assert (Sqrt (9.0) = 3.0, "wrong sqrt");
20094 @end smallexample
20095
20096 and for the test routine corresponding to test case 2:
20097
20098 @smallexample @c ada
20099 Assert (Sqrt (-5.0) = -1.0, "wrong error indication");
20100 @end smallexample
20101
20102 are acceptable:
20103
20104 @smallexample
20105 cd obj/driver
20106 gnatmake -Ptest_driver
20107 test_runner
20108 @end smallexample
20109
20110 However, by changing 9.0 to 25.0 and 3.0 to 5.0, for example, you can get
20111 a precondition violation for test case one. Also, by using any otherwise
20112 correct but positive pair of numbers in the second test routine, you can also
20113 get a precondition violation. Postconditions are checked and reported
20114 the same way.
20115
20116 @node Additional Tests
20117 @section Additional Tests
20118
20119 @noindent
20120 @command{gnattest} can add user-written tests to the main suite of the test
20121 driver. @command{gnattest} traverses the given packages and searches for test
20122 routines. All procedures with a single in out parameter of a type which is
20123 derived from AUnit.Test_Fixtures.Test_Fixture and that are declared in package
20124 specifications are added to the suites and are then executed by the test driver.
20125 (Set_Up and Tear_Down are filtered out.)
20126
20127 An example illustrates two ways of creating test harnesses for user-written
20128 tests. Directory additional_tests contains an AUnit-based test driver written
20129 by hand.
20130
20131 @smallexample
20132 <install_prefix>/share/examples/gnattest/additional_tests/
20133 @end smallexample
20134
20135 To create a test driver for already-written tests, use the --harness-only
20136 option:
20137
20138 @smallexample
20139 gnattest -Padditional/harness/harness.gpr --harness-dir=harness_only \
20140 --harness-only
20141 gnatmake -Pharness_only/test_driver.gpr
20142 harness_only/test_runner
20143 @end smallexample
20144
20145 Additional tests can also be executed together with generated tests:
20146
20147 @smallexample
20148 gnattest -Psimple.gpr --additional-tests=additional/harness/harness.gpr \
20149 --harness-dir=mixing
20150 gnatmake -Pmixing/test_driver.gpr
20151 mixing/test_runner
20152 @end smallexample
20153
20154 @ifclear vms
20155 @node Support for other platforms/run-times
20156 @section Support for other platforms/run-times
20157
20158 @noindent
20159 @command{gnattest} can be used to generate the test harness for platforms
20160 and run-time libraries others than the default native target with the
20161 default full run-time. For example, when using a limited run-time library
20162 such as Zero FootPrint (ZFP), a simplified harness is generated.
20163
20164 Two variables are used to tell the underlying AUnit framework how to generate
20165 the test harness: @code{PLATFORM}, which identifies the target, and
20166 @code{RUNTIME}, used to determine the run-time library for which the harness
20167 is generated. Corresponding prefix should also be used when calling
20168 @command{gnattest} for non-native targets. For example, the following options
20169 are used to generate the AUnit test harness for a PowerPC ELF target using
20170 the ZFP run-time library:
20171
20172 @smallexample
20173 powerpc-elf-gnattest -Psimple.gpr -XPLATFORM=powerpc-elf -XRUNTIME=zfp
20174 @end smallexample
20175 @end ifclear
20176
20177 @node Current Limitations
20178 @section Current Limitations
20179
20180 @noindent
20181
20182 The tool currently does not support following features:
20183
20184 @itemize @bullet
20185 @item generic tests for generic packages and package instantiations
20186 @item tests for protected subprograms and entries
20187
20188 @end itemize
20189 @end ifclear
20190
20191
20192 @c *********************************
20193 @node Performing Dimensionality Analysis in GNAT
20194 @chapter Performing Dimensionality Analysis in GNAT
20195 @cindex Dimensionality analysis
20196
20197 @noindent
20198 The GNAT compiler now supports dimensionality checking. The user can
20199 specify physical units for objects, and the compiler will verify that uses
20200 of these objects are compatible with their dimensions, in a fashion that is
20201 familiar to engineering practice. The dimensions of algebraic expressions
20202 (including powers with static exponents) are computed from their constituents.
20203
20204 This feature depends on Ada 2012 aspect specifications, and is available from
20205 version 7.0.1 of GNAT onwards.
20206 The GNAT-specific aspect @code{Dimension_System}
20207 @cindex @code{Dimension_System} aspect
20208 allows you to define a system of units; the aspect @code{Dimension}
20209 @cindex @code{Dimension} aspect
20210 then allows the user to declare dimensioned quantities within a given system.
20211 (These aspects are described in the @i{Implementation Defined Aspects}
20212 chapter of the @i{GNAT Reference Manual}).
20213
20214 The major advantage of this model is that it does not require the declaration of
20215 multiple operators for all possible combinations of types: it is only necessary
20216 to use the proper subtypes in object declarations.
20217
20218 The simplest way to impose dimensionality checking on a computation is to make
20219 use of the package @code{System.Dim.Mks},
20220 @cindex @code{System.Dim.Mks} package (GNAT library)
20221 which is part of the GNAT library. This
20222 package defines a floating-point type @code{MKS_Type},
20223 @cindex @code{MKS_Type} type
20224 for which a sequence of
20225 dimension names are specified, together with their conventional abbreviations.
20226 The following should be read together with the full specification of the
20227 package, in file @file{s-dimmks.ads}.
20228 @cindex @file{s-dimmks.ads} file
20229
20230 @smallexample @c ada
20231 @group
20232 type Mks_Type is new Long_Long_Float
20233 with
20234 Dimension_System => (
20235 (Unit_Name => Meter, Unit_Symbol => 'm', Dim_Symbol => 'L'),
20236 (Unit_Name => Kilogram, Unit_Symbol => "kg", Dim_Symbol => 'M'),
20237 (Unit_Name => Second, Unit_Symbol => 's', Dim_Symbol => 'T'),
20238 (Unit_Name => Ampere, Unit_Symbol => 'A', Dim_Symbol => 'I'),
20239 (Unit_Name => Kelvin, Unit_Symbol => 'K', Dim_Symbol => "Theta"),
20240 (Unit_Name => Mole, Unit_Symbol => "mol", Dim_Symbol => 'N'),
20241 (Unit_Name => Candela, Unit_Symbol => "cd", Dim_Symbol => 'J'));
20242 @end group
20243 @end smallexample
20244
20245 @noindent
20246 The package then defines a series of subtypes that correspond to these
20247 conventional units. For example:
20248
20249 @smallexample @c ada
20250 @group
20251 subtype Length is Mks_Type
20252 with
20253 Dimension => (Symbol => 'm', Meter => 1, others => 0);
20254 @end group
20255 @end smallexample
20256
20257 @noindent
20258 and similarly for @code{Mass}, @code{Time}, @code{Electric_Current},
20259 @code{Thermodynamic_Temperature}, @code{Amount_Of_Substance}, and
20260 @code{Luminous_Intensity} (the standard set of units of the SI system).
20261
20262 The package also defines conventional names for values of each unit, for
20263 example:
20264
20265 @smallexample @c ada
20266 @group
20267 m : constant Length := 1.0;
20268 kg : constant Mass := 1.0;
20269 s : constant Time := 1.0;
20270 A : constant Electric_Current := 1.0;
20271 @end group
20272 @end smallexample
20273
20274 @noindent
20275 as well as useful multiples of these units:
20276
20277 @smallexample @c ada
20278 @group
20279 cm : constant Length := 1.0E-02;
20280 g : constant Mass := 1.0E-03;
20281 min : constant Time := 60.0;
20282 day : constant Time := 60.0 * 24.0 * min;
20283 ...
20284 @end group
20285 @end smallexample
20286
20287 @noindent
20288 Using this package, you can then define a derived unit by
20289 providing the aspect that
20290 specifies its dimensions within the MKS system, as well as the string to
20291 be used for output of a value of that unit:
20292
20293 @smallexample @c ada
20294 @group
20295 subtype Acceleration is Mks_Type
20296 with Dimension => ("m/sec^^^2",
20297 Meter => 1,
20298 Second => -2,
20299 others => 0);
20300 @end group
20301 @end smallexample
20302
20303 @noindent
20304 Here is a complete example of use:
20305
20306 @smallexample @c ada
20307 @group
20308 with System.Dim.MKS; use System.Dim.Mks;
20309 with System.Dim.Mks_IO; use System.Dim.Mks_IO;
20310 with Text_IO; use Text_IO;
20311 procedure Free_Fall is
20312 subtype Acceleration is Mks_Type
20313 with Dimension => ("m/sec^^^2", 1, 0, -2, others => 0);
20314 G : constant acceleration := 9.81 * m / (s ** 2);
20315 T : Time := 10.0*s;
20316 Distance : Length;
20317 @end group
20318 @group
20319 begin
20320 Put ("Gravitational constant: ");
20321 Put (G, Aft => 2, Exp => 0); Put_Line ("");
20322 Distance := 0.5 * G * T ** 2;
20323 Put ("distance travelled in 10 seconds of free fall ");
20324 Put (Distance, Aft => 2, Exp => 0);
20325 Put_Line ("");
20326 end Free_Fall;
20327 @end group
20328 @end smallexample
20329
20330 @noindent
20331 Execution of this program yields:
20332 @smallexample
20333 @group
20334 Gravitational constant: 9.81 m/sec^^^2
20335 distance travelled in 10 seconds of free fall 490.50 m
20336 @end group
20337 @end smallexample
20338
20339 @noindent
20340 However, incorrect assignments such as:
20341
20342 @smallexample @c ada
20343 @group
20344 Distance := 5.0;
20345 Distance := 5.0 * kg:
20346 @end group
20347 @end smallexample
20348
20349 @noindent
20350 are rejected with the following diagnoses:
20351
20352 @smallexample
20353 @group
20354 Distance := 5.0;
20355 >>> dimensions mismatch in assignment
20356 >>> left-hand side has dimension [L]
20357 >>> right-hand side is dimensionless
20358 @end group
20359
20360 @group
20361 Distance := 5.0 * kg:
20362 >>> dimensions mismatch in assignment
20363 >>> left-hand side has dimension [L]
20364 >>> right-hand side has dimension [M]
20365 @end group
20366 @end smallexample
20367
20368 @noindent
20369 The dimensions of an expression are properly displayed, even if there is
20370 no explicit subtype for it. If we add to the program:
20371
20372 @smallexample @c ada
20373 @group
20374 Put ("Final velocity: ");
20375 Put (G * T, Aft =>2, Exp =>0);
20376 Put_Line ("");
20377 @end group
20378 @end smallexample
20379
20380 @noindent
20381 then the output includes:
20382 @smallexample
20383 Final velocity: 98.10 m.s**(-1)
20384 @end smallexample
20385
20386
20387 @c *********************************
20388 @node Generating Ada Bindings for C and C++ headers
20389 @chapter Generating Ada Bindings for C and C++ headers
20390 @findex binding
20391
20392 @noindent
20393 GNAT now comes with a binding generator for C and C++ headers which is
20394 intended to do 95% of the tedious work of generating Ada specs from C
20395 or C++ header files.
20396
20397 Note that this capability is not intended to generate 100% correct Ada specs,
20398 and will is some cases require manual adjustments, although it can often
20399 be used out of the box in practice.
20400
20401 Some of the known limitations include:
20402
20403 @itemize @bullet
20404 @item only very simple character constant macros are translated into Ada
20405 constants. Function macros (macros with arguments) are partially translated
20406 as comments, to be completed manually if needed.
20407 @item some extensions (e.g. vector types) are not supported
20408 @item pointers to pointers or complex structures are mapped to System.Address
20409 @item identifiers with identical name (except casing) will generate compilation
20410 errors (e.g. @code{shm_get} vs @code{SHM_GET}).
20411 @end itemize
20412
20413 The code generated is using the Ada 2005 syntax, which makes it
20414 easier to interface with other languages than previous versions of Ada.
20415
20416 @menu
20417 * Running the binding generator::
20418 * Generating bindings for C++ headers::
20419 * Switches::
20420 @end menu
20421
20422 @node Running the binding generator
20423 @section Running the binding generator
20424
20425 @noindent
20426 The binding generator is part of the @command{gcc} compiler and can be
20427 invoked via the @option{-fdump-ada-spec} switch, which will generate Ada
20428 spec files for the header files specified on the command line, and all
20429 header files needed by these files transitively. For example:
20430
20431 @smallexample
20432 $ g++ -c -fdump-ada-spec -C /usr/include/time.h
20433 $ gcc -c -gnat05 *.ads
20434 @end smallexample
20435
20436 will generate, under GNU/Linux, the following files: @file{time_h.ads},
20437 @file{bits_time_h.ads}, @file{stddef_h.ads}, @file{bits_types_h.ads} which
20438 correspond to the files @file{/usr/include/time.h},
20439 @file{/usr/include/bits/time.h}, etc@dots{}, and will then compile in Ada 2005
20440 mode these Ada specs.
20441
20442 The @code{-C} switch tells @command{gcc} to extract comments from headers,
20443 and will attempt to generate corresponding Ada comments.
20444
20445 If you want to generate a single Ada file and not the transitive closure, you
20446 can use instead the @option{-fdump-ada-spec-slim} switch.
20447
20448 You can optionally specify a parent unit, of which all generated units will
20449 be children, using @code{-fada-spec-parent=}@var{unit}.
20450
20451 Note that we recommend when possible to use the @command{g++} driver to
20452 generate bindings, even for most C headers, since this will in general
20453 generate better Ada specs. For generating bindings for C++ headers, it is
20454 mandatory to use the @command{g++} command, or @command{gcc -x c++} which
20455 is equivalent in this case. If @command{g++} cannot work on your C headers
20456 because of incompatibilities between C and C++, then you can fallback to
20457 @command{gcc} instead.
20458
20459 For an example of better bindings generated from the C++ front-end,
20460 the name of the parameters (when available) are actually ignored by the C
20461 front-end. Consider the following C header:
20462
20463 @smallexample
20464 extern void foo (int variable);
20465 @end smallexample
20466
20467 with the C front-end, @code{variable} is ignored, and the above is handled as:
20468
20469 @smallexample
20470 extern void foo (int);
20471 @end smallexample
20472
20473 generating a generic:
20474
20475 @smallexample
20476 procedure foo (param1 : int);
20477 @end smallexample
20478
20479 with the C++ front-end, the name is available, and we generate:
20480
20481 @smallexample
20482 procedure foo (variable : int);
20483 @end smallexample
20484
20485 In some cases, the generated bindings will be more complete or more meaningful
20486 when defining some macros, which you can do via the @option{-D} switch. This
20487 is for example the case with @file{Xlib.h} under GNU/Linux:
20488
20489 @smallexample
20490 g++ -c -fdump-ada-spec -DXLIB_ILLEGAL_ACCESS -C /usr/include/X11/Xlib.h
20491 @end smallexample
20492
20493 The above will generate more complete bindings than a straight call without
20494 the @option{-DXLIB_ILLEGAL_ACCESS} switch.
20495
20496 In other cases, it is not possible to parse a header file in a stand-alone
20497 manner, because other include files need to be included first. In this
20498 case, the solution is to create a small header file including the needed
20499 @code{#include} and possible @code{#define} directives. For example, to
20500 generate Ada bindings for @file{readline/readline.h}, you need to first
20501 include @file{stdio.h}, so you can create a file with the following two
20502 lines in e.g. @file{readline1.h}:
20503
20504 @smallexample
20505 #include <stdio.h>
20506 #include <readline/readline.h>
20507 @end smallexample
20508
20509 and then generate Ada bindings from this file:
20510
20511 @smallexample
20512 $ g++ -c -fdump-ada-spec readline1.h
20513 @end smallexample
20514
20515 @node Generating bindings for C++ headers
20516 @section Generating bindings for C++ headers
20517
20518 @noindent
20519 Generating bindings for C++ headers is done using the same options, always
20520 with the @command{g++} compiler.
20521
20522 In this mode, C++ classes will be mapped to Ada tagged types, constructors
20523 will be mapped using the @code{CPP_Constructor} pragma, and when possible,
20524 multiple inheritance of abstract classes will be mapped to Ada interfaces
20525 (@xref{Interfacing to C++,,,gnat_rm, GNAT Reference Manual}, for additional
20526 information on interfacing to C++).
20527
20528 For example, given the following C++ header file:
20529
20530 @smallexample
20531 @group
20532 @cartouche
20533 class Carnivore @{
20534 public:
20535 virtual int Number_Of_Teeth () = 0;
20536 @};
20537
20538 class Domestic @{
20539 public:
20540 virtual void Set_Owner (char* Name) = 0;
20541 @};
20542
20543 class Animal @{
20544 public:
20545 int Age_Count;
20546 virtual void Set_Age (int New_Age);
20547 @};
20548
20549 class Dog : Animal, Carnivore, Domestic @{
20550 public:
20551 int Tooth_Count;
20552 char *Owner;
20553
20554 virtual int Number_Of_Teeth ();
20555 virtual void Set_Owner (char* Name);
20556
20557 Dog();
20558 @};
20559 @end cartouche
20560 @end group
20561 @end smallexample
20562
20563 The corresponding Ada code is generated:
20564
20565 @smallexample @c ada
20566 @group
20567 @cartouche
20568 package Class_Carnivore is
20569 type Carnivore is limited interface;
20570 pragma Import (CPP, Carnivore);
20571
20572 function Number_Of_Teeth (this : access Carnivore) return int is abstract;
20573 end;
20574 use Class_Carnivore;
20575
20576 package Class_Domestic is
20577 type Domestic is limited interface;
20578 pragma Import (CPP, Domestic);
20579
20580 procedure Set_Owner
20581 (this : access Domestic;
20582 Name : Interfaces.C.Strings.chars_ptr) is abstract;
20583 end;
20584 use Class_Domestic;
20585
20586 package Class_Animal is
20587 type Animal is tagged limited record
20588 Age_Count : aliased int;
20589 end record;
20590 pragma Import (CPP, Animal);
20591
20592 procedure Set_Age (this : access Animal; New_Age : int);
20593 pragma Import (CPP, Set_Age, "_ZN6Animal7Set_AgeEi");
20594 end;
20595 use Class_Animal;
20596
20597 package Class_Dog is
20598 type Dog is new Animal and Carnivore and Domestic with record
20599 Tooth_Count : aliased int;
20600 Owner : Interfaces.C.Strings.chars_ptr;
20601 end record;
20602 pragma Import (CPP, Dog);
20603
20604 function Number_Of_Teeth (this : access Dog) return int;
20605 pragma Import (CPP, Number_Of_Teeth, "_ZN3Dog15Number_Of_TeethEv");
20606
20607 procedure Set_Owner
20608 (this : access Dog; Name : Interfaces.C.Strings.chars_ptr);
20609 pragma Import (CPP, Set_Owner, "_ZN3Dog9Set_OwnerEPc");
20610
20611 function New_Dog return Dog;
20612 pragma CPP_Constructor (New_Dog);
20613 pragma Import (CPP, New_Dog, "_ZN3DogC1Ev");
20614 end;
20615 use Class_Dog;
20616 @end cartouche
20617 @end group
20618 @end smallexample
20619
20620 @node Switches
20621 @section Switches
20622
20623 @table @option
20624 @item -fdump-ada-spec
20625 @cindex @option{-fdump-ada-spec} (@command{gcc})
20626 Generate Ada spec files for the given header files transitively (including
20627 all header files that these headers depend upon).
20628
20629 @item -fdump-ada-spec-slim
20630 @cindex @option{-fdump-ada-spec-slim} (@command{gcc})
20631 Generate Ada spec files for the header files specified on the command line
20632 only.
20633
20634 @item -fada-spec-parent=@var{unit}
20635 @cindex -fada-spec-parent (@command{gcc})
20636 Specifies that all files generated by @option{-fdump-ada-spec*} are
20637 to be child units of the specified parent unit.
20638
20639 @item -C
20640 @cindex @option{-C} (@command{gcc})
20641 Extract comments from headers and generate Ada comments in the Ada spec files.
20642 @end table
20643
20644 @node Other Utility Programs
20645 @chapter Other Utility Programs
20646
20647 @noindent
20648 This chapter discusses some other utility programs available in the Ada
20649 environment.
20650
20651 @menu
20652 * Using Other Utility Programs with GNAT::
20653 * The External Symbol Naming Scheme of GNAT::
20654 * Converting Ada Files to html with gnathtml::
20655 * Installing gnathtml::
20656 @ifset vms
20657 * LSE::
20658 * Profiling::
20659 @end ifset
20660 @end menu
20661
20662 @node Using Other Utility Programs with GNAT
20663 @section Using Other Utility Programs with GNAT
20664
20665 @noindent
20666 The object files generated by GNAT are in standard system format and in
20667 particular the debugging information uses this format. This means
20668 programs generated by GNAT can be used with existing utilities that
20669 depend on these formats.
20670
20671 @ifclear vms
20672 In general, any utility program that works with C will also often work with
20673 Ada programs generated by GNAT. This includes software utilities such as
20674 gprof (a profiling program), @code{gdb} (the FSF debugger), and utilities such
20675 as Purify.
20676 @end ifclear
20677
20678 @node The External Symbol Naming Scheme of GNAT
20679 @section The External Symbol Naming Scheme of GNAT
20680
20681 @noindent
20682 In order to interpret the output from GNAT, when using tools that are
20683 originally intended for use with other languages, it is useful to
20684 understand the conventions used to generate link names from the Ada
20685 entity names.
20686
20687 All link names are in all lowercase letters. With the exception of library
20688 procedure names, the mechanism used is simply to use the full expanded
20689 Ada name with dots replaced by double underscores. For example, suppose
20690 we have the following package spec:
20691
20692 @smallexample @c ada
20693 @group
20694 @cartouche
20695 package QRS is
20696 MN : Integer;
20697 end QRS;
20698 @end cartouche
20699 @end group
20700 @end smallexample
20701
20702 @noindent
20703 The variable @code{MN} has a full expanded Ada name of @code{QRS.MN}, so
20704 the corresponding link name is @code{qrs__mn}.
20705 @findex Export
20706 Of course if a @code{pragma Export} is used this may be overridden:
20707
20708 @smallexample @c ada
20709 @group
20710 @cartouche
20711 package Exports is
20712 Var1 : Integer;
20713 pragma Export (Var1, C, External_Name => "var1_name");
20714 Var2 : Integer;
20715 pragma Export (Var2, C, Link_Name => "var2_link_name");
20716 end Exports;
20717 @end cartouche
20718 @end group
20719 @end smallexample
20720
20721 @noindent
20722 In this case, the link name for @var{Var1} is whatever link name the
20723 C compiler would assign for the C function @var{var1_name}. This typically
20724 would be either @var{var1_name} or @var{_var1_name}, depending on operating
20725 system conventions, but other possibilities exist. The link name for
20726 @var{Var2} is @var{var2_link_name}, and this is not operating system
20727 dependent.
20728
20729 @findex _main
20730 One exception occurs for library level procedures. A potential ambiguity
20731 arises between the required name @code{_main} for the C main program,
20732 and the name we would otherwise assign to an Ada library level procedure
20733 called @code{Main} (which might well not be the main program).
20734
20735 To avoid this ambiguity, we attach the prefix @code{_ada_} to such
20736 names. So if we have a library level procedure such as
20737
20738 @smallexample @c ada
20739 @group
20740 @cartouche
20741 procedure Hello (S : String);
20742 @end cartouche
20743 @end group
20744 @end smallexample
20745
20746 @noindent
20747 the external name of this procedure will be @var{_ada_hello}.
20748
20749
20750 @node Converting Ada Files to html with gnathtml
20751 @section Converting Ada Files to HTML with @code{gnathtml}
20752
20753 @noindent
20754 This @code{Perl} script allows Ada source files to be browsed using
20755 standard Web browsers. For installation procedure, see the section
20756 @xref{Installing gnathtml}.
20757
20758 Ada reserved keywords are highlighted in a bold font and Ada comments in
20759 a blue font. Unless your program was compiled with the gcc @option{-gnatx}
20760 switch to suppress the generation of cross-referencing information, user
20761 defined variables and types will appear in a different color; you will
20762 be able to click on any identifier and go to its declaration.
20763
20764 The command line is as follow:
20765 @smallexample
20766 @c $ perl gnathtml.pl @ovar{^switches^options^} @var{ada-files}
20767 @c Expanding @ovar macro inline (explanation in macro def comments)
20768 $ perl gnathtml.pl @r{[}@var{^switches^options^}@r{]} @var{ada-files}
20769 @end smallexample
20770
20771 @noindent
20772 You can pass it as many Ada files as you want. @code{gnathtml} will generate
20773 an html file for every ada file, and a global file called @file{index.htm}.
20774 This file is an index of every identifier defined in the files.
20775
20776 The available ^switches^options^ are the following ones:
20777
20778 @table @option
20779 @item -83
20780 @cindex @option{-83} (@code{gnathtml})
20781 Only the Ada 83 subset of keywords will be highlighted.
20782
20783 @item -cc @var{color}
20784 @cindex @option{-cc} (@code{gnathtml})
20785 This option allows you to change the color used for comments. The default
20786 value is green. The color argument can be any name accepted by html.
20787
20788 @item -d
20789 @cindex @option{-d} (@code{gnathtml})
20790 If the Ada files depend on some other files (for instance through
20791 @code{with} clauses, the latter files will also be converted to html.
20792 Only the files in the user project will be converted to html, not the files
20793 in the run-time library itself.
20794
20795 @item -D
20796 @cindex @option{-D} (@code{gnathtml})
20797 This command is the same as @option{-d} above, but @command{gnathtml} will
20798 also look for files in the run-time library, and generate html files for them.
20799
20800 @item -ext @var{extension}
20801 @cindex @option{-ext} (@code{gnathtml})
20802 This option allows you to change the extension of the generated HTML files.
20803 If you do not specify an extension, it will default to @file{htm}.
20804
20805 @item -f
20806 @cindex @option{-f} (@code{gnathtml})
20807 By default, gnathtml will generate html links only for global entities
20808 ('with'ed units, global variables and types,@dots{}). If you specify
20809 @option{-f} on the command line, then links will be generated for local
20810 entities too.
20811
20812 @item -l @var{number}
20813 @cindex @option{-l} (@code{gnathtml})
20814 If this ^switch^option^ is provided and @var{number} is not 0, then
20815 @code{gnathtml} will number the html files every @var{number} line.
20816
20817 @item -I @var{dir}
20818 @cindex @option{-I} (@code{gnathtml})
20819 Specify a directory to search for library files (@file{.ALI} files) and
20820 source files. You can provide several -I switches on the command line,
20821 and the directories will be parsed in the order of the command line.
20822
20823 @item -o @var{dir}
20824 @cindex @option{-o} (@code{gnathtml})
20825 Specify the output directory for html files. By default, gnathtml will
20826 saved the generated html files in a subdirectory named @file{html/}.
20827
20828 @item -p @var{file}
20829 @cindex @option{-p} (@code{gnathtml})
20830 If you are using Emacs and the most recent Emacs Ada mode, which provides
20831 a full Integrated Development Environment for compiling, checking,
20832 running and debugging applications, you may use @file{.gpr} files
20833 to give the directories where Emacs can find sources and object files.
20834
20835 Using this ^switch^option^, you can tell gnathtml to use these files.
20836 This allows you to get an html version of your application, even if it
20837 is spread over multiple directories.
20838
20839 @item -sc @var{color}
20840 @cindex @option{-sc} (@code{gnathtml})
20841 This ^switch^option^ allows you to change the color used for symbol
20842 definitions.
20843 The default value is red. The color argument can be any name accepted by html.
20844
20845 @item -t @var{file}
20846 @cindex @option{-t} (@code{gnathtml})
20847 This ^switch^option^ provides the name of a file. This file contains a list of
20848 file names to be converted, and the effect is exactly as though they had
20849 appeared explicitly on the command line. This
20850 is the recommended way to work around the command line length limit on some
20851 systems.
20852
20853 @end table
20854
20855 @node Installing gnathtml
20856 @section Installing @code{gnathtml}
20857
20858 @noindent
20859 @code{Perl} needs to be installed on your machine to run this script.
20860 @code{Perl} is freely available for almost every architecture and
20861 Operating System via the Internet.
20862
20863 On Unix systems, you may want to modify the first line of the script
20864 @code{gnathtml}, to explicitly tell the Operating system where Perl
20865 is. The syntax of this line is:
20866 @smallexample
20867 #!full_path_name_to_perl
20868 @end smallexample
20869
20870 @noindent
20871 Alternatively, you may run the script using the following command line:
20872
20873 @smallexample
20874 @c $ perl gnathtml.pl @ovar{switches} @var{files}
20875 @c Expanding @ovar macro inline (explanation in macro def comments)
20876 $ perl gnathtml.pl @r{[}@var{switches}@r{]} @var{files}
20877 @end smallexample
20878
20879 @ifset vms
20880 @node LSE
20881 @section LSE
20882 @findex LSE
20883
20884 @noindent
20885 The GNAT distribution provides an Ada 95 template for the HP Language
20886 Sensitive Editor (LSE), a component of DECset. In order to
20887 access it, invoke LSE with the qualifier /ENVIRONMENT=GNU:[LIB]ADA95.ENV.
20888
20889 @node Profiling
20890 @section Profiling
20891 @findex PCA
20892
20893 @noindent
20894 GNAT supports The HP Performance Coverage Analyzer (PCA), a component
20895 of DECset. To use it proceed as outlined under ``HELP PCA'', except for running
20896 the collection phase with the /DEBUG qualifier.
20897
20898 @smallexample
20899 $ GNAT MAKE /DEBUG <PROGRAM_NAME>
20900 $ DEFINE LIB$DEBUG PCA$COLLECTOR
20901 $ RUN/DEBUG <PROGRAM_NAME>
20902 @end smallexample
20903 @noindent
20904 @end ifset
20905
20906 @ifclear vms
20907 @c ******************************
20908 @node Code Coverage and Profiling
20909 @chapter Code Coverage and Profiling
20910 @cindex Code Coverage
20911 @cindex Profiling
20912
20913 @noindent
20914 This chapter describes how to use @code{gcov} - coverage testing tool - and
20915 @code{gprof} - profiler tool - on your Ada programs.
20916
20917 @menu
20918 * Code Coverage of Ada Programs with gcov::
20919 * Profiling an Ada Program with gprof::
20920 @end menu
20921
20922 @node Code Coverage of Ada Programs with gcov
20923 @section Code Coverage of Ada Programs with gcov
20924 @cindex gcov
20925 @cindex -fprofile-arcs
20926 @cindex -ftest-coverage
20927 @cindex -coverage
20928 @cindex Code Coverage
20929
20930 @noindent
20931 @code{gcov} is a test coverage program: it analyzes the execution of a given
20932 program on selected tests, to help you determine the portions of the program
20933 that are still untested.
20934
20935 @code{gcov} is part of the GCC suite, and is described in detail in the GCC
20936 User's Guide. You can refer to this documentation for a more complete
20937 description.
20938
20939 This chapter provides a quick startup guide, and
20940 details some Gnat-specific features.
20941
20942 @menu
20943 * Quick startup guide::
20944 * Gnat specifics::
20945 @end menu
20946
20947 @node Quick startup guide
20948 @subsection Quick startup guide
20949
20950 In order to perform coverage analysis of a program using @code{gcov}, 3
20951 steps are needed:
20952
20953 @itemize @bullet
20954 @item
20955 Code instrumentation during the compilation process
20956 @item
20957 Execution of the instrumented program
20958 @item
20959 Execution of the @code{gcov} tool to generate the result.
20960 @end itemize
20961
20962 The code instrumentation needed by gcov is created at the object level:
20963 The source code is not modified in any way, because the instrumentation code is
20964 inserted by gcc during the compilation process. To compile your code with code
20965 coverage activated, you need to recompile your whole project using the
20966 switches
20967 @code{-fprofile-arcs} and @code{-ftest-coverage}, and link it using
20968 @code{-fprofile-arcs}.
20969
20970 @smallexample
20971 $ gnatmake -P my_project.gpr -f -cargs -fprofile-arcs -ftest-coverage \
20972 -largs -fprofile-arcs
20973 @end smallexample
20974
20975 This compilation process will create @file{.gcno} files together with
20976 the usual object files.
20977
20978 Once the program is compiled with coverage instrumentation, you can
20979 run it as many times as needed - on portions of a test suite for
20980 example. The first execution will produce @file{.gcda} files at the
20981 same location as the @file{.gcno} files. The following executions
20982 will update those files, so that a cumulative result of the covered
20983 portions of the program is generated.
20984
20985 Finally, you need to call the @code{gcov} tool. The different options of
20986 @code{gcov} are available in the GCC User's Guide, section 'Invoking gcov'.
20987
20988 This will create annotated source files with a @file{.gcov} extension:
20989 @file{my_main.adb} file will be analysed in @file{my_main.adb.gcov}.
20990
20991 @node Gnat specifics
20992 @subsection Gnat specifics
20993
20994 Because Ada semantics, portions of the source code may be shared among
20995 several object files. This is the case for example when generics are
20996 involved, when inlining is active or when declarations generate initialisation
20997 calls. In order to take
20998 into account this shared code, you need to call @code{gcov} on all
20999 source files of the tested program at once.
21000
21001 The list of source files might exceed the system's maximum command line
21002 length. In order to bypass this limitation, a new mechanism has been
21003 implemented in @code{gcov}: you can now list all your project's files into a
21004 text file, and provide this file to gcov as a parameter, preceded by a @@
21005 (e.g. @samp{gcov @@mysrclist.txt}).
21006
21007 Note that on AIX compiling a static library with @code{-fprofile-arcs} is
21008 not supported as there can be unresolved symbols during the final link.
21009
21010 @node Profiling an Ada Program with gprof
21011 @section Profiling an Ada Program with gprof
21012 @cindex gprof
21013 @cindex -pg
21014 @cindex Profiling
21015
21016 @noindent
21017 This section is not meant to be an exhaustive documentation of @code{gprof}.
21018 Full documentation for it can be found in the GNU Profiler User's Guide
21019 documentation that is part of this GNAT distribution.
21020
21021 Profiling a program helps determine the parts of a program that are executed
21022 most often, and are therefore the most time-consuming.
21023
21024 @code{gprof} is the standard GNU profiling tool; it has been enhanced to
21025 better handle Ada programs and multitasking.
21026 It is currently supported on the following platforms
21027 @itemize @bullet
21028 @item
21029 linux x86/x86_64
21030 @item
21031 solaris sparc/sparc64/x86
21032 @item
21033 windows x86
21034 @end itemize
21035
21036 @noindent
21037 In order to profile a program using @code{gprof}, 3 steps are needed:
21038
21039 @itemize @bullet
21040 @item
21041 Code instrumentation, requiring a full recompilation of the project with the
21042 proper switches.
21043 @item
21044 Execution of the program under the analysis conditions, i.e. with the desired
21045 input.
21046 @item
21047 Analysis of the results using the @code{gprof} tool.
21048 @end itemize
21049
21050 @noindent
21051 The following sections detail the different steps, and indicate how
21052 to interpret the results:
21053 @menu
21054 * Compilation for profiling::
21055 * Program execution::
21056 * Running gprof::
21057 * Interpretation of profiling results::
21058 @end menu
21059
21060 @node Compilation for profiling
21061 @subsection Compilation for profiling
21062 @cindex -pg
21063 @cindex Profiling
21064
21065 In order to profile a program the first step is to tell the compiler
21066 to generate the necessary profiling information. The compiler switch to be used
21067 is @code{-pg}, which must be added to other compilation switches. This
21068 switch needs to be specified both during compilation and link stages, and can
21069 be specified once when using gnatmake:
21070
21071 @smallexample
21072 gnatmake -f -pg -P my_project
21073 @end smallexample
21074
21075 @noindent
21076 Note that only the objects that were compiled with the @samp{-pg} switch will
21077 be profiled; if you need to profile your whole project, use the @samp{-f}
21078 gnatmake switch to force full recompilation.
21079
21080 @node Program execution
21081 @subsection Program execution
21082
21083 @noindent
21084 Once the program has been compiled for profiling, you can run it as usual.
21085
21086 The only constraint imposed by profiling is that the program must terminate
21087 normally. An interrupted program (via a Ctrl-C, kill, etc.) will not be
21088 properly analyzed.
21089
21090 Once the program completes execution, a data file called @file{gmon.out} is
21091 generated in the directory where the program was launched from. If this file
21092 already exists, it will be overwritten.
21093
21094 @node Running gprof
21095 @subsection Running gprof
21096
21097 @noindent
21098 The @code{gprof} tool is called as follow:
21099
21100 @smallexample
21101 gprof my_prog gmon.out
21102 @end smallexample
21103
21104 @noindent
21105 or simpler:
21106
21107 @smallexample
21108 gprof my_prog
21109 @end smallexample
21110
21111 @noindent
21112 The complete form of the gprof command line is the following:
21113
21114 @smallexample
21115 gprof [^switches^options^] [executable [data-file]]
21116 @end smallexample
21117
21118 @noindent
21119 @code{gprof} supports numerous ^switch^options^. The order of these
21120 ^switch^options^ does not matter. The full list of options can be found in
21121 the GNU Profiler User's Guide documentation that comes with this documentation.
21122
21123 The following is the subset of those switches that is most relevant:
21124
21125 @table @option
21126
21127 @item --demangle[=@var{style}]
21128 @itemx --no-demangle
21129 @cindex @option{--demangle} (@code{gprof})
21130 These options control whether symbol names should be demangled when
21131 printing output. The default is to demangle C++ symbols. The
21132 @code{--no-demangle} option may be used to turn off demangling. Different
21133 compilers have different mangling styles. The optional demangling style
21134 argument can be used to choose an appropriate demangling style for your
21135 compiler, in particular Ada symbols generated by GNAT can be demangled using
21136 @code{--demangle=gnat}.
21137
21138 @item -e @var{function_name}
21139 @cindex @option{-e} (@code{gprof})
21140 The @samp{-e @var{function}} option tells @code{gprof} not to print
21141 information about the function @var{function_name} (and its
21142 children@dots{}) in the call graph. The function will still be listed
21143 as a child of any functions that call it, but its index number will be
21144 shown as @samp{[not printed]}. More than one @samp{-e} option may be
21145 given; only one @var{function_name} may be indicated with each @samp{-e}
21146 option.
21147
21148 @item -E @var{function_name}
21149 @cindex @option{-E} (@code{gprof})
21150 The @code{-E @var{function}} option works like the @code{-e} option, but
21151 execution time spent in the function (and children who were not called from
21152 anywhere else), will not be used to compute the percentages-of-time for
21153 the call graph. More than one @samp{-E} option may be given; only one
21154 @var{function_name} may be indicated with each @samp{-E} option.
21155
21156 @item -f @var{function_name}
21157 @cindex @option{-f} (@code{gprof})
21158 The @samp{-f @var{function}} option causes @code{gprof} to limit the
21159 call graph to the function @var{function_name} and its children (and
21160 their children@dots{}). More than one @samp{-f} option may be given;
21161 only one @var{function_name} may be indicated with each @samp{-f}
21162 option.
21163
21164 @item -F @var{function_name}
21165 @cindex @option{-F} (@code{gprof})
21166 The @samp{-F @var{function}} option works like the @code{-f} option, but
21167 only time spent in the function and its children (and their
21168 children@dots{}) will be used to determine total-time and
21169 percentages-of-time for the call graph. More than one @samp{-F} option
21170 may be given; only one @var{function_name} may be indicated with each
21171 @samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.
21172
21173 @end table
21174
21175 @node Interpretation of profiling results
21176 @subsection Interpretation of profiling results
21177
21178 @noindent
21179
21180 The results of the profiling analysis are represented by two arrays: the
21181 'flat profile' and the 'call graph'. Full documentation of those outputs
21182 can be found in the GNU Profiler User's Guide.
21183
21184 The flat profile shows the time spent in each function of the program, and how
21185 many time it has been called. This allows you to locate easily the most
21186 time-consuming functions.
21187
21188 The call graph shows, for each subprogram, the subprograms that call it,
21189 and the subprograms that it calls. It also provides an estimate of the time
21190 spent in each of those callers/called subprograms.
21191 @end ifclear
21192
21193 @c ******************************
21194 @node Running and Debugging Ada Programs
21195 @chapter Running and Debugging Ada Programs
21196 @cindex Debugging
21197
21198 @noindent
21199 This chapter discusses how to debug Ada programs.
21200 @ifset vms
21201 It applies to GNAT on the Alpha OpenVMS platform;
21202 for I64 OpenVMS please refer to the @cite{OpenVMS Debugger Manual},
21203 since HP has implemented Ada support in the OpenVMS debugger on I64.
21204 @end ifset
21205
21206 An incorrect Ada program may be handled in three ways by the GNAT compiler:
21207
21208 @enumerate
21209 @item
21210 The illegality may be a violation of the static semantics of Ada. In
21211 that case GNAT diagnoses the constructs in the program that are illegal.
21212 It is then a straightforward matter for the user to modify those parts of
21213 the program.
21214
21215 @item
21216 The illegality may be a violation of the dynamic semantics of Ada. In
21217 that case the program compiles and executes, but may generate incorrect
21218 results, or may terminate abnormally with some exception.
21219
21220 @item
21221 When presented with a program that contains convoluted errors, GNAT
21222 itself may terminate abnormally without providing full diagnostics on
21223 the incorrect user program.
21224 @end enumerate
21225
21226 @menu
21227 * The GNAT Debugger GDB::
21228 * Running GDB::
21229 * Introduction to GDB Commands::
21230 * Using Ada Expressions::
21231 * Calling User-Defined Subprograms::
21232 * Using the Next Command in a Function::
21233 * Ada Exceptions::
21234 * Ada Tasks::
21235 * Debugging Generic Units::
21236 * Remote Debugging with gdbserver::
21237 * GNAT Abnormal Termination or Failure to Terminate::
21238 * Naming Conventions for GNAT Source Files::
21239 * Getting Internal Debugging Information::
21240 * Stack Traceback::
21241 @end menu
21242
21243 @cindex Debugger
21244 @findex gdb
21245
21246 @node The GNAT Debugger GDB
21247 @section The GNAT Debugger GDB
21248
21249 @noindent
21250 @code{GDB} is a general purpose, platform-independent debugger that
21251 can be used to debug mixed-language programs compiled with @command{gcc},
21252 and in particular is capable of debugging Ada programs compiled with
21253 GNAT. The latest versions of @code{GDB} are Ada-aware and can handle
21254 complex Ada data structures.
21255
21256 @xref{Top,, Debugging with GDB, gdb, Debugging with GDB},
21257 @ifset vms
21258 located in the GNU:[DOCS] directory,
21259 @end ifset
21260 for full details on the usage of @code{GDB}, including a section on
21261 its usage on programs. This manual should be consulted for full
21262 details. The section that follows is a brief introduction to the
21263 philosophy and use of @code{GDB}.
21264
21265 When GNAT programs are compiled, the compiler optionally writes debugging
21266 information into the generated object file, including information on
21267 line numbers, and on declared types and variables. This information is
21268 separate from the generated code. It makes the object files considerably
21269 larger, but it does not add to the size of the actual executable that
21270 will be loaded into memory, and has no impact on run-time performance. The
21271 generation of debug information is triggered by the use of the
21272 ^-g^/DEBUG^ switch in the @command{gcc} or @command{gnatmake} command
21273 used to carry out the compilations. It is important to emphasize that
21274 the use of these options does not change the generated code.
21275
21276 The debugging information is written in standard system formats that
21277 are used by many tools, including debuggers and profilers. The format
21278 of the information is typically designed to describe C types and
21279 semantics, but GNAT implements a translation scheme which allows full
21280 details about Ada types and variables to be encoded into these
21281 standard C formats. Details of this encoding scheme may be found in
21282 the file exp_dbug.ads in the GNAT source distribution. However, the
21283 details of this encoding are, in general, of no interest to a user,
21284 since @code{GDB} automatically performs the necessary decoding.
21285
21286 When a program is bound and linked, the debugging information is
21287 collected from the object files, and stored in the executable image of
21288 the program. Again, this process significantly increases the size of
21289 the generated executable file, but it does not increase the size of
21290 the executable program itself. Furthermore, if this program is run in
21291 the normal manner, it runs exactly as if the debug information were
21292 not present, and takes no more actual memory.
21293
21294 However, if the program is run under control of @code{GDB}, the
21295 debugger is activated. The image of the program is loaded, at which
21296 point it is ready to run. If a run command is given, then the program
21297 will run exactly as it would have if @code{GDB} were not present. This
21298 is a crucial part of the @code{GDB} design philosophy. @code{GDB} is
21299 entirely non-intrusive until a breakpoint is encountered. If no
21300 breakpoint is ever hit, the program will run exactly as it would if no
21301 debugger were present. When a breakpoint is hit, @code{GDB} accesses
21302 the debugging information and can respond to user commands to inspect
21303 variables, and more generally to report on the state of execution.
21304
21305 @c **************
21306 @node Running GDB
21307 @section Running GDB
21308
21309 @noindent
21310 This section describes how to initiate the debugger.
21311 @c The above sentence is really just filler, but it was otherwise
21312 @c clumsy to get the first paragraph nonindented given the conditional
21313 @c nature of the description
21314
21315 @ifclear vms
21316 The debugger can be launched from a @code{GPS} menu or
21317 directly from the command line. The description below covers the latter use.
21318 All the commands shown can be used in the @code{GPS} debug console window,
21319 but there are usually more GUI-based ways to achieve the same effect.
21320 @end ifclear
21321
21322 The command to run @code{GDB} is
21323
21324 @smallexample
21325 $ ^gdb program^GDB PROGRAM^
21326 @end smallexample
21327
21328 @noindent
21329 where @code{^program^PROGRAM^} is the name of the executable file. This
21330 activates the debugger and results in a prompt for debugger commands.
21331 The simplest command is simply @code{run}, which causes the program to run
21332 exactly as if the debugger were not present. The following section
21333 describes some of the additional commands that can be given to @code{GDB}.
21334
21335 @c *******************************
21336 @node Introduction to GDB Commands
21337 @section Introduction to GDB Commands
21338
21339 @noindent
21340 @code{GDB} contains a large repertoire of commands. @xref{Top,,
21341 Debugging with GDB, gdb, Debugging with GDB},
21342 @ifset vms
21343 located in the GNU:[DOCS] directory,
21344 @end ifset
21345 for extensive documentation on the use
21346 of these commands, together with examples of their use. Furthermore,
21347 the command @command{help} invoked from within GDB activates a simple help
21348 facility which summarizes the available commands and their options.
21349 In this section we summarize a few of the most commonly
21350 used commands to give an idea of what @code{GDB} is about. You should create
21351 a simple program with debugging information and experiment with the use of
21352 these @code{GDB} commands on the program as you read through the
21353 following section.
21354
21355 @table @code
21356 @item set args @var{arguments}
21357 The @var{arguments} list above is a list of arguments to be passed to
21358 the program on a subsequent run command, just as though the arguments
21359 had been entered on a normal invocation of the program. The @code{set args}
21360 command is not needed if the program does not require arguments.
21361
21362 @item run
21363 The @code{run} command causes execution of the program to start from
21364 the beginning. If the program is already running, that is to say if
21365 you are currently positioned at a breakpoint, then a prompt will ask
21366 for confirmation that you want to abandon the current execution and
21367 restart.
21368
21369 @item breakpoint @var{location}
21370 The breakpoint command sets a breakpoint, that is to say a point at which
21371 execution will halt and @code{GDB} will await further
21372 commands. @var{location} is
21373 either a line number within a file, given in the format @code{file:linenumber},
21374 or it is the name of a subprogram. If you request that a breakpoint be set on
21375 a subprogram that is overloaded, a prompt will ask you to specify on which of
21376 those subprograms you want to breakpoint. You can also
21377 specify that all of them should be breakpointed. If the program is run
21378 and execution encounters the breakpoint, then the program
21379 stops and @code{GDB} signals that the breakpoint was encountered by
21380 printing the line of code before which the program is halted.
21381
21382 @item catch exception @var{name}
21383 This command causes the program execution to stop whenever exception
21384 @var{name} is raised. If @var{name} is omitted, then the execution is
21385 suspended when any exception is raised.
21386
21387 @item print @var{expression}
21388 This will print the value of the given expression. Most simple
21389 Ada expression formats are properly handled by @code{GDB}, so the expression
21390 can contain function calls, variables, operators, and attribute references.
21391
21392 @item continue
21393 Continues execution following a breakpoint, until the next breakpoint or the
21394 termination of the program.
21395
21396 @item step
21397 Executes a single line after a breakpoint. If the next statement
21398 is a subprogram call, execution continues into (the first statement of)
21399 the called subprogram.
21400
21401 @item next
21402 Executes a single line. If this line is a subprogram call, executes and
21403 returns from the call.
21404
21405 @item list
21406 Lists a few lines around the current source location. In practice, it
21407 is usually more convenient to have a separate edit window open with the
21408 relevant source file displayed. Successive applications of this command
21409 print subsequent lines. The command can be given an argument which is a
21410 line number, in which case it displays a few lines around the specified one.
21411
21412 @item backtrace
21413 Displays a backtrace of the call chain. This command is typically
21414 used after a breakpoint has occurred, to examine the sequence of calls that
21415 leads to the current breakpoint. The display includes one line for each
21416 activation record (frame) corresponding to an active subprogram.
21417
21418 @item up
21419 At a breakpoint, @code{GDB} can display the values of variables local
21420 to the current frame. The command @code{up} can be used to
21421 examine the contents of other active frames, by moving the focus up
21422 the stack, that is to say from callee to caller, one frame at a time.
21423
21424 @item down
21425 Moves the focus of @code{GDB} down from the frame currently being
21426 examined to the frame of its callee (the reverse of the previous command),
21427
21428 @item frame @var{n}
21429 Inspect the frame with the given number. The value 0 denotes the frame
21430 of the current breakpoint, that is to say the top of the call stack.
21431
21432 @item kill
21433 Kills the child process in which the program is running under GDB.
21434 This may be useful for several purposes:
21435 @itemize @bullet
21436 @item
21437 It allows you to recompile and relink your program, since on many systems
21438 you cannot regenerate an executable file while it is running in a process.
21439 @item
21440 You can run your program outside the debugger, on systems that do not
21441 permit executing a program outside GDB while breakpoints are set
21442 within GDB.
21443 @item
21444 It allows you to debug a core dump rather than a running process.
21445 @end itemize
21446 @end table
21447
21448 @noindent
21449 The above list is a very short introduction to the commands that
21450 @code{GDB} provides. Important additional capabilities, including conditional
21451 breakpoints, the ability to execute command sequences on a breakpoint,
21452 the ability to debug at the machine instruction level and many other
21453 features are described in detail in @ref{Top,, Debugging with GDB, gdb,
21454 Debugging with GDB}. Note that most commands can be abbreviated
21455 (for example, c for continue, bt for backtrace).
21456
21457 @node Using Ada Expressions
21458 @section Using Ada Expressions
21459 @cindex Ada expressions
21460
21461 @noindent
21462 @code{GDB} supports a fairly large subset of Ada expression syntax, with some
21463 extensions. The philosophy behind the design of this subset is
21464
21465 @itemize @bullet
21466 @item
21467 That @code{GDB} should provide basic literals and access to operations for
21468 arithmetic, dereferencing, field selection, indexing, and subprogram calls,
21469 leaving more sophisticated computations to subprograms written into the
21470 program (which therefore may be called from @code{GDB}).
21471
21472 @item
21473 That type safety and strict adherence to Ada language restrictions
21474 are not particularly important to the @code{GDB} user.
21475
21476 @item
21477 That brevity is important to the @code{GDB} user.
21478 @end itemize
21479
21480 @noindent
21481 Thus, for brevity, the debugger acts as if there were
21482 implicit @code{with} and @code{use} clauses in effect for all user-written
21483 packages, thus making it unnecessary to fully qualify most names with
21484 their packages, regardless of context. Where this causes ambiguity,
21485 @code{GDB} asks the user's intent.
21486
21487 For details on the supported Ada syntax, see @ref{Top,, Debugging with
21488 GDB, gdb, Debugging with GDB}.
21489
21490 @node Calling User-Defined Subprograms
21491 @section Calling User-Defined Subprograms
21492
21493 @noindent
21494 An important capability of @code{GDB} is the ability to call user-defined
21495 subprograms while debugging. This is achieved simply by entering
21496 a subprogram call statement in the form:
21497
21498 @smallexample
21499 call subprogram-name (parameters)
21500 @end smallexample
21501
21502 @noindent
21503 The keyword @code{call} can be omitted in the normal case where the
21504 @code{subprogram-name} does not coincide with any of the predefined
21505 @code{GDB} commands.
21506
21507 The effect is to invoke the given subprogram, passing it the
21508 list of parameters that is supplied. The parameters can be expressions and
21509 can include variables from the program being debugged. The
21510 subprogram must be defined
21511 at the library level within your program, and @code{GDB} will call the
21512 subprogram within the environment of your program execution (which
21513 means that the subprogram is free to access or even modify variables
21514 within your program).
21515
21516 The most important use of this facility is in allowing the inclusion of
21517 debugging routines that are tailored to particular data structures
21518 in your program. Such debugging routines can be written to provide a suitably
21519 high-level description of an abstract type, rather than a low-level dump
21520 of its physical layout. After all, the standard
21521 @code{GDB print} command only knows the physical layout of your
21522 types, not their abstract meaning. Debugging routines can provide information
21523 at the desired semantic level and are thus enormously useful.
21524
21525 For example, when debugging GNAT itself, it is crucial to have access to
21526 the contents of the tree nodes used to represent the program internally.
21527 But tree nodes are represented simply by an integer value (which in turn
21528 is an index into a table of nodes).
21529 Using the @code{print} command on a tree node would simply print this integer
21530 value, which is not very useful. But the PN routine (defined in file
21531 treepr.adb in the GNAT sources) takes a tree node as input, and displays
21532 a useful high level representation of the tree node, which includes the
21533 syntactic category of the node, its position in the source, the integers
21534 that denote descendant nodes and parent node, as well as varied
21535 semantic information. To study this example in more detail, you might want to
21536 look at the body of the PN procedure in the stated file.
21537
21538 @node Using the Next Command in a Function
21539 @section Using the Next Command in a Function
21540
21541 @noindent
21542 When you use the @code{next} command in a function, the current source
21543 location will advance to the next statement as usual. A special case
21544 arises in the case of a @code{return} statement.
21545
21546 Part of the code for a return statement is the ``epilog'' of the function.
21547 This is the code that returns to the caller. There is only one copy of
21548 this epilog code, and it is typically associated with the last return
21549 statement in the function if there is more than one return. In some
21550 implementations, this epilog is associated with the first statement
21551 of the function.
21552
21553 The result is that if you use the @code{next} command from a return
21554 statement that is not the last return statement of the function you
21555 may see a strange apparent jump to the last return statement or to
21556 the start of the function. You should simply ignore this odd jump.
21557 The value returned is always that from the first return statement
21558 that was stepped through.
21559
21560 @node Ada Exceptions
21561 @section Stopping when Ada Exceptions are Raised
21562 @cindex Exceptions
21563
21564 @noindent
21565 You can set catchpoints that stop the program execution when your program
21566 raises selected exceptions.
21567
21568 @table @code
21569 @item catch exception
21570 Set a catchpoint that stops execution whenever (any task in the) program
21571 raises any exception.
21572
21573 @item catch exception @var{name}
21574 Set a catchpoint that stops execution whenever (any task in the) program
21575 raises the exception @var{name}.
21576
21577 @item catch exception unhandled
21578 Set a catchpoint that stops executing whenever (any task in the) program
21579 raises an exception for which there is no handler.
21580
21581 @item info exceptions
21582 @itemx info exceptions @var{regexp}
21583 The @code{info exceptions} command permits the user to examine all defined
21584 exceptions within Ada programs. With a regular expression, @var{regexp}, as
21585 argument, prints out only those exceptions whose name matches @var{regexp}.
21586 @end table
21587
21588 @node Ada Tasks
21589 @section Ada Tasks
21590 @cindex Tasks
21591
21592 @noindent
21593 @code{GDB} allows the following task-related commands:
21594
21595 @table @code
21596 @item info tasks
21597 This command shows a list of current Ada tasks, as in the following example:
21598
21599 @smallexample
21600 @iftex
21601 @leftskip=0cm
21602 @end iftex
21603 (gdb) info tasks
21604 ID TID P-ID Thread Pri State Name
21605 1 8088000 0 807e000 15 Child Activation Wait main_task
21606 2 80a4000 1 80ae000 15 Accept/Select Wait b
21607 3 809a800 1 80a4800 15 Child Activation Wait a
21608 * 4 80ae800 3 80b8000 15 Running c
21609 @end smallexample
21610
21611 @noindent
21612 In this listing, the asterisk before the first task indicates it to be the
21613 currently running task. The first column lists the task ID that is used
21614 to refer to tasks in the following commands.
21615
21616 @item break @var{linespec} task @var{taskid}
21617 @itemx break @var{linespec} task @var{taskid} if @dots{}
21618 @cindex Breakpoints and tasks
21619 These commands are like the @code{break @dots{} thread @dots{}}.
21620 @var{linespec} specifies source lines.
21621
21622 Use the qualifier @samp{task @var{taskid}} with a breakpoint command
21623 to specify that you only want @code{GDB} to stop the program when a
21624 particular Ada task reaches this breakpoint. @var{taskid} is one of the
21625 numeric task identifiers assigned by @code{GDB}, shown in the first
21626 column of the @samp{info tasks} display.
21627
21628 If you do not specify @samp{task @var{taskid}} when you set a
21629 breakpoint, the breakpoint applies to @emph{all} tasks of your
21630 program.
21631
21632 You can use the @code{task} qualifier on conditional breakpoints as
21633 well; in this case, place @samp{task @var{taskid}} before the
21634 breakpoint condition (before the @code{if}).
21635
21636 @item task @var{taskno}
21637 @cindex Task switching
21638
21639 This command allows to switch to the task referred by @var{taskno}. In
21640 particular, This allows to browse the backtrace of the specified
21641 task. It is advised to switch back to the original task before
21642 continuing execution otherwise the scheduling of the program may be
21643 perturbed.
21644 @end table
21645
21646 @noindent
21647 For more detailed information on the tasking support,
21648 see @ref{Top,, Debugging with GDB, gdb, Debugging with GDB}.
21649
21650 @node Debugging Generic Units
21651 @section Debugging Generic Units
21652 @cindex Debugging Generic Units
21653 @cindex Generics
21654
21655 @noindent
21656 GNAT always uses code expansion for generic instantiation. This means that
21657 each time an instantiation occurs, a complete copy of the original code is
21658 made, with appropriate substitutions of formals by actuals.
21659
21660 It is not possible to refer to the original generic entities in
21661 @code{GDB}, but it is always possible to debug a particular instance of
21662 a generic, by using the appropriate expanded names. For example, if we have
21663
21664 @smallexample @c ada
21665 @group
21666 @cartouche
21667 procedure g is
21668
21669 generic package k is
21670 procedure kp (v1 : in out integer);
21671 end k;
21672
21673 package body k is
21674 procedure kp (v1 : in out integer) is
21675 begin
21676 v1 := v1 + 1;
21677 end kp;
21678 end k;
21679
21680 package k1 is new k;
21681 package k2 is new k;
21682
21683 var : integer := 1;
21684
21685 begin
21686 k1.kp (var);
21687 k2.kp (var);
21688 k1.kp (var);
21689 k2.kp (var);
21690 end;
21691 @end cartouche
21692 @end group
21693 @end smallexample
21694
21695 @noindent
21696 Then to break on a call to procedure kp in the k2 instance, simply
21697 use the command:
21698
21699 @smallexample
21700 (gdb) break g.k2.kp
21701 @end smallexample
21702
21703 @noindent
21704 When the breakpoint occurs, you can step through the code of the
21705 instance in the normal manner and examine the values of local variables, as for
21706 other units.
21707
21708 @node Remote Debugging with gdbserver
21709 @section Remote Debugging with gdbserver
21710 @cindex Remote Debugging with gdbserver
21711
21712 @noindent
21713 On platforms where gdbserver is supported, it is possible to use this tool
21714 to debug your application remotely. This can be useful in situations
21715 where the program needs to be run on a target host that is different
21716 from the host used for development, particularly when the target has
21717 a limited amount of resources (either CPU and/or memory).
21718
21719 To do so, start your program using gdbserver on the target machine.
21720 gdbserver then automatically suspends the execution of your program
21721 at its entry point, waiting for a debugger to connect to it. The
21722 following commands starts an application and tells gdbserver to
21723 wait for a connection with the debugger on localhost port 4444.
21724
21725 @smallexample
21726 $ gdbserver localhost:4444 program
21727 Process program created; pid = 5685
21728 Listening on port 4444
21729 @end smallexample
21730
21731 Once gdbserver has started listening, we can tell the debugger to establish
21732 a connection with this gdbserver, and then start the same debugging session
21733 as if the program was being debugged on the same host, directly under
21734 the control of GDB.
21735
21736 @smallexample
21737 $ gdb program
21738 (gdb) target remote targethost:4444
21739 Remote debugging using targethost:4444
21740 0x00007f29936d0af0 in ?? () from /lib64/ld-linux-x86-64.so.
21741 (gdb) b foo.adb:3
21742 Breakpoint 1 at 0x401f0c: file foo.adb, line 3.
21743 (gdb) continue
21744 Continuing.
21745
21746 Breakpoint 1, foo () at foo.adb:4
21747 4 end foo;
21748 @end smallexample
21749
21750 It is also possible to use gdbserver to attach to an already running
21751 program, in which case the execution of that program is simply suspended
21752 until the connection between the debugger and gdbserver is established.
21753
21754 For more information on how to use gdbserver, @ref{Top, Server, Using
21755 the gdbserver Program, gdb, Debugging with GDB}. @value{EDITION} provides support
21756 for gdbserver on x86-linux, x86-windows and x86_64-linux.
21757
21758 @node GNAT Abnormal Termination or Failure to Terminate
21759 @section GNAT Abnormal Termination or Failure to Terminate
21760 @cindex GNAT Abnormal Termination or Failure to Terminate
21761
21762 @noindent
21763 When presented with programs that contain serious errors in syntax
21764 or semantics,
21765 GNAT may on rare occasions experience problems in operation, such
21766 as aborting with a
21767 segmentation fault or illegal memory access, raising an internal
21768 exception, terminating abnormally, or failing to terminate at all.
21769 In such cases, you can activate
21770 various features of GNAT that can help you pinpoint the construct in your
21771 program that is the likely source of the problem.
21772
21773 The following strategies are presented in increasing order of
21774 difficulty, corresponding to your experience in using GNAT and your
21775 familiarity with compiler internals.
21776
21777 @enumerate
21778 @item
21779 Run @command{gcc} with the @option{-gnatf}. This first
21780 switch causes all errors on a given line to be reported. In its absence,
21781 only the first error on a line is displayed.
21782
21783 The @option{-gnatdO} switch causes errors to be displayed as soon as they
21784 are encountered, rather than after compilation is terminated. If GNAT
21785 terminates prematurely or goes into an infinite loop, the last error
21786 message displayed may help to pinpoint the culprit.
21787
21788 @item
21789 Run @command{gcc} with the @option{^-v (verbose)^/VERBOSE^} switch. In this
21790 mode, @command{gcc} produces ongoing information about the progress of the
21791 compilation and provides the name of each procedure as code is
21792 generated. This switch allows you to find which Ada procedure was being
21793 compiled when it encountered a code generation problem.
21794
21795 @item
21796 @cindex @option{-gnatdc} switch
21797 Run @command{gcc} with the @option{-gnatdc} switch. This is a GNAT specific
21798 switch that does for the front-end what @option{^-v^VERBOSE^} does
21799 for the back end. The system prints the name of each unit,
21800 either a compilation unit or nested unit, as it is being analyzed.
21801 @item
21802 Finally, you can start
21803 @code{gdb} directly on the @code{gnat1} executable. @code{gnat1} is the
21804 front-end of GNAT, and can be run independently (normally it is just
21805 called from @command{gcc}). You can use @code{gdb} on @code{gnat1} as you
21806 would on a C program (but @pxref{The GNAT Debugger GDB} for caveats). The
21807 @code{where} command is the first line of attack; the variable
21808 @code{lineno} (seen by @code{print lineno}), used by the second phase of
21809 @code{gnat1} and by the @command{gcc} backend, indicates the source line at
21810 which the execution stopped, and @code{input_file name} indicates the name of
21811 the source file.
21812 @end enumerate
21813
21814 @node Naming Conventions for GNAT Source Files
21815 @section Naming Conventions for GNAT Source Files
21816
21817 @noindent
21818 In order to examine the workings of the GNAT system, the following
21819 brief description of its organization may be helpful:
21820
21821 @itemize @bullet
21822 @item
21823 Files with prefix @file{^sc^SC^} contain the lexical scanner.
21824
21825 @item
21826 All files prefixed with @file{^par^PAR^} are components of the parser. The
21827 numbers correspond to chapters of the Ada Reference Manual. For example,
21828 parsing of select statements can be found in @file{par-ch9.adb}.
21829
21830 @item
21831 All files prefixed with @file{^sem^SEM^} perform semantic analysis. The
21832 numbers correspond to chapters of the Ada standard. For example, all
21833 issues involving context clauses can be found in @file{sem_ch10.adb}. In
21834 addition, some features of the language require sufficient special processing
21835 to justify their own semantic files: sem_aggr for aggregates, sem_disp for
21836 dynamic dispatching, etc.
21837
21838 @item
21839 All files prefixed with @file{^exp^EXP^} perform normalization and
21840 expansion of the intermediate representation (abstract syntax tree, or AST).
21841 these files use the same numbering scheme as the parser and semantics files.
21842 For example, the construction of record initialization procedures is done in
21843 @file{exp_ch3.adb}.
21844
21845 @item
21846 The files prefixed with @file{^bind^BIND^} implement the binder, which
21847 verifies the consistency of the compilation, determines an order of
21848 elaboration, and generates the bind file.
21849
21850 @item
21851 The files @file{atree.ads} and @file{atree.adb} detail the low-level
21852 data structures used by the front-end.
21853
21854 @item
21855 The files @file{sinfo.ads} and @file{sinfo.adb} detail the structure of
21856 the abstract syntax tree as produced by the parser.
21857
21858 @item
21859 The files @file{einfo.ads} and @file{einfo.adb} detail the attributes of
21860 all entities, computed during semantic analysis.
21861
21862 @item
21863 Library management issues are dealt with in files with prefix
21864 @file{^lib^LIB^}.
21865
21866 @item
21867 @findex Ada
21868 @cindex Annex A
21869 Ada files with the prefix @file{^a-^A-^} are children of @code{Ada}, as
21870 defined in Annex A.
21871
21872 @item
21873 @findex Interfaces
21874 @cindex Annex B
21875 Files with prefix @file{^i-^I-^} are children of @code{Interfaces}, as
21876 defined in Annex B.
21877
21878 @item
21879 @findex System
21880 Files with prefix @file{^s-^S-^} are children of @code{System}. This includes
21881 both language-defined children and GNAT run-time routines.
21882
21883 @item
21884 @findex GNAT
21885 Files with prefix @file{^g-^G-^} are children of @code{GNAT}. These are useful
21886 general-purpose packages, fully documented in their specs. All
21887 the other @file{.c} files are modifications of common @command{gcc} files.
21888 @end itemize
21889
21890 @node Getting Internal Debugging Information
21891 @section Getting Internal Debugging Information
21892
21893 @noindent
21894 Most compilers have internal debugging switches and modes. GNAT
21895 does also, except GNAT internal debugging switches and modes are not
21896 secret. A summary and full description of all the compiler and binder
21897 debug flags are in the file @file{debug.adb}. You must obtain the
21898 sources of the compiler to see the full detailed effects of these flags.
21899
21900 The switches that print the source of the program (reconstructed from
21901 the internal tree) are of general interest for user programs, as are the
21902 options to print
21903 the full internal tree, and the entity table (the symbol table
21904 information). The reconstructed source provides a readable version of the
21905 program after the front-end has completed analysis and expansion,
21906 and is useful when studying the performance of specific constructs.
21907 For example, constraint checks are indicated, complex aggregates
21908 are replaced with loops and assignments, and tasking primitives
21909 are replaced with run-time calls.
21910
21911 @node Stack Traceback
21912 @section Stack Traceback
21913 @cindex traceback
21914 @cindex stack traceback
21915 @cindex stack unwinding
21916
21917 @noindent
21918 Traceback is a mechanism to display the sequence of subprogram calls that
21919 leads to a specified execution point in a program. Often (but not always)
21920 the execution point is an instruction at which an exception has been raised.
21921 This mechanism is also known as @i{stack unwinding} because it obtains
21922 its information by scanning the run-time stack and recovering the activation
21923 records of all active subprograms. Stack unwinding is one of the most
21924 important tools for program debugging.
21925
21926 The first entry stored in traceback corresponds to the deepest calling level,
21927 that is to say the subprogram currently executing the instruction
21928 from which we want to obtain the traceback.
21929
21930 Note that there is no runtime performance penalty when stack traceback
21931 is enabled, and no exception is raised during program execution.
21932
21933 @menu
21934 * Non-Symbolic Traceback::
21935 * Symbolic Traceback::
21936 @end menu
21937
21938 @node Non-Symbolic Traceback
21939 @subsection Non-Symbolic Traceback
21940 @cindex traceback, non-symbolic
21941
21942 @noindent
21943 Note: this feature is not supported on all platforms. See
21944 @file{GNAT.Traceback spec in g-traceb.ads} for a complete list of supported
21945 platforms.
21946
21947 @menu
21948 * Tracebacks From an Unhandled Exception::
21949 * Tracebacks From Exception Occurrences (non-symbolic)::
21950 * Tracebacks From Anywhere in a Program (non-symbolic)::
21951 @end menu
21952
21953 @node Tracebacks From an Unhandled Exception
21954 @subsubsection Tracebacks From an Unhandled Exception
21955
21956 @noindent
21957 A runtime non-symbolic traceback is a list of addresses of call instructions.
21958 To enable this feature you must use the @option{-E}
21959 @code{gnatbind}'s option. With this option a stack traceback is stored as part
21960 of exception information. You can retrieve this information using the
21961 @code{addr2line} tool.
21962
21963 Here is a simple example:
21964
21965 @smallexample @c ada
21966 @cartouche
21967 procedure STB is
21968
21969 procedure P1 is
21970 begin
21971 raise Constraint_Error;
21972 end P1;
21973
21974 procedure P2 is
21975 begin
21976 P1;
21977 end P2;
21978
21979 begin
21980 P2;
21981 end STB;
21982 @end cartouche
21983 @end smallexample
21984
21985 @smallexample
21986 $ gnatmake stb -bargs -E
21987 $ stb
21988
21989 Execution terminated by unhandled exception
21990 Exception name: CONSTRAINT_ERROR
21991 Message: stb.adb:5
21992 Call stack traceback locations:
21993 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
21994 @end smallexample
21995
21996 @noindent
21997 As we see the traceback lists a sequence of addresses for the unhandled
21998 exception @code{CONSTRAINT_ERROR} raised in procedure P1. It is easy to
21999 guess that this exception come from procedure P1. To translate these
22000 addresses into the source lines where the calls appear, the
22001 @code{addr2line} tool, described below, is invaluable. The use of this tool
22002 requires the program to be compiled with debug information.
22003
22004 @smallexample
22005 $ gnatmake -g stb -bargs -E
22006 $ stb
22007
22008 Execution terminated by unhandled exception
22009 Exception name: CONSTRAINT_ERROR
22010 Message: stb.adb:5
22011 Call stack traceback locations:
22012 0x401373 0x40138b 0x40139c 0x401335 0x4011c4 0x4011f1 0x77e892a4
22013
22014 $ addr2line --exe=stb 0x401373 0x40138b 0x40139c 0x401335 0x4011c4
22015 0x4011f1 0x77e892a4
22016
22017 00401373 at d:/stb/stb.adb:5
22018 0040138B at d:/stb/stb.adb:10
22019 0040139C at d:/stb/stb.adb:14
22020 00401335 at d:/stb/b~stb.adb:104
22021 004011C4 at /build/@dots{}/crt1.c:200
22022 004011F1 at /build/@dots{}/crt1.c:222
22023 77E892A4 in ?? at ??:0
22024 @end smallexample
22025
22026 @noindent
22027 The @code{addr2line} tool has several other useful options:
22028
22029 @table @code
22030 @item --functions
22031 to get the function name corresponding to any location
22032
22033 @item --demangle=gnat
22034 to use the gnat decoding mode for the function names. Note that
22035 for binutils version 2.9.x the option is simply @option{--demangle}.
22036 @end table
22037
22038 @smallexample
22039 $ addr2line --exe=stb --functions --demangle=gnat 0x401373 0x40138b
22040 0x40139c 0x401335 0x4011c4 0x4011f1
22041
22042 00401373 in stb.p1 at d:/stb/stb.adb:5
22043 0040138B in stb.p2 at d:/stb/stb.adb:10
22044 0040139C in stb at d:/stb/stb.adb:14
22045 00401335 in main at d:/stb/b~stb.adb:104
22046 004011C4 in <__mingw_CRTStartup> at /build/@dots{}/crt1.c:200
22047 004011F1 in <mainCRTStartup> at /build/@dots{}/crt1.c:222
22048 @end smallexample
22049
22050 @noindent
22051 From this traceback we can see that the exception was raised in
22052 @file{stb.adb} at line 5, which was reached from a procedure call in
22053 @file{stb.adb} at line 10, and so on. The @file{b~std.adb} is the binder file,
22054 which contains the call to the main program.
22055 @xref{Running gnatbind}. The remaining entries are assorted runtime routines,
22056 and the output will vary from platform to platform.
22057
22058 It is also possible to use @code{GDB} with these traceback addresses to debug
22059 the program. For example, we can break at a given code location, as reported
22060 in the stack traceback:
22061
22062 @smallexample
22063 $ gdb -nw stb
22064 @ifclear vms
22065 @noindent
22066 Furthermore, this feature is not implemented inside Windows DLL. Only
22067 the non-symbolic traceback is reported in this case.
22068 @end ifclear
22069
22070 (gdb) break *0x401373
22071 Breakpoint 1 at 0x401373: file stb.adb, line 5.
22072 @end smallexample
22073
22074 @noindent
22075 It is important to note that the stack traceback addresses
22076 do not change when debug information is included. This is particularly useful
22077 because it makes it possible to release software without debug information (to
22078 minimize object size), get a field report that includes a stack traceback
22079 whenever an internal bug occurs, and then be able to retrieve the sequence
22080 of calls with the same program compiled with debug information.
22081
22082 @node Tracebacks From Exception Occurrences (non-symbolic)
22083 @subsubsection Tracebacks From Exception Occurrences
22084
22085 @noindent
22086 Non-symbolic tracebacks are obtained by using the @option{-E} binder argument.
22087 The stack traceback is attached to the exception information string, and can
22088 be retrieved in an exception handler within the Ada program, by means of the
22089 Ada facilities defined in @code{Ada.Exceptions}. Here is a simple example:
22090
22091 @smallexample @c ada
22092 with Ada.Text_IO;
22093 with Ada.Exceptions;
22094
22095 procedure STB is
22096
22097 use Ada;
22098 use Ada.Exceptions;
22099
22100 procedure P1 is
22101 K : Positive := 1;
22102 begin
22103 K := K - 1;
22104 exception
22105 when E : others =>
22106 Text_IO.Put_Line (Exception_Information (E));
22107 end P1;
22108
22109 procedure P2 is
22110 begin
22111 P1;
22112 end P2;
22113
22114 begin
22115 P2;
22116 end STB;
22117 @end smallexample
22118
22119 @noindent
22120 This program will output:
22121
22122 @smallexample
22123 $ stb
22124
22125 Exception name: CONSTRAINT_ERROR
22126 Message: stb.adb:12
22127 Call stack traceback locations:
22128 0x4015e4 0x401633 0x401644 0x401461 0x4011c4 0x4011f1 0x77e892a4
22129 @end smallexample
22130
22131 @node Tracebacks From Anywhere in a Program (non-symbolic)
22132 @subsubsection Tracebacks From Anywhere in a Program
22133
22134 @noindent
22135 It is also possible to retrieve a stack traceback from anywhere in a
22136 program. For this you need to
22137 use the @code{GNAT.Traceback} API. This package includes a procedure called
22138 @code{Call_Chain} that computes a complete stack traceback, as well as useful
22139 display procedures described below. It is not necessary to use the
22140 @option{-E gnatbind} option in this case, because the stack traceback mechanism
22141 is invoked explicitly.
22142
22143 @noindent
22144 In the following example we compute a traceback at a specific location in
22145 the program, and we display it using @code{GNAT.Debug_Utilities.Image} to
22146 convert addresses to strings:
22147
22148 @smallexample @c ada
22149 with Ada.Text_IO;
22150 with GNAT.Traceback;
22151 with GNAT.Debug_Utilities;
22152
22153 procedure STB is
22154
22155 use Ada;
22156 use GNAT;
22157 use GNAT.Traceback;
22158
22159 procedure P1 is
22160 TB : Tracebacks_Array (1 .. 10);
22161 -- We are asking for a maximum of 10 stack frames.
22162 Len : Natural;
22163 -- Len will receive the actual number of stack frames returned.
22164 begin
22165 Call_Chain (TB, Len);
22166
22167 Text_IO.Put ("In STB.P1 : ");
22168
22169 for K in 1 .. Len loop
22170 Text_IO.Put (Debug_Utilities.Image (TB (K)));
22171 Text_IO.Put (' ');
22172 end loop;
22173
22174 Text_IO.New_Line;
22175 end P1;
22176
22177 procedure P2 is
22178 begin
22179 P1;
22180 end P2;
22181
22182 begin
22183 P2;
22184 end STB;
22185 @end smallexample
22186
22187 @smallexample
22188 $ gnatmake -g stb
22189 $ stb
22190
22191 In STB.P1 : 16#0040_F1E4# 16#0040_14F2# 16#0040_170B# 16#0040_171C#
22192 16#0040_1461# 16#0040_11C4# 16#0040_11F1# 16#77E8_92A4#
22193 @end smallexample
22194
22195 @noindent
22196 You can then get further information by invoking the @code{addr2line}
22197 tool as described earlier (note that the hexadecimal addresses
22198 need to be specified in C format, with a leading ``0x'').
22199
22200 @node Symbolic Traceback
22201 @subsection Symbolic Traceback
22202 @cindex traceback, symbolic
22203
22204 @noindent
22205 A symbolic traceback is a stack traceback in which procedure names are
22206 associated with each code location.
22207
22208 @noindent
22209 Note that this feature is not supported on all platforms. See
22210 @file{GNAT.Traceback.Symbolic spec in g-trasym.ads} for a complete
22211 list of currently supported platforms.
22212
22213 @noindent
22214 Note that the symbolic traceback requires that the program be compiled
22215 with debug information. If it is not compiled with debug information
22216 only the non-symbolic information will be valid.
22217
22218 @menu
22219 * Tracebacks From Exception Occurrences (symbolic)::
22220 * Tracebacks From Anywhere in a Program (symbolic)::
22221 @end menu
22222
22223 @node Tracebacks From Exception Occurrences (symbolic)
22224 @subsubsection Tracebacks From Exception Occurrences
22225
22226 @smallexample @c ada
22227 with Ada.Text_IO;
22228 with GNAT.Traceback.Symbolic;
22229
22230 procedure STB is
22231
22232 procedure P1 is
22233 begin
22234 raise Constraint_Error;
22235 end P1;
22236
22237 procedure P2 is
22238 begin
22239 P1;
22240 end P2;
22241
22242 procedure P3 is
22243 begin
22244 P2;
22245 end P3;
22246
22247 begin
22248 P3;
22249 exception
22250 when E : others =>
22251 Ada.Text_IO.Put_Line (GNAT.Traceback.Symbolic.Symbolic_Traceback (E));
22252 end STB;
22253 @end smallexample
22254
22255 @smallexample
22256 $ gnatmake -g .\stb -bargs -E
22257 $ stb
22258
22259 0040149F in stb.p1 at stb.adb:8
22260 004014B7 in stb.p2 at stb.adb:13
22261 004014CF in stb.p3 at stb.adb:18
22262 004015DD in ada.stb at stb.adb:22
22263 00401461 in main at b~stb.adb:168
22264 004011C4 in __mingw_CRTStartup at crt1.c:200
22265 004011F1 in mainCRTStartup at crt1.c:222
22266 77E892A4 in ?? at ??:0
22267 @end smallexample
22268
22269 @noindent
22270 In the above example the ``.\'' syntax in the @command{gnatmake} command
22271 is currently required by @command{addr2line} for files that are in
22272 the current working directory.
22273 Moreover, the exact sequence of linker options may vary from platform
22274 to platform.
22275 The above @option{-largs} section is for Windows platforms. By contrast,
22276 under Unix there is no need for the @option{-largs} section.
22277 Differences across platforms are due to details of linker implementation.
22278
22279 @node Tracebacks From Anywhere in a Program (symbolic)
22280 @subsubsection Tracebacks From Anywhere in a Program
22281
22282 @noindent
22283 It is possible to get a symbolic stack traceback
22284 from anywhere in a program, just as for non-symbolic tracebacks.
22285 The first step is to obtain a non-symbolic
22286 traceback, and then call @code{Symbolic_Traceback} to compute the symbolic
22287 information. Here is an example:
22288
22289 @smallexample @c ada
22290 with Ada.Text_IO;
22291 with GNAT.Traceback;
22292 with GNAT.Traceback.Symbolic;
22293
22294 procedure STB is
22295
22296 use Ada;
22297 use GNAT.Traceback;
22298 use GNAT.Traceback.Symbolic;
22299
22300 procedure P1 is
22301 TB : Tracebacks_Array (1 .. 10);
22302 -- We are asking for a maximum of 10 stack frames.
22303 Len : Natural;
22304 -- Len will receive the actual number of stack frames returned.
22305 begin
22306 Call_Chain (TB, Len);
22307 Text_IO.Put_Line (Symbolic_Traceback (TB (1 .. Len)));
22308 end P1;
22309
22310 procedure P2 is
22311 begin
22312 P1;
22313 end P2;
22314
22315 begin
22316 P2;
22317 end STB;
22318 @end smallexample
22319
22320 @c ******************************
22321 @ifset vms
22322 @node Compatibility with HP Ada
22323 @chapter Compatibility with HP Ada
22324 @cindex Compatibility
22325
22326 @noindent
22327 @cindex DEC Ada
22328 @cindex HP Ada
22329 @cindex Compatibility between GNAT and HP Ada
22330 This chapter compares HP Ada (formerly known as ``DEC Ada'')
22331 for OpenVMS Alpha and GNAT for OpenVMS for Alpha and for I64.
22332 GNAT is highly compatible
22333 with HP Ada, and it should generally be straightforward to port code
22334 from the HP Ada environment to GNAT. However, there are a few language
22335 and implementation differences of which the user must be aware. These
22336 differences are discussed in this chapter. In
22337 addition, the operating environment and command structure for the
22338 compiler are different, and these differences are also discussed.
22339
22340 For further details on these and other compatibility issues,
22341 see Appendix E of the HP publication
22342 @cite{HP Ada, Technical Overview and Comparison on HP Platforms}.
22343
22344 Except where otherwise indicated, the description of GNAT for OpenVMS
22345 applies to both the Alpha and I64 platforms.
22346
22347 For information on porting Ada code from GNAT on Alpha OpenVMS to GNAT on
22348 I64 OpenVMS, see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22349
22350 The discussion in this chapter addresses specifically the implementation
22351 of Ada 83 for HP OpenVMS Alpha Systems. In cases where the implementation
22352 of HP Ada differs between OpenVMS Alpha Systems and OpenVMS VAX Systems,
22353 GNAT always follows the Alpha implementation.
22354
22355 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
22356 attributes are recognized, although only a subset of them can sensibly
22357 be implemented. The description of pragmas in
22358 @xref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference Manual},
22359 indicates whether or not they are applicable to non-VMS systems.
22360
22361 @menu
22362 * Ada Language Compatibility::
22363 * Differences in the Definition of Package System::
22364 * Language-Related Features::
22365 * The Package STANDARD::
22366 * The Package SYSTEM::
22367 * Tasking and Task-Related Features::
22368 * Pragmas and Pragma-Related Features::
22369 * Library of Predefined Units::
22370 * Bindings::
22371 * Main Program Definition::
22372 * Implementation-Defined Attributes::
22373 * Compiler and Run-Time Interfacing::
22374 * Program Compilation and Library Management::
22375 * Input-Output::
22376 * Implementation Limits::
22377 * Tools and Utilities::
22378 @end menu
22379
22380 @node Ada Language Compatibility
22381 @section Ada Language Compatibility
22382
22383 @noindent
22384 GNAT handles Ada 95 and Ada 2005 as well as Ada 83, whereas HP Ada is only
22385 for Ada 83. Ada 95 and Ada 2005 are almost completely upwards compatible
22386 with Ada 83, and therefore Ada 83 programs will compile
22387 and run under GNAT with
22388 no changes or only minor changes. The @cite{Annotated Ada Reference Manual}
22389 provides details on specific incompatibilities.
22390
22391 GNAT provides the switch @option{/83} on the @command{GNAT COMPILE} command,
22392 as well as the pragma @code{ADA_83}, to force the compiler to
22393 operate in Ada 83 mode. This mode does not guarantee complete
22394 conformance to Ada 83, but in practice is sufficient to
22395 eliminate most sources of incompatibilities.
22396 In particular, it eliminates the recognition of the
22397 additional Ada 95 and Ada 2005 keywords, so that their use as identifiers
22398 in Ada 83 programs is legal, and handles the cases of packages
22399 with optional bodies, and generics that instantiate unconstrained
22400 types without the use of @code{(<>)}.
22401
22402 @node Differences in the Definition of Package System
22403 @section Differences in the Definition of Package @code{System}
22404
22405 @noindent
22406 An Ada compiler is allowed to add
22407 implementation-dependent declarations to package @code{System}.
22408 In normal mode,
22409 GNAT does not take advantage of this permission, and the version of
22410 @code{System} provided by GNAT exactly matches that defined in the Ada
22411 Reference Manual.
22412
22413 However, HP Ada adds an extensive set of declarations to package
22414 @code{System},
22415 as fully documented in the HP Ada manuals. To minimize changes required
22416 for programs that make use of these extensions, GNAT provides the pragma
22417 @code{Extend_System} for extending the definition of package System. By using:
22418 @cindex pragma @code{Extend_System}
22419 @cindex @code{Extend_System} pragma
22420
22421 @smallexample @c ada
22422 @group
22423 @cartouche
22424 pragma Extend_System (Aux_DEC);
22425 @end cartouche
22426 @end group
22427 @end smallexample
22428
22429 @noindent
22430 the set of definitions in @code{System} is extended to include those in
22431 package @code{System.Aux_DEC}.
22432 @cindex @code{System.Aux_DEC} package
22433 @cindex @code{Aux_DEC} package (child of @code{System})
22434 These definitions are incorporated directly into package @code{System},
22435 as though they had been declared there. For a
22436 list of the declarations added, see the spec of this package,
22437 which can be found in the file @file{s-auxdec.ads} in the GNAT library.
22438 @cindex @file{s-auxdec.ads} file
22439 The pragma @code{Extend_System} is a configuration pragma, which means that
22440 it can be placed in the file @file{gnat.adc}, so that it will automatically
22441 apply to all subsequent compilations. See @ref{Configuration Pragmas},
22442 for further details.
22443
22444 An alternative approach that avoids the use of the non-standard
22445 @code{Extend_System} pragma is to add a context clause to the unit that
22446 references these facilities:
22447
22448 @smallexample @c ada
22449 @cartouche
22450 with System.Aux_DEC;
22451 use System.Aux_DEC;
22452 @end cartouche
22453 @end smallexample
22454
22455 @noindent
22456 The effect is not quite semantically identical to incorporating
22457 the declarations directly into package @code{System},
22458 but most programs will not notice a difference
22459 unless they use prefix notation (e.g.@: @code{System.Integer_8})
22460 to reference the entities directly in package @code{System}.
22461 For units containing such references,
22462 the prefixes must either be removed, or the pragma @code{Extend_System}
22463 must be used.
22464
22465 @node Language-Related Features
22466 @section Language-Related Features
22467
22468 @noindent
22469 The following sections highlight differences in types,
22470 representations of types, operations, alignment, and
22471 related topics.
22472
22473 @menu
22474 * Integer Types and Representations::
22475 * Floating-Point Types and Representations::
22476 * Pragmas Float_Representation and Long_Float::
22477 * Fixed-Point Types and Representations::
22478 * Record and Array Component Alignment::
22479 * Address Clauses::
22480 * Other Representation Clauses::
22481 @end menu
22482
22483 @node Integer Types and Representations
22484 @subsection Integer Types and Representations
22485
22486 @noindent
22487 The set of predefined integer types is identical in HP Ada and GNAT.
22488 Furthermore the representation of these integer types is also identical,
22489 including the capability of size clauses forcing biased representation.
22490
22491 In addition,
22492 HP Ada for OpenVMS Alpha systems has defined the
22493 following additional integer types in package @code{System}:
22494
22495 @itemize @bullet
22496
22497 @item
22498 @code{INTEGER_8}
22499
22500 @item
22501 @code{INTEGER_16}
22502
22503 @item
22504 @code{INTEGER_32}
22505
22506 @item
22507 @code{INTEGER_64}
22508
22509 @item
22510 @code{LARGEST_INTEGER}
22511 @end itemize
22512
22513 @noindent
22514 In GNAT, the first four of these types may be obtained from the
22515 standard Ada package @code{Interfaces}.
22516 Alternatively, by use of the pragma @code{Extend_System}, identical
22517 declarations can be referenced directly in package @code{System}.
22518 On both GNAT and HP Ada, the maximum integer size is 64 bits.
22519
22520 @node Floating-Point Types and Representations
22521 @subsection Floating-Point Types and Representations
22522 @cindex Floating-Point types
22523
22524 @noindent
22525 The set of predefined floating-point types is identical in HP Ada and GNAT.
22526 Furthermore the representation of these floating-point
22527 types is also identical. One important difference is that the default
22528 representation for HP Ada is @code{VAX_Float}, but the default representation
22529 for GNAT is IEEE.
22530
22531 Specific types may be declared to be @code{VAX_Float} or IEEE, using the
22532 pragma @code{Float_Representation} as described in the HP Ada
22533 documentation.
22534 For example, the declarations:
22535
22536 @smallexample @c ada
22537 @cartouche
22538 type F_Float is digits 6;
22539 pragma Float_Representation (VAX_Float, F_Float);
22540 @end cartouche
22541 @end smallexample
22542
22543 @noindent
22544 declares a type @code{F_Float} that will be represented in @code{VAX_Float}
22545 format.
22546 This set of declarations actually appears in @code{System.Aux_DEC},
22547 which contains
22548 the full set of additional floating-point declarations provided in
22549 the HP Ada version of package @code{System}.
22550 This and similar declarations may be accessed in a user program
22551 by using pragma @code{Extend_System}. The use of this
22552 pragma, and the related pragma @code{Long_Float} is described in further
22553 detail in the following section.
22554
22555 @node Pragmas Float_Representation and Long_Float
22556 @subsection Pragmas @code{Float_Representation} and @code{Long_Float}
22557
22558 @noindent
22559 HP Ada provides the pragma @code{Float_Representation}, which
22560 acts as a program library switch to allow control over
22561 the internal representation chosen for the predefined
22562 floating-point types declared in the package @code{Standard}.
22563 The format of this pragma is as follows:
22564
22565 @smallexample @c ada
22566 @cartouche
22567 pragma Float_Representation(VAX_Float | IEEE_Float);
22568 @end cartouche
22569 @end smallexample
22570
22571 @noindent
22572 This pragma controls the representation of floating-point
22573 types as follows:
22574
22575 @itemize @bullet
22576 @item
22577 @code{VAX_Float} specifies that floating-point
22578 types are represented by default with the VAX system hardware types
22579 @code{F-floating}, @code{D-floating}, @code{G-floating}.
22580 Note that the @code{H-floating}
22581 type was available only on VAX systems, and is not available
22582 in either HP Ada or GNAT.
22583
22584 @item
22585 @code{IEEE_Float} specifies that floating-point
22586 types are represented by default with the IEEE single and
22587 double floating-point types.
22588 @end itemize
22589
22590 @noindent
22591 GNAT provides an identical implementation of the pragma
22592 @code{Float_Representation}, except that it functions as a
22593 configuration pragma. Note that the
22594 notion of configuration pragma corresponds closely to the
22595 HP Ada notion of a program library switch.
22596
22597 When no pragma is used in GNAT, the default is @code{IEEE_Float},
22598 which is different
22599 from HP Ada 83, where the default is @code{VAX_Float}. In addition, the
22600 predefined libraries in GNAT are built using @code{IEEE_Float}, so it is not
22601 advisable to change the format of numbers passed to standard library
22602 routines, and if necessary explicit type conversions may be needed.
22603
22604 The use of @code{IEEE_Float} is recommended in GNAT since it is more
22605 efficient, and (given that it conforms to an international standard)
22606 potentially more portable.
22607 The situation in which @code{VAX_Float} may be useful is in interfacing
22608 to existing code and data that expect the use of @code{VAX_Float}.
22609 In such a situation use the predefined @code{VAX_Float}
22610 types in package @code{System}, as extended by
22611 @code{Extend_System}. For example, use @code{System.F_Float}
22612 to specify the 32-bit @code{F-Float} format.
22613
22614 @noindent
22615 On OpenVMS systems, HP Ada provides the pragma @code{Long_Float}
22616 to allow control over the internal representation chosen
22617 for the predefined type @code{Long_Float} and for floating-point
22618 type declarations with digits specified in the range 7 .. 15.
22619 The format of this pragma is as follows:
22620
22621 @smallexample @c ada
22622 @cartouche
22623 pragma Long_Float (D_FLOAT | G_FLOAT);
22624 @end cartouche
22625 @end smallexample
22626
22627 @node Fixed-Point Types and Representations
22628 @subsection Fixed-Point Types and Representations
22629
22630 @noindent
22631 On HP Ada for OpenVMS Alpha systems, rounding is
22632 away from zero for both positive and negative numbers.
22633 Therefore, @code{+0.5} rounds to @code{1},
22634 and @code{-0.5} rounds to @code{-1}.
22635
22636 On GNAT the results of operations
22637 on fixed-point types are in accordance with the Ada
22638 rules. In particular, results of operations on decimal
22639 fixed-point types are truncated.
22640
22641 @node Record and Array Component Alignment
22642 @subsection Record and Array Component Alignment
22643
22644 @noindent
22645 On HP Ada for OpenVMS Alpha, all non-composite components
22646 are aligned on natural boundaries. For example, 1-byte
22647 components are aligned on byte boundaries, 2-byte
22648 components on 2-byte boundaries, 4-byte components on 4-byte
22649 byte boundaries, and so on. The OpenVMS Alpha hardware
22650 runs more efficiently with naturally aligned data.
22651
22652 On GNAT, alignment rules are compatible
22653 with HP Ada for OpenVMS Alpha.
22654
22655 @node Address Clauses
22656 @subsection Address Clauses
22657
22658 @noindent
22659 In HP Ada and GNAT, address clauses are supported for
22660 objects and imported subprograms.
22661 The predefined type @code{System.Address} is a private type
22662 in both compilers on Alpha OpenVMS, with the same representation
22663 (it is simply a machine pointer). Addition, subtraction, and comparison
22664 operations are available in the standard Ada package
22665 @code{System.Storage_Elements}, or in package @code{System}
22666 if it is extended to include @code{System.Aux_DEC} using a
22667 pragma @code{Extend_System} as previously described.
22668
22669 Note that code that @code{with}'s both this extended package @code{System}
22670 and the package @code{System.Storage_Elements} should not @code{use}
22671 both packages, or ambiguities will result. In general it is better
22672 not to mix these two sets of facilities. The Ada package was
22673 designed specifically to provide the kind of features that HP Ada
22674 adds directly to package @code{System}.
22675
22676 The type @code{System.Address} is a 64-bit integer type in GNAT for
22677 I64 OpenVMS. For more information,
22678 see @ref{Transitioning to 64-Bit GNAT for OpenVMS}.
22679
22680 GNAT is compatible with HP Ada in its handling of address
22681 clauses, except for some limitations in
22682 the form of address clauses for composite objects with
22683 initialization. Such address clauses are easily replaced
22684 by the use of an explicitly-defined constant as described
22685 in the Ada Reference Manual (13.1(22)). For example, the sequence
22686 of declarations:
22687
22688 @smallexample @c ada
22689 @cartouche
22690 X, Y : Integer := Init_Func;
22691 Q : String (X .. Y) := "abc";
22692 @dots{}
22693 for Q'Address use Compute_Address;
22694 @end cartouche
22695 @end smallexample
22696
22697 @noindent
22698 will be rejected by GNAT, since the address cannot be computed at the time
22699 that @code{Q} is declared. To achieve the intended effect, write instead:
22700
22701 @smallexample @c ada
22702 @group
22703 @cartouche
22704 X, Y : Integer := Init_Func;
22705 Q_Address : constant Address := Compute_Address;
22706 Q : String (X .. Y) := "abc";
22707 @dots{}
22708 for Q'Address use Q_Address;
22709 @end cartouche
22710 @end group
22711 @end smallexample
22712
22713 @noindent
22714 which will be accepted by GNAT (and other Ada compilers), and is also
22715 compatible with Ada 83. A fuller description of the restrictions
22716 on address specifications is found in @ref{Top, GNAT Reference Manual,
22717 About This Guide, gnat_rm, GNAT Reference Manual}.
22718
22719 @node Other Representation Clauses
22720 @subsection Other Representation Clauses
22721
22722 @noindent
22723 GNAT implements in a compatible manner all the representation
22724 clauses supported by HP Ada. In addition, GNAT
22725 implements the representation clause forms that were introduced in Ada 95,
22726 including @code{COMPONENT_SIZE} and @code{SIZE} clauses for objects.
22727
22728 @node The Package STANDARD
22729 @section The Package @code{STANDARD}
22730
22731 @noindent
22732 The package @code{STANDARD}, as implemented by HP Ada, is fully
22733 described in the @cite{Ada Reference Manual} and in the
22734 @cite{HP Ada Language Reference Manual}. As implemented by GNAT, the
22735 package @code{STANDARD} is described in the @cite{Ada Reference Manual}.
22736
22737 In addition, HP Ada supports the Latin-1 character set in
22738 the type @code{CHARACTER}. GNAT supports the Latin-1 character set
22739 in the type @code{CHARACTER} and also Unicode (ISO 10646 BMP) in
22740 the type @code{WIDE_CHARACTER}.
22741
22742 The floating-point types supported by GNAT are those
22743 supported by HP Ada, but the defaults are different, and are controlled by
22744 pragmas. See @ref{Floating-Point Types and Representations}, for details.
22745
22746 @node The Package SYSTEM
22747 @section The Package @code{SYSTEM}
22748
22749 @noindent
22750 HP Ada provides a specific version of the package
22751 @code{SYSTEM} for each platform on which the language is implemented.
22752 For the complete spec of the package @code{SYSTEM}, see
22753 Appendix F of the @cite{HP Ada Language Reference Manual}.
22754
22755 On HP Ada, the package @code{SYSTEM} includes the following conversion
22756 functions:
22757 @itemize @bullet
22758 @item @code{TO_ADDRESS(INTEGER)}
22759
22760 @item @code{TO_ADDRESS(UNSIGNED_LONGWORD)}
22761
22762 @item @code{TO_ADDRESS(}@i{universal_integer}@code{)}
22763
22764 @item @code{TO_INTEGER(ADDRESS)}
22765
22766 @item @code{TO_UNSIGNED_LONGWORD(ADDRESS)}
22767
22768 @item Function @code{IMPORT_VALUE return UNSIGNED_LONGWORD} and the
22769 functions @code{IMPORT_ADDRESS} and @code{IMPORT_LARGEST_VALUE}
22770 @end itemize
22771
22772 @noindent
22773 By default, GNAT supplies a version of @code{SYSTEM} that matches
22774 the definition given in the @cite{Ada Reference Manual}.
22775 This
22776 is a subset of the HP system definitions, which is as
22777 close as possible to the original definitions. The only difference
22778 is that the definition of @code{SYSTEM_NAME} is different:
22779
22780 @smallexample @c ada
22781 @cartouche
22782 type Name is (SYSTEM_NAME_GNAT);
22783 System_Name : constant Name := SYSTEM_NAME_GNAT;
22784 @end cartouche
22785 @end smallexample
22786
22787 @noindent
22788 Also, GNAT adds the Ada declarations for
22789 @code{BIT_ORDER} and @code{DEFAULT_BIT_ORDER}.
22790
22791 However, the use of the following pragma causes GNAT
22792 to extend the definition of package @code{SYSTEM} so that it
22793 encompasses the full set of HP-specific extensions,
22794 including the functions listed above:
22795
22796 @smallexample @c ada
22797 @cartouche
22798 pragma Extend_System (Aux_DEC);
22799 @end cartouche
22800 @end smallexample
22801
22802 @noindent
22803 The pragma @code{Extend_System} is a configuration pragma that
22804 is most conveniently placed in the @file{gnat.adc} file. @xref{Pragma
22805 Extend_System,,, gnat_rm, GNAT Reference Manual}, for further details.
22806
22807 HP Ada does not allow the recompilation of the package
22808 @code{SYSTEM}. Instead HP Ada provides several pragmas
22809 (@code{SYSTEM_NAME}, @code{STORAGE_UNIT}, and @code{MEMORY_SIZE})
22810 to modify values in the package @code{SYSTEM}.
22811 On OpenVMS Alpha systems, the pragma
22812 @code{SYSTEM_NAME} takes the enumeration literal @code{OPENVMS_AXP} as
22813 its single argument.
22814
22815 GNAT does permit the recompilation of package @code{SYSTEM} using
22816 the special switch @option{-gnatg}, and this switch can be used if
22817 it is necessary to modify the definitions in @code{SYSTEM}. GNAT does
22818 not permit the specification of @code{SYSTEM_NAME}, @code{STORAGE_UNIT}
22819 or @code{MEMORY_SIZE} by any other means.
22820
22821 On GNAT systems, the pragma @code{SYSTEM_NAME} takes the
22822 enumeration literal @code{SYSTEM_NAME_GNAT}.
22823
22824 The definitions provided by the use of
22825
22826 @smallexample @c ada
22827 pragma Extend_System (AUX_Dec);
22828 @end smallexample
22829
22830 @noindent
22831 are virtually identical to those provided by the HP Ada 83 package
22832 @code{SYSTEM}. One important difference is that the name of the
22833 @code{TO_ADDRESS}
22834 function for type @code{UNSIGNED_LONGWORD} is changed to
22835 @code{TO_ADDRESS_LONG}.
22836 @xref{Address Clauses,,, gnat_rm, GNAT Reference Manual}, for a
22837 discussion of why this change was necessary.
22838
22839 @noindent
22840 The version of @code{TO_ADDRESS} taking a @i{universal_integer} argument
22841 is in fact
22842 an extension to Ada 83 not strictly compatible with the reference manual.
22843 GNAT, in order to be exactly compatible with the standard,
22844 does not provide this capability. In HP Ada 83, the
22845 point of this definition is to deal with a call like:
22846
22847 @smallexample @c ada
22848 TO_ADDRESS (16#12777#);
22849 @end smallexample
22850
22851 @noindent
22852 Normally, according to Ada 83 semantics, one would expect this to be
22853 ambiguous, since it matches both the @code{INTEGER} and
22854 @code{UNSIGNED_LONGWORD} forms of @code{TO_ADDRESS}.
22855 However, in HP Ada 83, there is no ambiguity, since the
22856 definition using @i{universal_integer} takes precedence.
22857
22858 In GNAT, since the version with @i{universal_integer} cannot be supplied,
22859 it is
22860 not possible to be 100% compatible. Since there are many programs using
22861 numeric constants for the argument to @code{TO_ADDRESS}, the decision in
22862 GNAT was
22863 to change the name of the function in the @code{UNSIGNED_LONGWORD} case,
22864 so the declarations provided in the GNAT version of @code{AUX_Dec} are:
22865
22866 @smallexample @c ada
22867 function To_Address (X : Integer) return Address;
22868 pragma Pure_Function (To_Address);
22869
22870 function To_Address_Long (X : Unsigned_Longword) return Address;
22871 pragma Pure_Function (To_Address_Long);
22872 @end smallexample
22873
22874 @noindent
22875 This means that programs using @code{TO_ADDRESS} for
22876 @code{UNSIGNED_LONGWORD} must change the name to @code{TO_ADDRESS_LONG}.
22877
22878 @node Tasking and Task-Related Features
22879 @section Tasking and Task-Related Features
22880
22881 @noindent
22882 This section compares the treatment of tasking in GNAT
22883 and in HP Ada for OpenVMS Alpha.
22884 The GNAT description applies to both Alpha and I64 OpenVMS.
22885 For detailed information on tasking in
22886 HP Ada, see the @cite{HP Ada Language Reference Manual} and the
22887 relevant run-time reference manual.
22888
22889 @menu
22890 * Implementation of Tasks in HP Ada for OpenVMS Alpha Systems::
22891 * Assigning Task IDs::
22892 * Task IDs and Delays::
22893 * Task-Related Pragmas::
22894 * Scheduling and Task Priority::
22895 * The Task Stack::
22896 * External Interrupts::
22897 @end menu
22898
22899 @node Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22900 @subsection Implementation of Tasks in HP Ada for OpenVMS Alpha Systems
22901
22902 @noindent
22903 On OpenVMS Alpha systems, each Ada task (except a passive
22904 task) is implemented as a single stream of execution
22905 that is created and managed by the kernel. On these
22906 systems, HP Ada tasking support is based on DECthreads,
22907 an implementation of the POSIX standard for threads.
22908
22909 Also, on OpenVMS Alpha systems, HP Ada tasks and foreign
22910 code that calls DECthreads routines can be used together.
22911 The interaction between Ada tasks and DECthreads routines
22912 can have some benefits. For example when on OpenVMS Alpha,
22913 HP Ada can call C code that is already threaded.
22914
22915 GNAT uses the facilities of DECthreads,
22916 and Ada tasks are mapped to threads.
22917
22918 @node Assigning Task IDs
22919 @subsection Assigning Task IDs
22920
22921 @noindent
22922 The HP Ada Run-Time Library always assigns @code{%TASK 1} to
22923 the environment task that executes the main program. On
22924 OpenVMS Alpha systems, @code{%TASK 0} is often used for tasks
22925 that have been created but are not yet activated.
22926
22927 On OpenVMS Alpha systems, task IDs are assigned at
22928 activation. On GNAT systems, task IDs are also assigned at
22929 task creation but do not have the same form or values as
22930 task ID values in HP Ada. There is no null task, and the
22931 environment task does not have a specific task ID value.
22932
22933 @node Task IDs and Delays
22934 @subsection Task IDs and Delays
22935
22936 @noindent
22937 On OpenVMS Alpha systems, tasking delays are implemented
22938 using Timer System Services. The Task ID is used for the
22939 identification of the timer request (the @code{REQIDT} parameter).
22940 If Timers are used in the application take care not to use
22941 @code{0} for the identification, because cancelling such a timer
22942 will cancel all timers and may lead to unpredictable results.
22943
22944 @node Task-Related Pragmas
22945 @subsection Task-Related Pragmas
22946
22947 @noindent
22948 Ada supplies the pragma @code{TASK_STORAGE}, which allows
22949 specification of the size of the guard area for a task
22950 stack. (The guard area forms an area of memory that has no
22951 read or write access and thus helps in the detection of
22952 stack overflow.) On OpenVMS Alpha systems, if the pragma
22953 @code{TASK_STORAGE} specifies a value of zero, a minimal guard
22954 area is created. In the absence of a pragma @code{TASK_STORAGE},
22955 a default guard area is created.
22956
22957 GNAT supplies the following task-related pragma:
22958
22959 @itemize
22960 @item @code{TASK_STORAGE}
22961
22962 GNAT implements pragma @code{TASK_STORAGE} in the same way as HP Ada.
22963 Both HP Ada and GNAT supply the pragmas @code{PASSIVE},
22964 @code{SUPPRESS}, and @code{VOLATILE}.
22965 @end itemize
22966
22967 @node Scheduling and Task Priority
22968 @subsection Scheduling and Task Priority
22969
22970 @noindent
22971 HP Ada implements the Ada language requirement that
22972 when two tasks are eligible for execution and they have
22973 different priorities, the lower priority task does not
22974 execute while the higher priority task is waiting. The HP
22975 Ada Run-Time Library keeps a task running until either the
22976 task is suspended or a higher priority task becomes ready.
22977
22978 On OpenVMS Alpha systems, the default strategy is round-
22979 robin with preemption. Tasks of equal priority take turns
22980 at the processor. A task is run for a certain period of
22981 time and then placed at the tail of the ready queue for
22982 its priority level.
22983
22984 HP Ada provides the implementation-defined pragma @code{TIME_SLICE},
22985 which can be used to enable or disable round-robin
22986 scheduling of tasks with the same priority.
22987 See the relevant HP Ada run-time reference manual for
22988 information on using the pragmas to control HP Ada task
22989 scheduling.
22990
22991 GNAT follows the scheduling rules of Annex D (Real-Time
22992 Annex) of the @cite{Ada Reference Manual}. In general, this
22993 scheduling strategy is fully compatible with HP Ada
22994 although it provides some additional constraints (as
22995 fully documented in Annex D).
22996 GNAT implements time slicing control in a manner compatible with
22997 HP Ada 83, by means of the pragma @code{Time_Slice}, whose semantics
22998 are identical to the HP Ada 83 pragma of the same name.
22999 Note that it is not possible to mix GNAT tasking and
23000 HP Ada 83 tasking in the same program, since the two run-time
23001 libraries are not compatible.
23002
23003 @node The Task Stack
23004 @subsection The Task Stack
23005
23006 @noindent
23007 In HP Ada, a task stack is allocated each time a
23008 non-passive task is activated. As soon as the task is
23009 terminated, the storage for the task stack is deallocated.
23010 If you specify a size of zero (bytes) with @code{T'STORAGE_SIZE},
23011 a default stack size is used. Also, regardless of the size
23012 specified, some additional space is allocated for task
23013 management purposes. On OpenVMS Alpha systems, at least
23014 one page is allocated.
23015
23016 GNAT handles task stacks in a similar manner. In accordance with
23017 the Ada rules, it provides the pragma @code{STORAGE_SIZE} as
23018 an alternative method for controlling the task stack size.
23019 The specification of the attribute @code{T'STORAGE_SIZE} is also
23020 supported in a manner compatible with HP Ada.
23021
23022 @node External Interrupts
23023 @subsection External Interrupts
23024
23025 @noindent
23026 On HP Ada, external interrupts can be associated with task entries.
23027 GNAT is compatible with HP Ada in its handling of external interrupts.
23028
23029 @node Pragmas and Pragma-Related Features
23030 @section Pragmas and Pragma-Related Features
23031
23032 @noindent
23033 Both HP Ada and GNAT supply all language-defined pragmas
23034 as specified by the Ada 83 standard. GNAT also supplies all
23035 language-defined pragmas introduced by Ada 95 and Ada 2005.
23036 In addition, GNAT implements the implementation-defined pragmas
23037 from HP Ada 83.
23038
23039 @itemize @bullet
23040 @item @code{AST_ENTRY}
23041
23042 @item @code{COMMON_OBJECT}
23043
23044 @item @code{COMPONENT_ALIGNMENT}
23045
23046 @item @code{EXPORT_EXCEPTION}
23047
23048 @item @code{EXPORT_FUNCTION}
23049
23050 @item @code{EXPORT_OBJECT}
23051
23052 @item @code{EXPORT_PROCEDURE}
23053
23054 @item @code{EXPORT_VALUED_PROCEDURE}
23055
23056 @item @code{FLOAT_REPRESENTATION}
23057
23058 @item @code{IDENT}
23059
23060 @item @code{IMPORT_EXCEPTION}
23061
23062 @item @code{IMPORT_FUNCTION}
23063
23064 @item @code{IMPORT_OBJECT}
23065
23066 @item @code{IMPORT_PROCEDURE}
23067
23068 @item @code{IMPORT_VALUED_PROCEDURE}
23069
23070 @item @code{INLINE_GENERIC}
23071
23072 @item @code{INTERFACE_NAME}
23073
23074 @item @code{LONG_FLOAT}
23075
23076 @item @code{MAIN_STORAGE}
23077
23078 @item @code{PASSIVE}
23079
23080 @item @code{PSECT_OBJECT}
23081
23082 @item @code{SHARE_GENERIC}
23083
23084 @item @code{SUPPRESS_ALL}
23085
23086 @item @code{TASK_STORAGE}
23087
23088 @item @code{TIME_SLICE}
23089
23090 @item @code{TITLE}
23091 @end itemize
23092
23093 @noindent
23094 These pragmas are all fully implemented, with the exception of @code{TITLE},
23095 @code{PASSIVE}, and @code{SHARE_GENERIC}, which are
23096 recognized, but which have no
23097 effect in GNAT. The effect of @code{PASSIVE} may be obtained by the
23098 use of Ada protected objects. In GNAT, all generics are inlined.
23099
23100 Unlike HP Ada, the GNAT ``@code{EXPORT_}@i{subprogram}'' pragmas require
23101 a separate subprogram specification which must appear before the
23102 subprogram body.
23103
23104 GNAT also supplies a number of implementation-defined pragmas including the
23105 following:
23106
23107 @itemize @bullet
23108 @item @code{ABORT_DEFER}
23109
23110 @item @code{ADA_83}
23111
23112 @item @code{ADA_95}
23113
23114 @item @code{ADA_05}
23115
23116 @item @code{Ada_2005}
23117
23118 @item @code{Ada_12}
23119
23120 @item @code{Ada_2012}
23121
23122 @item @code{ALLOW_INTEGER_ADDRESS}
23123
23124 @item @code{ANNOTATE}
23125
23126 @item @code{ASSERT}
23127
23128 @item @code{C_PASS_BY_COPY}
23129
23130 @item @code{CPP_CLASS}
23131
23132 @item @code{CPP_CONSTRUCTOR}
23133
23134 @item @code{CPP_DESTRUCTOR}
23135
23136 @item @code{DEBUG}
23137
23138 @item @code{EXTEND_SYSTEM}
23139
23140 @item @code{LINKER_ALIAS}
23141
23142 @item @code{LINKER_SECTION}
23143
23144 @item @code{MACHINE_ATTRIBUTE}
23145
23146 @item @code{NO_RETURN}
23147
23148 @item @code{PURE_FUNCTION}
23149
23150 @item @code{SOURCE_FILE_NAME}
23151
23152 @item @code{SOURCE_REFERENCE}
23153
23154 @item @code{UNCHECKED_UNION}
23155
23156 @item @code{UNIMPLEMENTED_UNIT}
23157
23158 @item @code{UNIVERSAL_DATA}
23159
23160 @item @code{UNSUPPRESS}
23161
23162 @item @code{WARNINGS}
23163
23164 @item @code{WEAK_EXTERNAL}
23165 @end itemize
23166
23167 @noindent
23168 For full details on these and other GNAT implementation-defined pragmas,
23169 see @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT Reference
23170 Manual}.
23171
23172 @menu
23173 * Restrictions on the Pragma INLINE::
23174 * Restrictions on the Pragma INTERFACE::
23175 * Restrictions on the Pragma SYSTEM_NAME::
23176 @end menu
23177
23178 @node Restrictions on the Pragma INLINE
23179 @subsection Restrictions on Pragma @code{INLINE}
23180
23181 @noindent
23182 HP Ada enforces the following restrictions on the pragma @code{INLINE}:
23183 @itemize @bullet
23184 @item Parameters cannot have a task type.
23185
23186 @item Function results cannot be task types, unconstrained
23187 array types, or unconstrained types with discriminants.
23188
23189 @item Bodies cannot declare the following:
23190 @itemize @bullet
23191 @item Subprogram body or stub (imported subprogram is allowed)
23192
23193 @item Tasks
23194
23195 @item Generic declarations
23196
23197 @item Instantiations
23198
23199 @item Exceptions
23200
23201 @item Access types (types derived from access types allowed)
23202
23203 @item Array or record types
23204
23205 @item Dependent tasks
23206
23207 @item Direct recursive calls of subprogram or containing
23208 subprogram, directly or via a renaming
23209
23210 @end itemize
23211 @end itemize
23212
23213 @noindent
23214 In GNAT, the only restriction on pragma @code{INLINE} is that the
23215 body must occur before the call if both are in the same
23216 unit, and the size must be appropriately small. There are
23217 no other specific restrictions which cause subprograms to
23218 be incapable of being inlined.
23219
23220 @node Restrictions on the Pragma INTERFACE
23221 @subsection Restrictions on Pragma @code{INTERFACE}
23222
23223 @noindent
23224 The following restrictions on pragma @code{INTERFACE}
23225 are enforced by both HP Ada and GNAT:
23226 @itemize @bullet
23227 @item Languages accepted: Ada, Bliss, C, Fortran, Default.
23228 Default is the default on OpenVMS Alpha systems.
23229
23230 @item Parameter passing: Language specifies default
23231 mechanisms but can be overridden with an @code{EXPORT} pragma.
23232
23233 @itemize @bullet
23234 @item Ada: Use internal Ada rules.
23235
23236 @item Bliss, C: Parameters must be mode @code{in}; cannot be
23237 record or task type. Result cannot be a string, an
23238 array, or a record.
23239
23240 @item Fortran: Parameters cannot have a task type. Result cannot
23241 be a string, an array, or a record.
23242 @end itemize
23243 @end itemize
23244
23245 @noindent
23246 GNAT is entirely upwards compatible with HP Ada, and in addition allows
23247 record parameters for all languages.
23248
23249 @node Restrictions on the Pragma SYSTEM_NAME
23250 @subsection Restrictions on Pragma @code{SYSTEM_NAME}
23251
23252 @noindent
23253 For HP Ada for OpenVMS Alpha, the enumeration literal
23254 for the type @code{NAME} is @code{OPENVMS_AXP}.
23255 In GNAT, the enumeration
23256 literal for the type @code{NAME} is @code{SYSTEM_NAME_GNAT}.
23257
23258 @node Library of Predefined Units
23259 @section Library of Predefined Units
23260
23261 @noindent
23262 A library of predefined units is provided as part of the
23263 HP Ada and GNAT implementations. HP Ada does not provide
23264 the package @code{MACHINE_CODE} but instead recommends importing
23265 assembler code.
23266
23267 The GNAT versions of the HP Ada Run-Time Library (@code{ADA$PREDEFINED:})
23268 units are taken from the OpenVMS Alpha version, not the OpenVMS VAX
23269 version.
23270 The HP Ada Predefined Library units are modified to remove post-Ada 83
23271 incompatibilities and to make them interoperable with GNAT
23272 (@pxref{Changes to DECLIB}, for details).
23273 The units are located in the @file{DECLIB} directory.
23274
23275 The GNAT RTL is contained in
23276 the @file{ADALIB} directory, and
23277 the default search path is set up to find @code{DECLIB} units in preference
23278 to @code{ADALIB} units with the same name (@code{TEXT_IO},
23279 @code{SEQUENTIAL_IO}, and @code{DIRECT_IO}, for example).
23280
23281 @menu
23282 * Changes to DECLIB::
23283 @end menu
23284
23285 @node Changes to DECLIB
23286 @subsection Changes to @code{DECLIB}
23287
23288 @noindent
23289 The changes made to the HP Ada predefined library for GNAT and post-Ada 83
23290 compatibility are minor and include the following:
23291
23292 @itemize @bullet
23293 @item Adjusting the location of pragmas and record representation
23294 clauses to obey Ada 95 (and thus Ada 2005) rules
23295
23296 @item Adding the proper notation to generic formal parameters
23297 that take unconstrained types in instantiation
23298
23299 @item Adding pragma @code{ELABORATE_BODY} to package specs
23300 that have package bodies not otherwise allowed
23301
23302 @item Replacing occurrences of the identifier ``@code{PROTECTED}'' by
23303 ``@code{PROTECTD}''.
23304 Currently these are found only in the @code{STARLET} package spec.
23305
23306 @item Changing @code{SYSTEM.ADDRESS} to @code{SYSTEM.SHORT_ADDRESS}
23307 where the address size is constrained to 32 bits.
23308 @end itemize
23309
23310 @noindent
23311 None of the above changes is visible to users.
23312
23313 @node Bindings
23314 @section Bindings
23315
23316 @noindent
23317 On OpenVMS Alpha, HP Ada provides the following strongly-typed bindings:
23318 @itemize @bullet
23319
23320 @item Command Language Interpreter (CLI interface)
23321
23322 @item DECtalk Run-Time Library (DTK interface)
23323
23324 @item Librarian utility routines (LBR interface)
23325
23326 @item General Purpose Run-Time Library (LIB interface)
23327
23328 @item Math Run-Time Library (MTH interface)
23329
23330 @item National Character Set Run-Time Library (NCS interface)
23331
23332 @item Compiled Code Support Run-Time Library (OTS interface)
23333
23334 @item Parallel Processing Run-Time Library (PPL interface)
23335
23336 @item Screen Management Run-Time Library (SMG interface)
23337
23338 @item Sort Run-Time Library (SOR interface)
23339
23340 @item String Run-Time Library (STR interface)
23341
23342 @item STARLET System Library
23343 @findex Starlet
23344
23345 @item X Window System Version 11R4 and 11R5 (X, XLIB interface)
23346
23347 @item X Windows Toolkit (XT interface)
23348
23349 @item X/Motif Version 1.1.3 and 1.2 (XM interface)
23350 @end itemize
23351
23352 @noindent
23353 GNAT provides implementations of these HP bindings in the @code{DECLIB}
23354 directory, on both the Alpha and I64 OpenVMS platforms.
23355
23356 The X components of DECLIB compatibility package are located in a separate
23357 library, called XDECGNAT, which is not linked with by default; this library
23358 must be explicitly linked with any application that makes use of any X facilities,
23359 with a command similar to
23360
23361 @code{GNAT MAKE USE_X /LINK /LIBRARY=XDECGNAT}
23362
23363 The X/Motif bindings used to build @code{DECLIB} are whatever versions are
23364 in the
23365 HP Ada @file{ADA$PREDEFINED} directory with extension @file{.ADC}.
23366 A pragma @code{Linker_Options} has been added to packages @code{Xm},
23367 @code{Xt}, and @code{X_Lib}
23368 causing the default X/Motif sharable image libraries to be linked in. This
23369 is done via options files named @file{xm.opt}, @file{xt.opt}, and
23370 @file{x_lib.opt} (also located in the @file{DECLIB} directory).
23371
23372 It may be necessary to edit these options files to update or correct the
23373 library names if, for example, the newer X/Motif bindings from
23374 @file{ADA$EXAMPLES}
23375 had been (previous to installing GNAT) copied and renamed to supersede the
23376 default @file{ADA$PREDEFINED} versions.
23377
23378 @menu
23379 * Shared Libraries and Options Files::
23380 * Interfaces to C::
23381 @end menu
23382
23383 @node Shared Libraries and Options Files
23384 @subsection Shared Libraries and Options Files
23385
23386 @noindent
23387 When using the HP Ada
23388 predefined X and Motif bindings, the linking with their sharable images is
23389 done automatically by @command{GNAT LINK}.
23390 When using other X and Motif bindings, you need
23391 to add the corresponding sharable images to the command line for
23392 @code{GNAT LINK}. When linking with shared libraries, or with
23393 @file{.OPT} files, you must
23394 also add them to the command line for @command{GNAT LINK}.
23395
23396 A shared library to be used with GNAT is built in the same way as other
23397 libraries under VMS. The VMS Link command can be used in standard fashion.
23398
23399 @node Interfaces to C
23400 @subsection Interfaces to C
23401
23402 @noindent
23403 HP Ada
23404 provides the following Ada types and operations:
23405
23406 @itemize @bullet
23407 @item C types package (@code{C_TYPES})
23408
23409 @item C strings (@code{C_TYPES.NULL_TERMINATED})
23410
23411 @item Other_types (@code{SHORT_INT})
23412 @end itemize
23413
23414 @noindent
23415 Interfacing to C with GNAT, you can use the above approach
23416 described for HP Ada or the facilities of Annex B of
23417 the @cite{Ada Reference Manual} (packages @code{INTERFACES.C},
23418 @code{INTERFACES.C.STRINGS} and @code{INTERFACES.C.POINTERS}). For more
23419 information, see @ref{Interfacing to C,,, gnat_rm, GNAT Reference Manual}.
23420
23421 The @option{-gnatF} qualifier forces default and explicit
23422 @code{External_Name} parameters in pragmas @code{Import} and @code{Export}
23423 to be uppercased for compatibility with the default behavior
23424 of HP C. The qualifier has no effect on @code{Link_Name} parameters.
23425
23426 @node Main Program Definition
23427 @section Main Program Definition
23428
23429 @noindent
23430 The following section discusses differences in the
23431 definition of main programs on HP Ada and GNAT.
23432 On HP Ada, main programs are defined to meet the
23433 following conditions:
23434 @itemize @bullet
23435 @item Procedure with no formal parameters (returns @code{0} upon
23436 normal completion)
23437
23438 @item Procedure with no formal parameters (returns @code{42} when
23439 an unhandled exception is raised)
23440
23441 @item Function with no formal parameters whose returned value
23442 is of a discrete type
23443
23444 @item Procedure with one @code{out} formal of a discrete type for
23445 which a specification of pragma @code{EXPORT_VALUED_PROCEDURE} is given.
23446
23447 @end itemize
23448
23449 @noindent
23450 When declared with the pragma @code{EXPORT_VALUED_PROCEDURE},
23451 a main function or main procedure returns a discrete
23452 value whose size is less than 64 bits (32 on VAX systems),
23453 the value is zero- or sign-extended as appropriate.
23454 On GNAT, main programs are defined as follows:
23455 @itemize @bullet
23456 @item Must be a non-generic, parameterless subprogram that
23457 is either a procedure or function returning an Ada
23458 @code{STANDARD.INTEGER} (the predefined type)
23459
23460 @item Cannot be a generic subprogram or an instantiation of a
23461 generic subprogram
23462 @end itemize
23463
23464 @node Implementation-Defined Attributes
23465 @section Implementation-Defined Attributes
23466
23467 @noindent
23468 GNAT provides all HP Ada implementation-defined
23469 attributes.
23470
23471 @node Compiler and Run-Time Interfacing
23472 @section Compiler and Run-Time Interfacing
23473
23474 @noindent
23475 HP Ada provides the following qualifiers to pass options to the linker
23476 (ACS LINK):
23477 @itemize @bullet
23478 @item @option{/WAIT} and @option{/SUBMIT}
23479
23480 @item @option{/COMMAND}
23481
23482 @item @option{/@r{[}NO@r{]}MAP}
23483
23484 @item @option{/OUTPUT=@var{file-spec}}
23485
23486 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
23487 @end itemize
23488
23489 @noindent
23490 To pass options to the linker, GNAT provides the following
23491 switches:
23492
23493 @itemize @bullet
23494 @item @option{/EXECUTABLE=@var{exec-name}}
23495
23496 @item @option{/VERBOSE}
23497
23498 @item @option{/@r{[}NO@r{]}DEBUG} and @option{/@r{[}NO@r{]}TRACEBACK}
23499 @end itemize
23500
23501 @noindent
23502 For more information on these switches, see
23503 @ref{Switches for gnatlink}.
23504 In HP Ada, the command-line switch @option{/OPTIMIZE} is available
23505 to control optimization. HP Ada also supplies the
23506 following pragmas:
23507 @itemize @bullet
23508 @item @code{OPTIMIZE}
23509
23510 @item @code{INLINE}
23511
23512 @item @code{INLINE_GENERIC}
23513
23514 @item @code{SUPPRESS_ALL}
23515
23516 @item @code{PASSIVE}
23517 @end itemize
23518
23519 @noindent
23520 In GNAT, optimization is controlled strictly by command
23521 line parameters, as described in the corresponding section of this guide.
23522 The HP pragmas for control of optimization are
23523 recognized but ignored.
23524
23525 Note that in GNAT, the default is optimization off, whereas in HP Ada
23526 the default is that optimization is turned on.
23527
23528 @node Program Compilation and Library Management
23529 @section Program Compilation and Library Management
23530
23531 @noindent
23532 HP Ada and GNAT provide a comparable set of commands to
23533 build programs. HP Ada also provides a program library,
23534 which is a concept that does not exist on GNAT. Instead,
23535 GNAT provides directories of sources that are compiled as
23536 needed.
23537
23538 The following table summarizes
23539 the HP Ada commands and provides
23540 equivalent GNAT commands. In this table, some GNAT
23541 equivalents reflect the fact that GNAT does not use the
23542 concept of a program library. Instead, it uses a model
23543 in which collections of source and object files are used
23544 in a manner consistent with other languages like C and
23545 Fortran. Therefore, standard system file commands are used
23546 to manipulate these elements. Those GNAT commands are marked with
23547 an asterisk.
23548 Note that, unlike HP Ada, none of the GNAT commands accepts wild cards.
23549
23550 @need 1500
23551 @multitable @columnfractions .35 .65
23552
23553 @item @emph{HP Ada Command}
23554 @tab @emph{GNAT Equivalent / Description}
23555
23556 @item @command{ADA}
23557 @tab @command{GNAT COMPILE}@*
23558 Invokes the compiler to compile one or more Ada source files.
23559
23560 @item @command{ACS ATTACH}@*
23561 @tab [No equivalent]@*
23562 Switches control of terminal from current process running the program
23563 library manager.
23564
23565 @item @command{ACS CHECK}
23566 @tab @command{GNAT MAKE /DEPENDENCY_LIST}@*
23567 Forms the execution closure of one
23568 or more compiled units and checks completeness and currency.
23569
23570 @item @command{ACS COMPILE}
23571 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23572 Forms the execution closure of one or
23573 more specified units, checks completeness and currency,
23574 identifies units that have revised source files, compiles same,
23575 and recompiles units that are or will become obsolete.
23576 Also completes incomplete generic instantiations.
23577
23578 @item @command{ACS COPY FOREIGN}
23579 @tab Copy (*)@*
23580 Copies a foreign object file into the program library as a
23581 library unit body.
23582
23583 @item @command{ACS COPY UNIT}
23584 @tab Copy (*)@*
23585 Copies a compiled unit from one program library to another.
23586
23587 @item @command{ACS CREATE LIBRARY}
23588 @tab Create /directory (*)@*
23589 Creates a program library.
23590
23591 @item @command{ACS CREATE SUBLIBRARY}
23592 @tab Create /directory (*)@*
23593 Creates a program sublibrary.
23594
23595 @item @command{ACS DELETE LIBRARY}
23596 @tab @*
23597 Deletes a program library and its contents.
23598
23599 @item @command{ACS DELETE SUBLIBRARY}
23600 @tab @*
23601 Deletes a program sublibrary and its contents.
23602
23603 @item @command{ACS DELETE UNIT}
23604 @tab Delete file (*)@*
23605 On OpenVMS systems, deletes one or more compiled units from
23606 the current program library.
23607
23608 @item @command{ACS DIRECTORY}
23609 @tab Directory (*)@*
23610 On OpenVMS systems, lists units contained in the current
23611 program library.
23612
23613 @item @command{ACS ENTER FOREIGN}
23614 @tab Copy (*)@*
23615 Allows the import of a foreign body as an Ada library
23616 spec and enters a reference to a pointer.
23617
23618 @item @command{ACS ENTER UNIT}
23619 @tab Copy (*)@*
23620 Enters a reference (pointer) from the current program library to
23621 a unit compiled into another program library.
23622
23623 @item @command{ACS EXIT}
23624 @tab [No equivalent]@*
23625 Exits from the program library manager.
23626
23627 @item @command{ACS EXPORT}
23628 @tab Copy (*)@*
23629 Creates an object file that contains system-specific object code
23630 for one or more units. With GNAT, object files can simply be copied
23631 into the desired directory.
23632
23633 @item @command{ACS EXTRACT SOURCE}
23634 @tab Copy (*)@*
23635 Allows access to the copied source file for each Ada compilation unit
23636
23637 @item @command{ACS HELP}
23638 @tab @command{HELP GNAT}@*
23639 Provides online help.
23640
23641 @item @command{ACS LINK}
23642 @tab @command{GNAT LINK}@*
23643 Links an object file containing Ada units into an executable file.
23644
23645 @item @command{ACS LOAD}
23646 @tab Copy (*)@*
23647 Loads (partially compiles) Ada units into the program library.
23648 Allows loading a program from a collection of files into a library
23649 without knowing the relationship among units.
23650
23651 @item @command{ACS MERGE}
23652 @tab Copy (*)@*
23653 Merges into the current program library, one or more units from
23654 another library where they were modified.
23655
23656 @item @command{ACS RECOMPILE}
23657 @tab @command{GNAT MAKE /ACTIONS=COMPILE}@*
23658 Recompiles from external or copied source files any obsolete
23659 unit in the closure. Also, completes any incomplete generic
23660 instantiations.
23661
23662 @item @command{ACS REENTER}
23663 @tab @command{GNAT MAKE}@*
23664 Reenters current references to units compiled after last entered
23665 with the @command{ACS ENTER UNIT} command.
23666
23667 @item @command{ACS SET LIBRARY}
23668 @tab Set default (*)@*
23669 Defines a program library to be the compilation context as well
23670 as the target library for compiler output and commands in general.
23671
23672 @item @command{ACS SET PRAGMA}
23673 @tab Edit @file{gnat.adc} (*)@*
23674 Redefines specified values of the library characteristics
23675 @code{LONG_ FLOAT}, @code{MEMORY_SIZE}, @code{SYSTEM_NAME},
23676 and @code{Float_Representation}.
23677
23678 @item @command{ACS SET SOURCE}
23679 @tab Define @code{ADA_INCLUDE_PATH} path (*)@*
23680 Defines the source file search list for the @command{ACS COMPILE} command.
23681
23682 @item @command{ACS SHOW LIBRARY}
23683 @tab Directory (*)@*
23684 Lists information about one or more program libraries.
23685
23686 @item @command{ACS SHOW PROGRAM}
23687 @tab [No equivalent]@*
23688 Lists information about the execution closure of one or
23689 more units in the program library.
23690
23691 @item @command{ACS SHOW SOURCE}
23692 @tab Show logical @code{ADA_INCLUDE_PATH}@*
23693 Shows the source file search used when compiling units.
23694
23695 @item @command{ACS SHOW VERSION}
23696 @tab Compile with @option{VERBOSE} option
23697 Displays the version number of the compiler and program library
23698 manager used.
23699
23700 @item @command{ACS SPAWN}
23701 @tab [No equivalent]@*
23702 Creates a subprocess of the current process (same as @command{DCL SPAWN}
23703 command).
23704
23705 @item @command{ACS VERIFY}
23706 @tab [No equivalent]@*
23707 Performs a series of consistency checks on a program library to
23708 determine whether the library structure and library files are in
23709 valid form.
23710 @end multitable
23711
23712 @noindent
23713
23714 @node Input-Output
23715 @section Input-Output
23716
23717 @noindent
23718 On OpenVMS Alpha systems, HP Ada uses OpenVMS Record
23719 Management Services (RMS) to perform operations on
23720 external files.
23721
23722 @noindent
23723 HP Ada and GNAT predefine an identical set of input-
23724 output packages. To make the use of the
23725 generic @code{TEXT_IO} operations more convenient, HP Ada
23726 provides predefined library packages that instantiate the
23727 integer and floating-point operations for the predefined
23728 integer and floating-point types as shown in the following table.
23729
23730 @multitable @columnfractions .45 .55
23731 @item @emph{Package Name} @tab Instantiation
23732
23733 @item @code{INTEGER_TEXT_IO}
23734 @tab @code{INTEGER_IO(INTEGER)}
23735
23736 @item @code{SHORT_INTEGER_TEXT_IO}
23737 @tab @code{INTEGER_IO(SHORT_INTEGER)}
23738
23739 @item @code{SHORT_SHORT_INTEGER_TEXT_IO}
23740 @tab @code{INTEGER_IO(SHORT_SHORT_INTEGER)}
23741
23742 @item @code{FLOAT_TEXT_IO}
23743 @tab @code{FLOAT_IO(FLOAT)}
23744
23745 @item @code{LONG_FLOAT_TEXT_IO}
23746 @tab @code{FLOAT_IO(LONG_FLOAT)}
23747 @end multitable
23748
23749 @noindent
23750 The HP Ada predefined packages and their operations
23751 are implemented using OpenVMS Alpha files and input-output
23752 facilities. HP Ada supports asynchronous input-output on OpenVMS Alpha.
23753 Familiarity with the following is recommended:
23754 @itemize @bullet
23755 @item RMS file organizations and access methods
23756
23757 @item OpenVMS file specifications and directories
23758
23759 @item OpenVMS File Definition Language (FDL)
23760 @end itemize
23761
23762 @noindent
23763 GNAT provides I/O facilities that are completely
23764 compatible with HP Ada. The distribution includes the
23765 standard HP Ada versions of all I/O packages, operating
23766 in a manner compatible with HP Ada. In particular, the
23767 following packages are by default the HP Ada (Ada 83)
23768 versions of these packages rather than the renamings
23769 suggested in Annex J of the Ada Reference Manual:
23770 @itemize @bullet
23771 @item @code{TEXT_IO}
23772
23773 @item @code{SEQUENTIAL_IO}
23774
23775 @item @code{DIRECT_IO}
23776 @end itemize
23777
23778 @noindent
23779 The use of the standard child package syntax (for
23780 example, @code{ADA.TEXT_IO}) retrieves the post-Ada 83 versions of these
23781 packages.
23782 GNAT provides HP-compatible predefined instantiations
23783 of the @code{TEXT_IO} packages, and also
23784 provides the standard predefined instantiations required
23785 by the @cite{Ada Reference Manual}.
23786
23787 For further information on how GNAT interfaces to the file
23788 system or how I/O is implemented in programs written in
23789 mixed languages, see @ref{Implementation of the Standard I/O,,,
23790 gnat_rm, GNAT Reference Manual}.
23791 This chapter covers the following:
23792 @itemize @bullet
23793 @item Standard I/O packages
23794
23795 @item @code{FORM} strings
23796
23797 @item @code{ADA.DIRECT_IO}
23798
23799 @item @code{ADA.SEQUENTIAL_IO}
23800
23801 @item @code{ADA.TEXT_IO}
23802
23803 @item Stream pointer positioning
23804
23805 @item Reading and writing non-regular files
23806
23807 @item @code{GET_IMMEDIATE}
23808
23809 @item Treating @code{TEXT_IO} files as streams
23810
23811 @item Shared files
23812
23813 @item Open modes
23814 @end itemize
23815
23816 @node Implementation Limits
23817 @section Implementation Limits
23818
23819 @noindent
23820 The following table lists implementation limits for HP Ada
23821 and GNAT systems.
23822 @multitable @columnfractions .60 .20 .20
23823 @sp 1
23824 @item @emph{Compilation Parameter}
23825 @tab @emph{HP Ada}
23826 @tab @emph{GNAT}
23827 @sp 1
23828
23829 @item In a subprogram or entry declaration, maximum number of
23830 formal parameters that are of an unconstrained record type
23831 @tab 32
23832 @tab No set limit
23833 @sp 1
23834
23835 @item Maximum identifier length (number of characters)
23836 @tab 255
23837 @tab 32766
23838 @sp 1
23839
23840 @item Maximum number of characters in a source line
23841 @tab 255
23842 @tab 32766
23843 @sp 1
23844
23845 @item Maximum collection size (number of bytes)
23846 @tab 2**31-1
23847 @tab 2**31-1
23848 @sp 1
23849
23850 @item Maximum number of discriminants for a record type
23851 @tab 245
23852 @tab No set limit
23853 @sp 1
23854
23855 @item Maximum number of formal parameters in an entry or
23856 subprogram declaration
23857 @tab 246
23858 @tab No set limit
23859 @sp 1
23860
23861 @item Maximum number of dimensions in an array type
23862 @tab 255
23863 @tab No set limit
23864 @sp 1
23865
23866 @item Maximum number of library units and subunits in a compilation.
23867 @tab 4095
23868 @tab No set limit
23869 @sp 1
23870
23871 @item Maximum number of library units and subunits in an execution.
23872 @tab 16383
23873 @tab No set limit
23874 @sp 1
23875
23876 @item Maximum number of objects declared with the pragma @code{COMMON_OBJECT}
23877 or @code{PSECT_OBJECT}
23878 @tab 32757
23879 @tab No set limit
23880 @sp 1
23881
23882 @item Maximum number of enumeration literals in an enumeration type
23883 definition
23884 @tab 65535
23885 @tab No set limit
23886 @sp 1
23887
23888 @item Maximum number of lines in a source file
23889 @tab 65534
23890 @tab No set limit
23891 @sp 1
23892
23893 @item Maximum number of bits in any object
23894 @tab 2**31-1
23895 @tab 2**31-1
23896 @sp 1
23897
23898 @item Maximum size of the static portion of a stack frame (approximate)
23899 @tab 2**31-1
23900 @tab 2**31-1
23901 @end multitable
23902
23903 @node Tools and Utilities
23904 @section Tools and Utilities
23905
23906 @noindent
23907 The following table lists some of the OpenVMS development tools
23908 available for HP Ada, and the corresponding tools for
23909 use with @value{EDITION} on Alpha and I64 platforms.
23910 Aside from the debugger, all the OpenVMS tools identified are part
23911 of the DECset package.
23912
23913 @iftex
23914 @c Specify table in TeX since Texinfo does a poor job
23915 @tex
23916 \smallskip
23917 \smallskip
23918 \settabs\+Language-Sensitive Editor\quad
23919 &Product with HP Ada\quad
23920 &\cr
23921 \+\it Tool
23922 &\it Product with HP Ada
23923 & \it Product with @value{EDITION}\cr
23924 \smallskip
23925 \+Code Management System
23926 &HP CMS
23927 & HP CMS\cr
23928 \smallskip
23929 \+Language-Sensitive Editor
23930 &HP LSE
23931 & emacs or HP LSE (Alpha)\cr
23932 \+
23933 &
23934 & HP LSE (I64)\cr
23935 \smallskip
23936 \+Debugger
23937 &OpenVMS Debug
23938 & gdb (Alpha),\cr
23939 \+
23940 &
23941 & OpenVMS Debug (I64)\cr
23942 \smallskip
23943 \+Source Code Analyzer /
23944 &HP SCA
23945 & GNAT XREF\cr
23946 \+Cross Referencer
23947 &
23948 &\cr
23949 \smallskip
23950 \+Test Manager
23951 &HP Digital Test
23952 & HP DTM\cr
23953 \+
23954 &Manager (DTM)
23955 &\cr
23956 \smallskip
23957 \+Performance and
23958 & HP PCA
23959 & HP PCA\cr
23960 \+Coverage Analyzer
23961 &
23962 &\cr
23963 \smallskip
23964 \+Module Management
23965 & HP MMS
23966 & Not applicable\cr
23967 \+ System
23968 &
23969 &\cr
23970 \smallskip
23971 \smallskip
23972 @end tex
23973 @end iftex
23974
23975 @ifnottex
23976 @c This is the Texinfo version of the table. It renders poorly in pdf, hence
23977 @c the TeX version above for the printed version
23978 @flushleft
23979 @c @multitable @columnfractions .3 .4 .4
23980 @multitable {Source Code Analyzer /}{Tool with HP Ada}{Tool with @value{EDITION}}
23981 @item @i{Tool}
23982 @tab @i{Tool with HP Ada}
23983 @tab @i{Tool with @value{EDITION}}
23984 @item Code Management@*System
23985 @tab HP CMS
23986 @tab HP CMS
23987 @item Language-Sensitive@*Editor
23988 @tab HP LSE
23989 @tab emacs or HP LSE (Alpha)
23990 @item
23991 @tab
23992 @tab HP LSE (I64)
23993 @item Debugger
23994 @tab OpenVMS Debug
23995 @tab gdb (Alpha),
23996 @item
23997 @tab
23998 @tab OpenVMS Debug (I64)
23999 @item Source Code Analyzer /@*Cross Referencer
24000 @tab HP SCA
24001 @tab GNAT XREF
24002 @item Test Manager
24003 @tab HP Digital Test@*Manager (DTM)
24004 @tab HP DTM
24005 @item Performance and@*Coverage Analyzer
24006 @tab HP PCA
24007 @tab HP PCA
24008 @item Module Management@*System
24009 @tab HP MMS
24010 @tab Not applicable
24011 @end multitable
24012 @end flushleft
24013 @end ifnottex
24014
24015 @end ifset
24016
24017 @c **************************************
24018 @node Platform-Specific Information for the Run-Time Libraries
24019 @appendix Platform-Specific Information for the Run-Time Libraries
24020 @cindex Tasking and threads libraries
24021 @cindex Threads libraries and tasking
24022 @cindex Run-time libraries (platform-specific information)
24023
24024 @noindent
24025 The GNAT run-time implementation may vary with respect to both the
24026 underlying threads library and the exception handling scheme.
24027 For threads support, one or more of the following are supplied:
24028 @itemize @bullet
24029 @item @b{native threads library}, a binding to the thread package from
24030 the underlying operating system
24031
24032 @item @b{pthreads library} (Sparc Solaris only), a binding to the Solaris
24033 POSIX thread package
24034 @end itemize
24035
24036 @noindent
24037 For exception handling, either or both of two models are supplied:
24038 @itemize @bullet
24039 @item @b{Zero-Cost Exceptions} (``ZCX''),@footnote{
24040 Most programs should experience a substantial speed improvement by
24041 being compiled with a ZCX run-time.
24042 This is especially true for
24043 tasking applications or applications with many exception handlers.}
24044 @cindex Zero-Cost Exceptions
24045 @cindex ZCX (Zero-Cost Exceptions)
24046 which uses binder-generated tables that
24047 are interrogated at run time to locate a handler
24048
24049 @item @b{setjmp / longjmp} (``SJLJ''),
24050 @cindex setjmp/longjmp Exception Model
24051 @cindex SJLJ (setjmp/longjmp Exception Model)
24052 which uses dynamically-set data to establish
24053 the set of handlers
24054 @end itemize
24055
24056 @noindent
24057 This appendix summarizes which combinations of threads and exception support
24058 are supplied on various GNAT platforms.
24059 It then shows how to select a particular library either
24060 permanently or temporarily,
24061 explains the properties of (and tradeoffs among) the various threads
24062 libraries, and provides some additional
24063 information about several specific platforms.
24064
24065 @menu
24066 * Summary of Run-Time Configurations::
24067 * Specifying a Run-Time Library::
24068 * Choosing the Scheduling Policy::
24069 * Solaris-Specific Considerations::
24070 * Linux-Specific Considerations::
24071 * AIX-Specific Considerations::
24072 * RTX-Specific Considerations::
24073 * HP-UX-Specific Considerations::
24074 @end menu
24075
24076 @node Summary of Run-Time Configurations
24077 @section Summary of Run-Time Configurations
24078
24079 @multitable @columnfractions .30 .70
24080 @item @b{alpha-openvms}
24081 @item @code{@ @ }@i{rts-native (default)}
24082 @item @code{@ @ @ @ }Tasking @tab native VMS threads
24083 @item @code{@ @ @ @ }Exceptions @tab ZCX
24084 @*
24085 @item @code{@ @ }@i{rts-sjlj}
24086 @item @code{@ @ @ @ }Tasking @tab native TRU64 threads
24087 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24088 @*
24089 @item @b{ia64-hp_linux}
24090 @item @code{@ @ }@i{rts-native (default)}
24091 @item @code{@ @ @ @ }Tasking @tab pthread library
24092 @item @code{@ @ @ @ }Exceptions @tab ZCX
24093 @*
24094 @item @b{ia64-hpux}
24095 @item @code{@ @ }@i{rts-native (default)}
24096 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
24097 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24098 @*
24099 @item @b{ia64-openvms}
24100 @item @code{@ @ }@i{rts-native (default)}
24101 @item @code{@ @ @ @ }Tasking @tab native VMS threads
24102 @item @code{@ @ @ @ }Exceptions @tab ZCX
24103 @*
24104 @item @b{ia64-sgi_linux}
24105 @item @code{@ @ }@i{rts-native (default)}
24106 @item @code{@ @ @ @ }Tasking @tab pthread library
24107 @item @code{@ @ @ @ }Exceptions @tab ZCX
24108 @*
24109 @item @b{pa-hpux}
24110 @item @code{@ @ }@i{rts-native (default)}
24111 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
24112 @item @code{@ @ @ @ }Exceptions @tab ZCX
24113 @*
24114 @item @code{@ @ }@i{rts-sjlj}
24115 @item @code{@ @ @ @ }Tasking @tab native HP-UX threads
24116 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24117 @*
24118 @item @b{ppc-aix}
24119 @item @code{@ @ }@i{rts-native (default)}
24120 @item @code{@ @ @ @ }Tasking @tab native AIX threads
24121 @item @code{@ @ @ @ }Exceptions @tab ZCX
24122 @*
24123 @item @code{@ @ }@i{rts-sjlj}
24124 @item @code{@ @ @ @ }Tasking @tab native AIX threads
24125 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24126 @*
24127 @item @b{ppc-darwin}
24128 @item @code{@ @ }@i{rts-native (default)}
24129 @item @code{@ @ @ @ }Tasking @tab native MacOS threads
24130 @item @code{@ @ @ @ }Exceptions @tab ZCX
24131 @*
24132 @item @b{sparc-solaris} @tab
24133 @item @code{@ @ }@i{rts-native (default)}
24134 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24135 @item @code{@ @ @ @ }Exceptions @tab ZCX
24136 @*
24137 @item @code{@ @ }@i{rts-pthread}
24138 @item @code{@ @ @ @ }Tasking @tab pthread library
24139 @item @code{@ @ @ @ }Exceptions @tab ZCX
24140 @*
24141 @item @code{@ @ }@i{rts-sjlj}
24142 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24143 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24144 @*
24145 @item @b{sparc64-solaris} @tab
24146 @item @code{@ @ }@i{rts-native (default)}
24147 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24148 @item @code{@ @ @ @ }Exceptions @tab ZCX
24149 @*
24150 @item @b{x86-linux}
24151 @item @code{@ @ }@i{rts-native (default)}
24152 @item @code{@ @ @ @ }Tasking @tab pthread library
24153 @item @code{@ @ @ @ }Exceptions @tab ZCX
24154 @*
24155 @item @code{@ @ }@i{rts-sjlj}
24156 @item @code{@ @ @ @ }Tasking @tab pthread library
24157 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24158 @*
24159 @item @b{x86-lynx}
24160 @item @code{@ @ }@i{rts-native (default)}
24161 @item @code{@ @ @ @ }Tasking @tab native LynxOS threads
24162 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24163 @*
24164 @item @b{x86-solaris}
24165 @item @code{@ @ }@i{rts-native (default)}
24166 @item @code{@ @ @ @ }Tasking @tab native Solaris threads
24167 @item @code{@ @ @ @ }Exceptions @tab ZCX
24168 @*
24169 @item @code{@ @ }@i{rts-sjlj}
24170 @item @code{@ @ @ @ }Tasking @tab native Solaris threads library
24171 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24172 @*
24173 @item @b{x86-windows}
24174 @item @code{@ @ }@i{rts-native (default)}
24175 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
24176 @item @code{@ @ @ @ }Exceptions @tab ZCX
24177 @*
24178 @item @code{@ @ }@i{rts-sjlj}
24179 @item @code{@ @ @ @ }Tasking @tab native Win32 threads
24180 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24181 @*
24182 @item @b{x86-windows-rtx}
24183 @item @code{@ @ }@i{rts-rtx-rtss (default)}
24184 @item @code{@ @ @ @ }Tasking @tab RTX real-time subsystem RTSS threads (kernel mode)
24185 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24186 @*
24187 @item @code{@ @ }@i{rts-rtx-w32}
24188 @item @code{@ @ @ @ }Tasking @tab RTX Win32 threads (user mode)
24189 @item @code{@ @ @ @ }Exceptions @tab ZCX
24190 @*
24191 @item @b{x86_64-linux}
24192 @item @code{@ @ }@i{rts-native (default)}
24193 @item @code{@ @ @ @ }Tasking @tab pthread library
24194 @item @code{@ @ @ @ }Exceptions @tab ZCX
24195 @*
24196 @item @code{@ @ }@i{rts-sjlj}
24197 @item @code{@ @ @ @ }Tasking @tab pthread library
24198 @item @code{@ @ @ @ }Exceptions @tab SJLJ
24199 @*
24200 @end multitable
24201
24202 @node Specifying a Run-Time Library
24203 @section Specifying a Run-Time Library
24204
24205 @noindent
24206 The @file{adainclude} subdirectory containing the sources of the GNAT
24207 run-time library, and the @file{adalib} subdirectory containing the
24208 @file{ALI} files and the static and/or shared GNAT library, are located
24209 in the gcc target-dependent area:
24210
24211 @smallexample
24212 target=$prefix/lib/gcc/gcc-@i{dumpmachine}/gcc-@i{dumpversion}/
24213 @end smallexample
24214
24215 @noindent
24216 As indicated above, on some platforms several run-time libraries are supplied.
24217 These libraries are installed in the target dependent area and
24218 contain a complete source and binary subdirectory. The detailed description
24219 below explains the differences between the different libraries in terms of
24220 their thread support.
24221
24222 The default run-time library (when GNAT is installed) is @emph{rts-native}.
24223 This default run time is selected by the means of soft links.
24224 For example on x86-linux:
24225
24226 @smallexample
24227 @group
24228 $(target-dir)
24229 |
24230 +--- adainclude----------+
24231 | |
24232 +--- adalib-----------+ |
24233 | | |
24234 +--- rts-native | |
24235 | | | |
24236 | +--- adainclude <---+
24237 | | |
24238 | +--- adalib <----+
24239 |
24240 +--- rts-sjlj
24241 |
24242 +--- adainclude
24243 |
24244 +--- adalib
24245 @end group
24246 @end smallexample
24247
24248 @noindent
24249 If the @i{rts-sjlj} library is to be selected on a permanent basis,
24250 these soft links can be modified with the following commands:
24251
24252 @smallexample
24253 $ cd $target
24254 $ rm -f adainclude adalib
24255 $ ln -s rts-sjlj/adainclude adainclude
24256 $ ln -s rts-sjlj/adalib adalib
24257 @end smallexample
24258
24259 @noindent
24260 Alternatively, you can specify @file{rts-sjlj/adainclude} in the file
24261 @file{$target/ada_source_path} and @file{rts-sjlj/adalib} in
24262 @file{$target/ada_object_path}.
24263
24264 Selecting another run-time library temporarily can be
24265 achieved by using the @option{--RTS} switch, e.g., @option{--RTS=sjlj}
24266 @cindex @option{--RTS} option
24267
24268 @node Choosing the Scheduling Policy
24269 @section Choosing the Scheduling Policy
24270
24271 @noindent
24272 When using a POSIX threads implementation, you have a choice of several
24273 scheduling policies: @code{SCHED_FIFO},
24274 @cindex @code{SCHED_FIFO} scheduling policy
24275 @code{SCHED_RR}
24276 @cindex @code{SCHED_RR} scheduling policy
24277 and @code{SCHED_OTHER}.
24278 @cindex @code{SCHED_OTHER} scheduling policy
24279 Typically, the default is @code{SCHED_OTHER}, while using @code{SCHED_FIFO}
24280 or @code{SCHED_RR} requires special (e.g., root) privileges.
24281
24282 By default, GNAT uses the @code{SCHED_OTHER} policy. To specify
24283 @code{SCHED_FIFO},
24284 @cindex @code{SCHED_FIFO} scheduling policy
24285 you can use one of the following:
24286
24287 @itemize @bullet
24288 @item
24289 @code{pragma Time_Slice (0.0)}
24290 @cindex pragma Time_Slice
24291 @item
24292 the corresponding binder option @option{-T0}
24293 @cindex @option{-T0} option
24294 @item
24295 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
24296 @cindex pragma Task_Dispatching_Policy
24297 @end itemize
24298
24299 @noindent
24300 To specify @code{SCHED_RR},
24301 @cindex @code{SCHED_RR} scheduling policy
24302 you should use @code{pragma Time_Slice} with a
24303 value greater than @code{0.0}, or else use the corresponding @option{-T}
24304 binder option.
24305
24306 @node Solaris-Specific Considerations
24307 @section Solaris-Specific Considerations
24308 @cindex Solaris Sparc threads libraries
24309
24310 @noindent
24311 This section addresses some topics related to the various threads libraries
24312 on Sparc Solaris.
24313
24314 @menu
24315 * Solaris Threads Issues::
24316 @end menu
24317
24318 @node Solaris Threads Issues
24319 @subsection Solaris Threads Issues
24320
24321 @noindent
24322 GNAT under Solaris/Sparc 32 bits comes with an alternate tasking run-time
24323 library based on POSIX threads --- @emph{rts-pthread}.
24324 @cindex rts-pthread threads library
24325 This run-time library has the advantage of being mostly shared across all
24326 POSIX-compliant thread implementations, and it also provides under
24327 @w{Solaris 8} the @code{PTHREAD_PRIO_INHERIT}
24328 @cindex @code{PTHREAD_PRIO_INHERIT} policy (under rts-pthread)
24329 and @code{PTHREAD_PRIO_PROTECT}
24330 @cindex @code{PTHREAD_PRIO_PROTECT} policy (under rts-pthread)
24331 semantics that can be selected using the predefined pragma
24332 @code{Locking_Policy}
24333 @cindex pragma Locking_Policy (under rts-pthread)
24334 with respectively
24335 @code{Inheritance_Locking} and @code{Ceiling_Locking} as the policy.
24336 @cindex @code{Inheritance_Locking} (under rts-pthread)
24337 @cindex @code{Ceiling_Locking} (under rts-pthread)
24338
24339 As explained above, the native run-time library is based on the Solaris thread
24340 library (@code{libthread}) and is the default library.
24341
24342 When the Solaris threads library is used (this is the default), programs
24343 compiled with GNAT can automatically take advantage of
24344 and can thus execute on multiple processors.
24345 The user can alternatively specify a processor on which the program should run
24346 to emulate a single-processor system. The multiprocessor / uniprocessor choice
24347 is made by
24348 setting the environment variable @env{GNAT_PROCESSOR}
24349 @cindex @env{GNAT_PROCESSOR} environment variable (on Sparc Solaris)
24350 to one of the following:
24351
24352 @table @code
24353 @item -2
24354 Use the default configuration (run the program on all
24355 available processors) - this is the same as having @code{GNAT_PROCESSOR}
24356 unset
24357
24358 @item -1
24359 Let the run-time implementation choose one processor and run the program on
24360 that processor
24361
24362 @item 0 .. Last_Proc
24363 Run the program on the specified processor.
24364 @code{Last_Proc} is equal to @code{_SC_NPROCESSORS_CONF - 1}
24365 (where @code{_SC_NPROCESSORS_CONF} is a system variable).
24366 @end table
24367
24368 @node Linux-Specific Considerations
24369 @section Linux-Specific Considerations
24370 @cindex Linux threads libraries
24371
24372 @noindent
24373 On GNU/Linux without NPTL support (usually system with GNU C Library
24374 older than 2.3), the signal model is not POSIX compliant, which means
24375 that to send a signal to the process, you need to send the signal to all
24376 threads, e.g.@: by using @code{killpg()}.
24377
24378 @node AIX-Specific Considerations
24379 @section AIX-Specific Considerations
24380 @cindex AIX resolver library
24381
24382 @noindent
24383 On AIX, the resolver library initializes some internal structure on
24384 the first call to @code{get*by*} functions, which are used to implement
24385 @code{GNAT.Sockets.Get_Host_By_Name} and
24386 @code{GNAT.Sockets.Get_Host_By_Address}.
24387 If such initialization occurs within an Ada task, and the stack size for
24388 the task is the default size, a stack overflow may occur.
24389
24390 To avoid this overflow, the user should either ensure that the first call
24391 to @code{GNAT.Sockets.Get_Host_By_Name} or
24392 @code{GNAT.Sockets.Get_Host_By_Addrss}
24393 occurs in the environment task, or use @code{pragma Storage_Size} to
24394 specify a sufficiently large size for the stack of the task that contains
24395 this call.
24396
24397 @node RTX-Specific Considerations
24398 @section RTX-Specific Considerations
24399 @cindex RTX libraries
24400
24401 @noindent
24402 The Real-time Extension (RTX) to Windows is based on the Windows Win32
24403 API. Applications can be built to work in two different modes:
24404
24405 @itemize @bullet
24406 @item
24407 Windows executables that run in Ring 3 to utilize memory protection
24408 (@emph{rts-rtx-w32}).
24409
24410 @item
24411 Real-time subsystem (RTSS) executables that run in Ring 0, where
24412 performance can be optimized with RTSS applications taking precedent
24413 over all Windows applications (@emph{rts-rtx-rtss}). This mode requires
24414 the Microsoft linker to handle RTSS libraries.
24415
24416 @end itemize
24417
24418 @node HP-UX-Specific Considerations
24419 @section HP-UX-Specific Considerations
24420 @cindex HP-UX Scheduling
24421
24422 @noindent
24423 On HP-UX, appropriate privileges are required to change the scheduling
24424 parameters of a task. The calling process must have appropriate
24425 privileges or be a member of a group having @code{PRIV_RTSCHED} access to
24426 successfully change the scheduling parameters.
24427
24428 By default, GNAT uses the @code{SCHED_HPUX} policy. To have access to the
24429 priority range 0-31 either the @code{FIFO_Within_Priorities} or the
24430 @code{Round_Robin_Within_Priorities} scheduling policies need to be set.
24431
24432 To specify the @code{FIFO_Within_Priorities} scheduling policy you can use
24433 one of the following:
24434
24435 @itemize @bullet
24436 @item
24437 @code{pragma Time_Slice (0.0)}
24438 @cindex pragma Time_Slice
24439 @item
24440 the corresponding binder option @option{-T0}
24441 @cindex @option{-T0} option
24442 @item
24443 @code{pragma Task_Dispatching_Policy (FIFO_Within_Priorities)}
24444 @cindex pragma Task_Dispatching_Policy
24445 @end itemize
24446
24447 @noindent
24448 To specify the @code{Round_Robin_Within_Priorities}, scheduling policy
24449 you should use @code{pragma Time_Slice} with a
24450 value greater than @code{0.0}, or use the corresponding @option{-T}
24451 binder option, or set the @code{pragma Task_Dispatching_Policy
24452 (Round_Robin_Within_Priorities)}.
24453
24454 @c *******************************
24455 @node Example of Binder Output File
24456 @appendix Example of Binder Output File
24457
24458 @noindent
24459 This Appendix displays the source code for @command{gnatbind}'s output
24460 file generated for a simple ``Hello World'' program.
24461 Comments have been added for clarification purposes.
24462
24463 @smallexample @c adanocomment
24464 @iftex
24465 @leftskip=0cm
24466 @end iftex
24467 -- The package is called Ada_Main unless this name is actually used
24468 -- as a unit name in the partition, in which case some other unique
24469 -- name is used.
24470
24471 with System;
24472 package ada_main is
24473
24474 Elab_Final_Code : Integer;
24475 pragma Import (C, Elab_Final_Code, "__gnat_inside_elab_final_code");
24476
24477 -- The main program saves the parameters (argument count,
24478 -- argument values, environment pointer) in global variables
24479 -- for later access by other units including
24480 -- Ada.Command_Line.
24481
24482 gnat_argc : Integer;
24483 gnat_argv : System.Address;
24484 gnat_envp : System.Address;
24485
24486 -- The actual variables are stored in a library routine. This
24487 -- is useful for some shared library situations, where there
24488 -- are problems if variables are not in the library.
24489
24490 pragma Import (C, gnat_argc);
24491 pragma Import (C, gnat_argv);
24492 pragma Import (C, gnat_envp);
24493
24494 -- The exit status is similarly an external location
24495
24496 gnat_exit_status : Integer;
24497 pragma Import (C, gnat_exit_status);
24498
24499 GNAT_Version : constant String :=
24500 "GNAT Version: 6.0.0w (20061115)";
24501 pragma Export (C, GNAT_Version, "__gnat_version");
24502
24503 -- This is the generated adafinal routine that performs
24504 -- finalization at the end of execution. In the case where
24505 -- Ada is the main program, this main program makes a call
24506 -- to adafinal at program termination.
24507
24508 procedure adafinal;
24509 pragma Export (C, adafinal, "adafinal");
24510
24511 -- This is the generated adainit routine that performs
24512 -- initialization at the start of execution. In the case
24513 -- where Ada is the main program, this main program makes
24514 -- a call to adainit at program startup.
24515
24516 procedure adainit;
24517 pragma Export (C, adainit, "adainit");
24518
24519 -- This routine is called at the start of execution. It is
24520 -- a dummy routine that is used by the debugger to breakpoint
24521 -- at the start of execution.
24522
24523 procedure Break_Start;
24524 pragma Import (C, Break_Start, "__gnat_break_start");
24525
24526 -- This is the actual generated main program (it would be
24527 -- suppressed if the no main program switch were used). As
24528 -- required by standard system conventions, this program has
24529 -- the external name main.
24530
24531 function main
24532 (argc : Integer;
24533 argv : System.Address;
24534 envp : System.Address)
24535 return Integer;
24536 pragma Export (C, main, "main");
24537
24538 -- The following set of constants give the version
24539 -- identification values for every unit in the bound
24540 -- partition. This identification is computed from all
24541 -- dependent semantic units, and corresponds to the
24542 -- string that would be returned by use of the
24543 -- Body_Version or Version attributes.
24544
24545 type Version_32 is mod 2 ** 32;
24546 u00001 : constant Version_32 := 16#7880BEB3#;
24547 u00002 : constant Version_32 := 16#0D24CBD0#;
24548 u00003 : constant Version_32 := 16#3283DBEB#;
24549 u00004 : constant Version_32 := 16#2359F9ED#;
24550 u00005 : constant Version_32 := 16#664FB847#;
24551 u00006 : constant Version_32 := 16#68E803DF#;
24552 u00007 : constant Version_32 := 16#5572E604#;
24553 u00008 : constant Version_32 := 16#46B173D8#;
24554 u00009 : constant Version_32 := 16#156A40CF#;
24555 u00010 : constant Version_32 := 16#033DABE0#;
24556 u00011 : constant Version_32 := 16#6AB38FEA#;
24557 u00012 : constant Version_32 := 16#22B6217D#;
24558 u00013 : constant Version_32 := 16#68A22947#;
24559 u00014 : constant Version_32 := 16#18CC4A56#;
24560 u00015 : constant Version_32 := 16#08258E1B#;
24561 u00016 : constant Version_32 := 16#367D5222#;
24562 u00017 : constant Version_32 := 16#20C9ECA4#;
24563 u00018 : constant Version_32 := 16#50D32CB6#;
24564 u00019 : constant Version_32 := 16#39A8BB77#;
24565 u00020 : constant Version_32 := 16#5CF8FA2B#;
24566 u00021 : constant Version_32 := 16#2F1EB794#;
24567 u00022 : constant Version_32 := 16#31AB6444#;
24568 u00023 : constant Version_32 := 16#1574B6E9#;
24569 u00024 : constant Version_32 := 16#5109C189#;
24570 u00025 : constant Version_32 := 16#56D770CD#;
24571 u00026 : constant Version_32 := 16#02F9DE3D#;
24572 u00027 : constant Version_32 := 16#08AB6B2C#;
24573 u00028 : constant Version_32 := 16#3FA37670#;
24574 u00029 : constant Version_32 := 16#476457A0#;
24575 u00030 : constant Version_32 := 16#731E1B6E#;
24576 u00031 : constant Version_32 := 16#23C2E789#;
24577 u00032 : constant Version_32 := 16#0F1BD6A1#;
24578 u00033 : constant Version_32 := 16#7C25DE96#;
24579 u00034 : constant Version_32 := 16#39ADFFA2#;
24580 u00035 : constant Version_32 := 16#571DE3E7#;
24581 u00036 : constant Version_32 := 16#5EB646AB#;
24582 u00037 : constant Version_32 := 16#4249379B#;
24583 u00038 : constant Version_32 := 16#0357E00A#;
24584 u00039 : constant Version_32 := 16#3784FB72#;
24585 u00040 : constant Version_32 := 16#2E723019#;
24586 u00041 : constant Version_32 := 16#623358EA#;
24587 u00042 : constant Version_32 := 16#107F9465#;
24588 u00043 : constant Version_32 := 16#6843F68A#;
24589 u00044 : constant Version_32 := 16#63305874#;
24590 u00045 : constant Version_32 := 16#31E56CE1#;
24591 u00046 : constant Version_32 := 16#02917970#;
24592 u00047 : constant Version_32 := 16#6CCBA70E#;
24593 u00048 : constant Version_32 := 16#41CD4204#;
24594 u00049 : constant Version_32 := 16#572E3F58#;
24595 u00050 : constant Version_32 := 16#20729FF5#;
24596 u00051 : constant Version_32 := 16#1D4F93E8#;
24597 u00052 : constant Version_32 := 16#30B2EC3D#;
24598 u00053 : constant Version_32 := 16#34054F96#;
24599 u00054 : constant Version_32 := 16#5A199860#;
24600 u00055 : constant Version_32 := 16#0E7F912B#;
24601 u00056 : constant Version_32 := 16#5760634A#;
24602 u00057 : constant Version_32 := 16#5D851835#;
24603
24604 -- The following Export pragmas export the version numbers
24605 -- with symbolic names ending in B (for body) or S
24606 -- (for spec) so that they can be located in a link. The
24607 -- information provided here is sufficient to track down
24608 -- the exact versions of units used in a given build.
24609
24610 pragma Export (C, u00001, "helloB");
24611 pragma Export (C, u00002, "system__standard_libraryB");
24612 pragma Export (C, u00003, "system__standard_libraryS");
24613 pragma Export (C, u00004, "adaS");
24614 pragma Export (C, u00005, "ada__text_ioB");
24615 pragma Export (C, u00006, "ada__text_ioS");
24616 pragma Export (C, u00007, "ada__exceptionsB");
24617 pragma Export (C, u00008, "ada__exceptionsS");
24618 pragma Export (C, u00009, "gnatS");
24619 pragma Export (C, u00010, "gnat__heap_sort_aB");
24620 pragma Export (C, u00011, "gnat__heap_sort_aS");
24621 pragma Export (C, u00012, "systemS");
24622 pragma Export (C, u00013, "system__exception_tableB");
24623 pragma Export (C, u00014, "system__exception_tableS");
24624 pragma Export (C, u00015, "gnat__htableB");
24625 pragma Export (C, u00016, "gnat__htableS");
24626 pragma Export (C, u00017, "system__exceptionsS");
24627 pragma Export (C, u00018, "system__machine_state_operationsB");
24628 pragma Export (C, u00019, "system__machine_state_operationsS");
24629 pragma Export (C, u00020, "system__machine_codeS");
24630 pragma Export (C, u00021, "system__storage_elementsB");
24631 pragma Export (C, u00022, "system__storage_elementsS");
24632 pragma Export (C, u00023, "system__secondary_stackB");
24633 pragma Export (C, u00024, "system__secondary_stackS");
24634 pragma Export (C, u00025, "system__parametersB");
24635 pragma Export (C, u00026, "system__parametersS");
24636 pragma Export (C, u00027, "system__soft_linksB");
24637 pragma Export (C, u00028, "system__soft_linksS");
24638 pragma Export (C, u00029, "system__stack_checkingB");
24639 pragma Export (C, u00030, "system__stack_checkingS");
24640 pragma Export (C, u00031, "system__tracebackB");
24641 pragma Export (C, u00032, "system__tracebackS");
24642 pragma Export (C, u00033, "ada__streamsS");
24643 pragma Export (C, u00034, "ada__tagsB");
24644 pragma Export (C, u00035, "ada__tagsS");
24645 pragma Export (C, u00036, "system__string_opsB");
24646 pragma Export (C, u00037, "system__string_opsS");
24647 pragma Export (C, u00038, "interfacesS");
24648 pragma Export (C, u00039, "interfaces__c_streamsB");
24649 pragma Export (C, u00040, "interfaces__c_streamsS");
24650 pragma Export (C, u00041, "system__file_ioB");
24651 pragma Export (C, u00042, "system__file_ioS");
24652 pragma Export (C, u00043, "ada__finalizationB");
24653 pragma Export (C, u00044, "ada__finalizationS");
24654 pragma Export (C, u00045, "system__finalization_rootB");
24655 pragma Export (C, u00046, "system__finalization_rootS");
24656 pragma Export (C, u00047, "system__finalization_implementationB");
24657 pragma Export (C, u00048, "system__finalization_implementationS");
24658 pragma Export (C, u00049, "system__string_ops_concat_3B");
24659 pragma Export (C, u00050, "system__string_ops_concat_3S");
24660 pragma Export (C, u00051, "system__stream_attributesB");
24661 pragma Export (C, u00052, "system__stream_attributesS");
24662 pragma Export (C, u00053, "ada__io_exceptionsS");
24663 pragma Export (C, u00054, "system__unsigned_typesS");
24664 pragma Export (C, u00055, "system__file_control_blockS");
24665 pragma Export (C, u00056, "ada__finalization__list_controllerB");
24666 pragma Export (C, u00057, "ada__finalization__list_controllerS");
24667
24668 -- BEGIN ELABORATION ORDER
24669 -- ada (spec)
24670 -- gnat (spec)
24671 -- gnat.heap_sort_a (spec)
24672 -- gnat.heap_sort_a (body)
24673 -- gnat.htable (spec)
24674 -- gnat.htable (body)
24675 -- interfaces (spec)
24676 -- system (spec)
24677 -- system.machine_code (spec)
24678 -- system.parameters (spec)
24679 -- system.parameters (body)
24680 -- interfaces.c_streams (spec)
24681 -- interfaces.c_streams (body)
24682 -- system.standard_library (spec)
24683 -- ada.exceptions (spec)
24684 -- system.exception_table (spec)
24685 -- system.exception_table (body)
24686 -- ada.io_exceptions (spec)
24687 -- system.exceptions (spec)
24688 -- system.storage_elements (spec)
24689 -- system.storage_elements (body)
24690 -- system.machine_state_operations (spec)
24691 -- system.machine_state_operations (body)
24692 -- system.secondary_stack (spec)
24693 -- system.stack_checking (spec)
24694 -- system.soft_links (spec)
24695 -- system.soft_links (body)
24696 -- system.stack_checking (body)
24697 -- system.secondary_stack (body)
24698 -- system.standard_library (body)
24699 -- system.string_ops (spec)
24700 -- system.string_ops (body)
24701 -- ada.tags (spec)
24702 -- ada.tags (body)
24703 -- ada.streams (spec)
24704 -- system.finalization_root (spec)
24705 -- system.finalization_root (body)
24706 -- system.string_ops_concat_3 (spec)
24707 -- system.string_ops_concat_3 (body)
24708 -- system.traceback (spec)
24709 -- system.traceback (body)
24710 -- ada.exceptions (body)
24711 -- system.unsigned_types (spec)
24712 -- system.stream_attributes (spec)
24713 -- system.stream_attributes (body)
24714 -- system.finalization_implementation (spec)
24715 -- system.finalization_implementation (body)
24716 -- ada.finalization (spec)
24717 -- ada.finalization (body)
24718 -- ada.finalization.list_controller (spec)
24719 -- ada.finalization.list_controller (body)
24720 -- system.file_control_block (spec)
24721 -- system.file_io (spec)
24722 -- system.file_io (body)
24723 -- ada.text_io (spec)
24724 -- ada.text_io (body)
24725 -- hello (body)
24726 -- END ELABORATION ORDER
24727
24728 end ada_main;
24729
24730 -- The following source file name pragmas allow the generated file
24731 -- names to be unique for different main programs. They are needed
24732 -- since the package name will always be Ada_Main.
24733
24734 pragma Source_File_Name (ada_main, Spec_File_Name => "b~hello.ads");
24735 pragma Source_File_Name (ada_main, Body_File_Name => "b~hello.adb");
24736
24737 -- Generated package body for Ada_Main starts here
24738
24739 package body ada_main is
24740
24741 -- The actual finalization is performed by calling the
24742 -- library routine in System.Standard_Library.Adafinal
24743
24744 procedure Do_Finalize;
24745 pragma Import (C, Do_Finalize, "system__standard_library__adafinal");
24746
24747 -------------
24748 -- adainit --
24749 -------------
24750
24751 @findex adainit
24752 procedure adainit is
24753
24754 -- These booleans are set to True once the associated unit has
24755 -- been elaborated. It is also used to avoid elaborating the
24756 -- same unit twice.
24757
24758 E040 : Boolean;
24759 pragma Import (Ada, E040, "interfaces__c_streams_E");
24760
24761 E008 : Boolean;
24762 pragma Import (Ada, E008, "ada__exceptions_E");
24763
24764 E014 : Boolean;
24765 pragma Import (Ada, E014, "system__exception_table_E");
24766
24767 E053 : Boolean;
24768 pragma Import (Ada, E053, "ada__io_exceptions_E");
24769
24770 E017 : Boolean;
24771 pragma Import (Ada, E017, "system__exceptions_E");
24772
24773 E024 : Boolean;
24774 pragma Import (Ada, E024, "system__secondary_stack_E");
24775
24776 E030 : Boolean;
24777 pragma Import (Ada, E030, "system__stack_checking_E");
24778
24779 E028 : Boolean;
24780 pragma Import (Ada, E028, "system__soft_links_E");
24781
24782 E035 : Boolean;
24783 pragma Import (Ada, E035, "ada__tags_E");
24784
24785 E033 : Boolean;
24786 pragma Import (Ada, E033, "ada__streams_E");
24787
24788 E046 : Boolean;
24789 pragma Import (Ada, E046, "system__finalization_root_E");
24790
24791 E048 : Boolean;
24792 pragma Import (Ada, E048, "system__finalization_implementation_E");
24793
24794 E044 : Boolean;
24795 pragma Import (Ada, E044, "ada__finalization_E");
24796
24797 E057 : Boolean;
24798 pragma Import (Ada, E057, "ada__finalization__list_controller_E");
24799
24800 E055 : Boolean;
24801 pragma Import (Ada, E055, "system__file_control_block_E");
24802
24803 E042 : Boolean;
24804 pragma Import (Ada, E042, "system__file_io_E");
24805
24806 E006 : Boolean;
24807 pragma Import (Ada, E006, "ada__text_io_E");
24808
24809 -- Set_Globals is a library routine that stores away the
24810 -- value of the indicated set of global values in global
24811 -- variables within the library.
24812
24813 procedure Set_Globals
24814 (Main_Priority : Integer;
24815 Time_Slice_Value : Integer;
24816 WC_Encoding : Character;
24817 Locking_Policy : Character;
24818 Queuing_Policy : Character;
24819 Task_Dispatching_Policy : Character;
24820 Adafinal : System.Address;
24821 Unreserve_All_Interrupts : Integer;
24822 Exception_Tracebacks : Integer);
24823 @findex __gnat_set_globals
24824 pragma Import (C, Set_Globals, "__gnat_set_globals");
24825
24826 -- SDP_Table_Build is a library routine used to build the
24827 -- exception tables. See unit Ada.Exceptions in files
24828 -- a-except.ads/adb for full details of how zero cost
24829 -- exception handling works. This procedure, the call to
24830 -- it, and the two following tables are all omitted if the
24831 -- build is in longjmp/setjmp exception mode.
24832
24833 @findex SDP_Table_Build
24834 @findex Zero Cost Exceptions
24835 procedure SDP_Table_Build
24836 (SDP_Addresses : System.Address;
24837 SDP_Count : Natural;
24838 Elab_Addresses : System.Address;
24839 Elab_Addr_Count : Natural);
24840 pragma Import (C, SDP_Table_Build, "__gnat_SDP_Table_Build");
24841
24842 -- Table of Unit_Exception_Table addresses. Used for zero
24843 -- cost exception handling to build the top level table.
24844
24845 ST : aliased constant array (1 .. 23) of System.Address := (
24846 Hello'UET_Address,
24847 Ada.Text_Io'UET_Address,
24848 Ada.Exceptions'UET_Address,
24849 Gnat.Heap_Sort_A'UET_Address,
24850 System.Exception_Table'UET_Address,
24851 System.Machine_State_Operations'UET_Address,
24852 System.Secondary_Stack'UET_Address,
24853 System.Parameters'UET_Address,
24854 System.Soft_Links'UET_Address,
24855 System.Stack_Checking'UET_Address,
24856 System.Traceback'UET_Address,
24857 Ada.Streams'UET_Address,
24858 Ada.Tags'UET_Address,
24859 System.String_Ops'UET_Address,
24860 Interfaces.C_Streams'UET_Address,
24861 System.File_Io'UET_Address,
24862 Ada.Finalization'UET_Address,
24863 System.Finalization_Root'UET_Address,
24864 System.Finalization_Implementation'UET_Address,
24865 System.String_Ops_Concat_3'UET_Address,
24866 System.Stream_Attributes'UET_Address,
24867 System.File_Control_Block'UET_Address,
24868 Ada.Finalization.List_Controller'UET_Address);
24869
24870 -- Table of addresses of elaboration routines. Used for
24871 -- zero cost exception handling to make sure these
24872 -- addresses are included in the top level procedure
24873 -- address table.
24874
24875 EA : aliased constant array (1 .. 23) of System.Address := (
24876 adainit'Code_Address,
24877 Do_Finalize'Code_Address,
24878 Ada.Exceptions'Elab_Spec'Address,
24879 System.Exceptions'Elab_Spec'Address,
24880 Interfaces.C_Streams'Elab_Spec'Address,
24881 System.Exception_Table'Elab_Body'Address,
24882 Ada.Io_Exceptions'Elab_Spec'Address,
24883 System.Stack_Checking'Elab_Spec'Address,
24884 System.Soft_Links'Elab_Body'Address,
24885 System.Secondary_Stack'Elab_Body'Address,
24886 Ada.Tags'Elab_Spec'Address,
24887 Ada.Tags'Elab_Body'Address,
24888 Ada.Streams'Elab_Spec'Address,
24889 System.Finalization_Root'Elab_Spec'Address,
24890 Ada.Exceptions'Elab_Body'Address,
24891 System.Finalization_Implementation'Elab_Spec'Address,
24892 System.Finalization_Implementation'Elab_Body'Address,
24893 Ada.Finalization'Elab_Spec'Address,
24894 Ada.Finalization.List_Controller'Elab_Spec'Address,
24895 System.File_Control_Block'Elab_Spec'Address,
24896 System.File_Io'Elab_Body'Address,
24897 Ada.Text_Io'Elab_Spec'Address,
24898 Ada.Text_Io'Elab_Body'Address);
24899
24900 -- Start of processing for adainit
24901
24902 begin
24903
24904 -- Call SDP_Table_Build to build the top level procedure
24905 -- table for zero cost exception handling (omitted in
24906 -- longjmp/setjmp mode).
24907
24908 SDP_Table_Build (ST'Address, 23, EA'Address, 23);
24909
24910 -- Call Set_Globals to record various information for
24911 -- this partition. The values are derived by the binder
24912 -- from information stored in the ali files by the compiler.
24913
24914 @findex __gnat_set_globals
24915 Set_Globals
24916 (Main_Priority => -1,
24917 -- Priority of main program, -1 if no pragma Priority used
24918
24919 Time_Slice_Value => -1,
24920 -- Time slice from Time_Slice pragma, -1 if none used
24921
24922 WC_Encoding => 'b',
24923 -- Wide_Character encoding used, default is brackets
24924
24925 Locking_Policy => ' ',
24926 -- Locking_Policy used, default of space means not
24927 -- specified, otherwise it is the first character of
24928 -- the policy name.
24929
24930 Queuing_Policy => ' ',
24931 -- Queuing_Policy used, default of space means not
24932 -- specified, otherwise it is the first character of
24933 -- the policy name.
24934
24935 Task_Dispatching_Policy => ' ',
24936 -- Task_Dispatching_Policy used, default of space means
24937 -- not specified, otherwise first character of the
24938 -- policy name.
24939
24940 Adafinal => System.Null_Address,
24941 -- Address of Adafinal routine, not used anymore
24942
24943 Unreserve_All_Interrupts => 0,
24944 -- Set true if pragma Unreserve_All_Interrupts was used
24945
24946 Exception_Tracebacks => 0);
24947 -- Indicates if exception tracebacks are enabled
24948
24949 Elab_Final_Code := 1;
24950
24951 -- Now we have the elaboration calls for all units in the partition.
24952 -- The Elab_Spec and Elab_Body attributes generate references to the
24953 -- implicit elaboration procedures generated by the compiler for
24954 -- each unit that requires elaboration.
24955
24956 if not E040 then
24957 Interfaces.C_Streams'Elab_Spec;
24958 end if;
24959 E040 := True;
24960 if not E008 then
24961 Ada.Exceptions'Elab_Spec;
24962 end if;
24963 if not E014 then
24964 System.Exception_Table'Elab_Body;
24965 E014 := True;
24966 end if;
24967 if not E053 then
24968 Ada.Io_Exceptions'Elab_Spec;
24969 E053 := True;
24970 end if;
24971 if not E017 then
24972 System.Exceptions'Elab_Spec;
24973 E017 := True;
24974 end if;
24975 if not E030 then
24976 System.Stack_Checking'Elab_Spec;
24977 end if;
24978 if not E028 then
24979 System.Soft_Links'Elab_Body;
24980 E028 := True;
24981 end if;
24982 E030 := True;
24983 if not E024 then
24984 System.Secondary_Stack'Elab_Body;
24985 E024 := True;
24986 end if;
24987 if not E035 then
24988 Ada.Tags'Elab_Spec;
24989 end if;
24990 if not E035 then
24991 Ada.Tags'Elab_Body;
24992 E035 := True;
24993 end if;
24994 if not E033 then
24995 Ada.Streams'Elab_Spec;
24996 E033 := True;
24997 end if;
24998 if not E046 then
24999 System.Finalization_Root'Elab_Spec;
25000 end if;
25001 E046 := True;
25002 if not E008 then
25003 Ada.Exceptions'Elab_Body;
25004 E008 := True;
25005 end if;
25006 if not E048 then
25007 System.Finalization_Implementation'Elab_Spec;
25008 end if;
25009 if not E048 then
25010 System.Finalization_Implementation'Elab_Body;
25011 E048 := True;
25012 end if;
25013 if not E044 then
25014 Ada.Finalization'Elab_Spec;
25015 end if;
25016 E044 := True;
25017 if not E057 then
25018 Ada.Finalization.List_Controller'Elab_Spec;
25019 end if;
25020 E057 := True;
25021 if not E055 then
25022 System.File_Control_Block'Elab_Spec;
25023 E055 := True;
25024 end if;
25025 if not E042 then
25026 System.File_Io'Elab_Body;
25027 E042 := True;
25028 end if;
25029 if not E006 then
25030 Ada.Text_Io'Elab_Spec;
25031 end if;
25032 if not E006 then
25033 Ada.Text_Io'Elab_Body;
25034 E006 := True;
25035 end if;
25036
25037 Elab_Final_Code := 0;
25038 end adainit;
25039
25040 --------------
25041 -- adafinal --
25042 --------------
25043
25044 @findex adafinal
25045 procedure adafinal is
25046 begin
25047 Do_Finalize;
25048 end adafinal;
25049
25050 ----------
25051 -- main --
25052 ----------
25053
25054 -- main is actually a function, as in the ANSI C standard,
25055 -- defined to return the exit status. The three parameters
25056 -- are the argument count, argument values and environment
25057 -- pointer.
25058
25059 @findex Main Program
25060 function main
25061 (argc : Integer;
25062 argv : System.Address;
25063 envp : System.Address)
25064 return Integer
25065 is
25066 -- The initialize routine performs low level system
25067 -- initialization using a standard library routine which
25068 -- sets up signal handling and performs any other
25069 -- required setup. The routine can be found in file
25070 -- a-init.c.
25071
25072 @findex __gnat_initialize
25073 procedure initialize;
25074 pragma Import (C, initialize, "__gnat_initialize");
25075
25076 -- The finalize routine performs low level system
25077 -- finalization using a standard library routine. The
25078 -- routine is found in file a-final.c and in the standard
25079 -- distribution is a dummy routine that does nothing, so
25080 -- really this is a hook for special user finalization.
25081
25082 @findex __gnat_finalize
25083 procedure finalize;
25084 pragma Import (C, finalize, "__gnat_finalize");
25085
25086 -- We get to the main program of the partition by using
25087 -- pragma Import because if we try to with the unit and
25088 -- call it Ada style, then not only do we waste time
25089 -- recompiling it, but also, we don't really know the right
25090 -- switches (e.g.@: identifier character set) to be used
25091 -- to compile it.
25092
25093 procedure Ada_Main_Program;
25094 pragma Import (Ada, Ada_Main_Program, "_ada_hello");
25095
25096 -- Start of processing for main
25097
25098 begin
25099 -- Save global variables
25100
25101 gnat_argc := argc;
25102 gnat_argv := argv;
25103 gnat_envp := envp;
25104
25105 -- Call low level system initialization
25106
25107 Initialize;
25108
25109 -- Call our generated Ada initialization routine
25110
25111 adainit;
25112
25113 -- This is the point at which we want the debugger to get
25114 -- control
25115
25116 Break_Start;
25117
25118 -- Now we call the main program of the partition
25119
25120 Ada_Main_Program;
25121
25122 -- Perform Ada finalization
25123
25124 adafinal;
25125
25126 -- Perform low level system finalization
25127
25128 Finalize;
25129
25130 -- Return the proper exit status
25131 return (gnat_exit_status);
25132 end;
25133
25134 -- This section is entirely comments, so it has no effect on the
25135 -- compilation of the Ada_Main package. It provides the list of
25136 -- object files and linker options, as well as some standard
25137 -- libraries needed for the link. The gnatlink utility parses
25138 -- this b~hello.adb file to read these comment lines to generate
25139 -- the appropriate command line arguments for the call to the
25140 -- system linker. The BEGIN/END lines are used for sentinels for
25141 -- this parsing operation.
25142
25143 -- The exact file names will of course depend on the environment,
25144 -- host/target and location of files on the host system.
25145
25146 @findex Object file list
25147 -- BEGIN Object file/option list
25148 -- ./hello.o
25149 -- -L./
25150 -- -L/usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/
25151 -- /usr/local/gnat/lib/gcc-lib/i686-pc-linux-gnu/2.8.1/adalib/libgnat.a
25152 -- END Object file/option list
25153
25154 end ada_main;
25155 @end smallexample
25156
25157 @noindent
25158 The Ada code in the above example is exactly what is generated by the
25159 binder. We have added comments to more clearly indicate the function
25160 of each part of the generated @code{Ada_Main} package.
25161
25162 The code is standard Ada in all respects, and can be processed by any
25163 tools that handle Ada. In particular, it is possible to use the debugger
25164 in Ada mode to debug the generated @code{Ada_Main} package. For example,
25165 suppose that for reasons that you do not understand, your program is crashing
25166 during elaboration of the body of @code{Ada.Text_IO}. To locate this bug,
25167 you can place a breakpoint on the call:
25168
25169 @smallexample @c ada
25170 Ada.Text_Io'Elab_Body;
25171 @end smallexample
25172
25173 @noindent
25174 and trace the elaboration routine for this package to find out where
25175 the problem might be (more usually of course you would be debugging
25176 elaboration code in your own application).
25177
25178 @node Elaboration Order Handling in GNAT
25179 @appendix Elaboration Order Handling in GNAT
25180 @cindex Order of elaboration
25181 @cindex Elaboration control
25182
25183 @menu
25184 * Elaboration Code::
25185 * Checking the Elaboration Order::
25186 * Controlling the Elaboration Order::
25187 * Controlling Elaboration in GNAT - Internal Calls::
25188 * Controlling Elaboration in GNAT - External Calls::
25189 * Default Behavior in GNAT - Ensuring Safety::
25190 * Treatment of Pragma Elaborate::
25191 * Elaboration Issues for Library Tasks::
25192 * Mixing Elaboration Models::
25193 * What to Do If the Default Elaboration Behavior Fails::
25194 * Elaboration for Indirect Calls::
25195 * Summary of Procedures for Elaboration Control::
25196 * Other Elaboration Order Considerations::
25197 * Determining the Chosen Elaboration Order::
25198 @end menu
25199
25200 @noindent
25201 This chapter describes the handling of elaboration code in Ada and
25202 in GNAT, and discusses how the order of elaboration of program units can
25203 be controlled in GNAT, either automatically or with explicit programming
25204 features.
25205
25206 @node Elaboration Code
25207 @section Elaboration Code
25208
25209 @noindent
25210 Ada provides rather general mechanisms for executing code at elaboration
25211 time, that is to say before the main program starts executing. Such code arises
25212 in three contexts:
25213
25214 @table @asis
25215 @item Initializers for variables.
25216 Variables declared at the library level, in package specs or bodies, can
25217 require initialization that is performed at elaboration time, as in:
25218 @smallexample @c ada
25219 @cartouche
25220 Sqrt_Half : Float := Sqrt (0.5);
25221 @end cartouche
25222 @end smallexample
25223
25224 @item Package initialization code
25225 Code in a @code{BEGIN-END} section at the outer level of a package body is
25226 executed as part of the package body elaboration code.
25227
25228 @item Library level task allocators
25229 Tasks that are declared using task allocators at the library level
25230 start executing immediately and hence can execute at elaboration time.
25231 @end table
25232
25233 @noindent
25234 Subprogram calls are possible in any of these contexts, which means that
25235 any arbitrary part of the program may be executed as part of the elaboration
25236 code. It is even possible to write a program which does all its work at
25237 elaboration time, with a null main program, although stylistically this
25238 would usually be considered an inappropriate way to structure
25239 a program.
25240
25241 An important concern arises in the context of elaboration code:
25242 we have to be sure that it is executed in an appropriate order. What we
25243 have is a series of elaboration code sections, potentially one section
25244 for each unit in the program. It is important that these execute
25245 in the correct order. Correctness here means that, taking the above
25246 example of the declaration of @code{Sqrt_Half},
25247 if some other piece of
25248 elaboration code references @code{Sqrt_Half},
25249 then it must run after the
25250 section of elaboration code that contains the declaration of
25251 @code{Sqrt_Half}.
25252
25253 There would never be any order of elaboration problem if we made a rule
25254 that whenever you @code{with} a unit, you must elaborate both the spec and body
25255 of that unit before elaborating the unit doing the @code{with}'ing:
25256
25257 @smallexample @c ada
25258 @group
25259 @cartouche
25260 with Unit_1;
25261 package Unit_2 is @dots{}
25262 @end cartouche
25263 @end group
25264 @end smallexample
25265
25266 @noindent
25267 would require that both the body and spec of @code{Unit_1} be elaborated
25268 before the spec of @code{Unit_2}. However, a rule like that would be far too
25269 restrictive. In particular, it would make it impossible to have routines
25270 in separate packages that were mutually recursive.
25271
25272 You might think that a clever enough compiler could look at the actual
25273 elaboration code and determine an appropriate correct order of elaboration,
25274 but in the general case, this is not possible. Consider the following
25275 example.
25276
25277 In the body of @code{Unit_1}, we have a procedure @code{Func_1}
25278 that references
25279 the variable @code{Sqrt_1}, which is declared in the elaboration code
25280 of the body of @code{Unit_1}:
25281
25282 @smallexample @c ada
25283 @cartouche
25284 Sqrt_1 : Float := Sqrt (0.1);
25285 @end cartouche
25286 @end smallexample
25287
25288 @noindent
25289 The elaboration code of the body of @code{Unit_1} also contains:
25290
25291 @smallexample @c ada
25292 @group
25293 @cartouche
25294 if expression_1 = 1 then
25295 Q := Unit_2.Func_2;
25296 end if;
25297 @end cartouche
25298 @end group
25299 @end smallexample
25300
25301 @noindent
25302 @code{Unit_2} is exactly parallel,
25303 it has a procedure @code{Func_2} that references
25304 the variable @code{Sqrt_2}, which is declared in the elaboration code of
25305 the body @code{Unit_2}:
25306
25307 @smallexample @c ada
25308 @cartouche
25309 Sqrt_2 : Float := Sqrt (0.1);
25310 @end cartouche
25311 @end smallexample
25312
25313 @noindent
25314 The elaboration code of the body of @code{Unit_2} also contains:
25315
25316 @smallexample @c ada
25317 @group
25318 @cartouche
25319 if expression_2 = 2 then
25320 Q := Unit_1.Func_1;
25321 end if;
25322 @end cartouche
25323 @end group
25324 @end smallexample
25325
25326 @noindent
25327 Now the question is, which of the following orders of elaboration is
25328 acceptable:
25329
25330 @smallexample
25331 @group
25332 Spec of Unit_1
25333 Spec of Unit_2
25334 Body of Unit_1
25335 Body of Unit_2
25336 @end group
25337 @end smallexample
25338
25339 @noindent
25340 or
25341
25342 @smallexample
25343 @group
25344 Spec of Unit_2
25345 Spec of Unit_1
25346 Body of Unit_2
25347 Body of Unit_1
25348 @end group
25349 @end smallexample
25350
25351 @noindent
25352 If you carefully analyze the flow here, you will see that you cannot tell
25353 at compile time the answer to this question.
25354 If @code{expression_1} is not equal to 1,
25355 and @code{expression_2} is not equal to 2,
25356 then either order is acceptable, because neither of the function calls is
25357 executed. If both tests evaluate to true, then neither order is acceptable
25358 and in fact there is no correct order.
25359
25360 If one of the two expressions is true, and the other is false, then one
25361 of the above orders is correct, and the other is incorrect. For example,
25362 if @code{expression_1} /= 1 and @code{expression_2} = 2,
25363 then the call to @code{Func_1}
25364 will occur, but not the call to @code{Func_2.}
25365 This means that it is essential
25366 to elaborate the body of @code{Unit_1} before
25367 the body of @code{Unit_2}, so the first
25368 order of elaboration is correct and the second is wrong.
25369
25370 By making @code{expression_1} and @code{expression_2}
25371 depend on input data, or perhaps
25372 the time of day, we can make it impossible for the compiler or binder
25373 to figure out which of these expressions will be true, and hence it
25374 is impossible to guarantee a safe order of elaboration at run time.
25375
25376 @node Checking the Elaboration Order
25377 @section Checking the Elaboration Order
25378
25379 @noindent
25380 In some languages that involve the same kind of elaboration problems,
25381 e.g.@: Java and C++, the programmer is expected to worry about these
25382 ordering problems himself, and it is common to
25383 write a program in which an incorrect elaboration order gives
25384 surprising results, because it references variables before they
25385 are initialized.
25386 Ada is designed to be a safe language, and a programmer-beware approach is
25387 clearly not sufficient. Consequently, the language provides three lines
25388 of defense:
25389
25390 @table @asis
25391 @item Standard rules
25392 Some standard rules restrict the possible choice of elaboration
25393 order. In particular, if you @code{with} a unit, then its spec is always
25394 elaborated before the unit doing the @code{with}. Similarly, a parent
25395 spec is always elaborated before the child spec, and finally
25396 a spec is always elaborated before its corresponding body.
25397
25398 @item Dynamic elaboration checks
25399 @cindex Elaboration checks
25400 @cindex Checks, elaboration
25401 Dynamic checks are made at run time, so that if some entity is accessed
25402 before it is elaborated (typically by means of a subprogram call)
25403 then the exception (@code{Program_Error}) is raised.
25404
25405 @item Elaboration control
25406 Facilities are provided for the programmer to specify the desired order
25407 of elaboration.
25408 @end table
25409
25410 Let's look at these facilities in more detail. First, the rules for
25411 dynamic checking. One possible rule would be simply to say that the
25412 exception is raised if you access a variable which has not yet been
25413 elaborated. The trouble with this approach is that it could require
25414 expensive checks on every variable reference. Instead Ada has two
25415 rules which are a little more restrictive, but easier to check, and
25416 easier to state:
25417
25418 @table @asis
25419 @item Restrictions on calls
25420 A subprogram can only be called at elaboration time if its body
25421 has been elaborated. The rules for elaboration given above guarantee
25422 that the spec of the subprogram has been elaborated before the
25423 call, but not the body. If this rule is violated, then the
25424 exception @code{Program_Error} is raised.
25425
25426 @item Restrictions on instantiations
25427 A generic unit can only be instantiated if the body of the generic
25428 unit has been elaborated. Again, the rules for elaboration given above
25429 guarantee that the spec of the generic unit has been elaborated
25430 before the instantiation, but not the body. If this rule is
25431 violated, then the exception @code{Program_Error} is raised.
25432 @end table
25433
25434 @noindent
25435 The idea is that if the body has been elaborated, then any variables
25436 it references must have been elaborated; by checking for the body being
25437 elaborated we guarantee that none of its references causes any
25438 trouble. As we noted above, this is a little too restrictive, because a
25439 subprogram that has no non-local references in its body may in fact be safe
25440 to call. However, it really would be unsafe to rely on this, because
25441 it would mean that the caller was aware of details of the implementation
25442 in the body. This goes against the basic tenets of Ada.
25443
25444 A plausible implementation can be described as follows.
25445 A Boolean variable is associated with each subprogram
25446 and each generic unit. This variable is initialized to False, and is set to
25447 True at the point body is elaborated. Every call or instantiation checks the
25448 variable, and raises @code{Program_Error} if the variable is False.
25449
25450 Note that one might think that it would be good enough to have one Boolean
25451 variable for each package, but that would not deal with cases of trying
25452 to call a body in the same package as the call
25453 that has not been elaborated yet.
25454 Of course a compiler may be able to do enough analysis to optimize away
25455 some of the Boolean variables as unnecessary, and @code{GNAT} indeed
25456 does such optimizations, but still the easiest conceptual model is to
25457 think of there being one variable per subprogram.
25458
25459 @node Controlling the Elaboration Order
25460 @section Controlling the Elaboration Order
25461
25462 @noindent
25463 In the previous section we discussed the rules in Ada which ensure
25464 that @code{Program_Error} is raised if an incorrect elaboration order is
25465 chosen. This prevents erroneous executions, but we need mechanisms to
25466 specify a correct execution and avoid the exception altogether.
25467 To achieve this, Ada provides a number of features for controlling
25468 the order of elaboration. We discuss these features in this section.
25469
25470 First, there are several ways of indicating to the compiler that a given
25471 unit has no elaboration problems:
25472
25473 @table @asis
25474 @item packages that do not require a body
25475 A library package that does not require a body does not permit
25476 a body (this rule was introduced in Ada 95).
25477 Thus if we have a such a package, as in:
25478
25479 @smallexample @c ada
25480 @group
25481 @cartouche
25482 package Definitions is
25483 generic
25484 type m is new integer;
25485 package Subp is
25486 type a is array (1 .. 10) of m;
25487 type b is array (1 .. 20) of m;
25488 end Subp;
25489 end Definitions;
25490 @end cartouche
25491 @end group
25492 @end smallexample
25493
25494 @noindent
25495 A package that @code{with}'s @code{Definitions} may safely instantiate
25496 @code{Definitions.Subp} because the compiler can determine that there
25497 definitely is no package body to worry about in this case
25498
25499 @item pragma Pure
25500 @cindex pragma Pure
25501 @findex Pure
25502 Places sufficient restrictions on a unit to guarantee that
25503 no call to any subprogram in the unit can result in an
25504 elaboration problem. This means that the compiler does not need
25505 to worry about the point of elaboration of such units, and in
25506 particular, does not need to check any calls to any subprograms
25507 in this unit.
25508
25509 @item pragma Preelaborate
25510 @findex Preelaborate
25511 @cindex pragma Preelaborate
25512 This pragma places slightly less stringent restrictions on a unit than
25513 does pragma Pure,
25514 but these restrictions are still sufficient to ensure that there
25515 are no elaboration problems with any calls to the unit.
25516
25517 @item pragma Elaborate_Body
25518 @findex Elaborate_Body
25519 @cindex pragma Elaborate_Body
25520 This pragma requires that the body of a unit be elaborated immediately
25521 after its spec. Suppose a unit @code{A} has such a pragma,
25522 and unit @code{B} does
25523 a @code{with} of unit @code{A}. Recall that the standard rules require
25524 the spec of unit @code{A}
25525 to be elaborated before the @code{with}'ing unit; given the pragma in
25526 @code{A}, we also know that the body of @code{A}
25527 will be elaborated before @code{B}, so
25528 that calls to @code{A} are safe and do not need a check.
25529 @end table
25530
25531 @noindent
25532 Note that,
25533 unlike pragma @code{Pure} and pragma @code{Preelaborate},
25534 the use of
25535 @code{Elaborate_Body} does not guarantee that the program is
25536 free of elaboration problems, because it may not be possible
25537 to satisfy the requested elaboration order.
25538 Let's go back to the example with @code{Unit_1} and @code{Unit_2}.
25539 If a programmer
25540 marks @code{Unit_1} as @code{Elaborate_Body},
25541 and not @code{Unit_2,} then the order of
25542 elaboration will be:
25543
25544 @smallexample
25545 @group
25546 Spec of Unit_2
25547 Spec of Unit_1
25548 Body of Unit_1
25549 Body of Unit_2
25550 @end group
25551 @end smallexample
25552
25553 @noindent
25554 Now that means that the call to @code{Func_1} in @code{Unit_2}
25555 need not be checked,
25556 it must be safe. But the call to @code{Func_2} in
25557 @code{Unit_1} may still fail if
25558 @code{Expression_1} is equal to 1,
25559 and the programmer must still take
25560 responsibility for this not being the case.
25561
25562 If all units carry a pragma @code{Elaborate_Body}, then all problems are
25563 eliminated, except for calls entirely within a body, which are
25564 in any case fully under programmer control. However, using the pragma
25565 everywhere is not always possible.
25566 In particular, for our @code{Unit_1}/@code{Unit_2} example, if
25567 we marked both of them as having pragma @code{Elaborate_Body}, then
25568 clearly there would be no possible elaboration order.
25569
25570 The above pragmas allow a server to guarantee safe use by clients, and
25571 clearly this is the preferable approach. Consequently a good rule
25572 is to mark units as @code{Pure} or @code{Preelaborate} if possible,
25573 and if this is not possible,
25574 mark them as @code{Elaborate_Body} if possible.
25575 As we have seen, there are situations where neither of these
25576 three pragmas can be used.
25577 So we also provide methods for clients to control the
25578 order of elaboration of the servers on which they depend:
25579
25580 @table @asis
25581 @item pragma Elaborate (unit)
25582 @findex Elaborate
25583 @cindex pragma Elaborate
25584 This pragma is placed in the context clause, after a @code{with} clause,
25585 and it requires that the body of the named unit be elaborated before
25586 the unit in which the pragma occurs. The idea is to use this pragma
25587 if the current unit calls at elaboration time, directly or indirectly,
25588 some subprogram in the named unit.
25589
25590 @item pragma Elaborate_All (unit)
25591 @findex Elaborate_All
25592 @cindex pragma Elaborate_All
25593 This is a stronger version of the Elaborate pragma. Consider the
25594 following example:
25595
25596 @smallexample
25597 Unit A @code{with}'s unit B and calls B.Func in elab code
25598 Unit B @code{with}'s unit C, and B.Func calls C.Func
25599 @end smallexample
25600
25601 @noindent
25602 Now if we put a pragma @code{Elaborate (B)}
25603 in unit @code{A}, this ensures that the
25604 body of @code{B} is elaborated before the call, but not the
25605 body of @code{C}, so
25606 the call to @code{C.Func} could still cause @code{Program_Error} to
25607 be raised.
25608
25609 The effect of a pragma @code{Elaborate_All} is stronger, it requires
25610 not only that the body of the named unit be elaborated before the
25611 unit doing the @code{with}, but also the bodies of all units that the
25612 named unit uses, following @code{with} links transitively. For example,
25613 if we put a pragma @code{Elaborate_All (B)} in unit @code{A},
25614 then it requires
25615 not only that the body of @code{B} be elaborated before @code{A},
25616 but also the
25617 body of @code{C}, because @code{B} @code{with}'s @code{C}.
25618 @end table
25619
25620 @noindent
25621 We are now in a position to give a usage rule in Ada for avoiding
25622 elaboration problems, at least if dynamic dispatching and access to
25623 subprogram values are not used. We will handle these cases separately
25624 later.
25625
25626 The rule is simple. If a unit has elaboration code that can directly or
25627 indirectly make a call to a subprogram in a @code{with}'ed unit, or instantiate
25628 a generic package in a @code{with}'ed unit,
25629 then if the @code{with}'ed unit does not have
25630 pragma @code{Pure} or @code{Preelaborate}, then the client should have
25631 a pragma @code{Elaborate_All}
25632 for the @code{with}'ed unit. By following this rule a client is
25633 assured that calls can be made without risk of an exception.
25634
25635 For generic subprogram instantiations, the rule can be relaxed to
25636 require only a pragma @code{Elaborate} since elaborating the body
25637 of a subprogram cannot cause any transitive elaboration (we are
25638 not calling the subprogram in this case, just elaborating its
25639 declaration).
25640
25641 If this rule is not followed, then a program may be in one of four
25642 states:
25643
25644 @table @asis
25645 @item No order exists
25646 No order of elaboration exists which follows the rules, taking into
25647 account any @code{Elaborate}, @code{Elaborate_All},
25648 or @code{Elaborate_Body} pragmas. In
25649 this case, an Ada compiler must diagnose the situation at bind
25650 time, and refuse to build an executable program.
25651
25652 @item One or more orders exist, all incorrect
25653 One or more acceptable elaboration orders exist, and all of them
25654 generate an elaboration order problem. In this case, the binder
25655 can build an executable program, but @code{Program_Error} will be raised
25656 when the program is run.
25657
25658 @item Several orders exist, some right, some incorrect
25659 One or more acceptable elaboration orders exists, and some of them
25660 work, and some do not. The programmer has not controlled
25661 the order of elaboration, so the binder may or may not pick one of
25662 the correct orders, and the program may or may not raise an
25663 exception when it is run. This is the worst case, because it means
25664 that the program may fail when moved to another compiler, or even
25665 another version of the same compiler.
25666
25667 @item One or more orders exists, all correct
25668 One ore more acceptable elaboration orders exist, and all of them
25669 work. In this case the program runs successfully. This state of
25670 affairs can be guaranteed by following the rule we gave above, but
25671 may be true even if the rule is not followed.
25672 @end table
25673
25674 @noindent
25675 Note that one additional advantage of following our rules on the use
25676 of @code{Elaborate} and @code{Elaborate_All}
25677 is that the program continues to stay in the ideal (all orders OK) state
25678 even if maintenance
25679 changes some bodies of some units. Conversely, if a program that does
25680 not follow this rule happens to be safe at some point, this state of affairs
25681 may deteriorate silently as a result of maintenance changes.
25682
25683 You may have noticed that the above discussion did not mention
25684 the use of @code{Elaborate_Body}. This was a deliberate omission. If you
25685 @code{with} an @code{Elaborate_Body} unit, it still may be the case that
25686 code in the body makes calls to some other unit, so it is still necessary
25687 to use @code{Elaborate_All} on such units.
25688
25689 @node Controlling Elaboration in GNAT - Internal Calls
25690 @section Controlling Elaboration in GNAT - Internal Calls
25691
25692 @noindent
25693 In the case of internal calls, i.e., calls within a single package, the
25694 programmer has full control over the order of elaboration, and it is up
25695 to the programmer to elaborate declarations in an appropriate order. For
25696 example writing:
25697
25698 @smallexample @c ada
25699 @group
25700 @cartouche
25701 function One return Float;
25702
25703 Q : Float := One;
25704
25705 function One return Float is
25706 begin
25707 return 1.0;
25708 end One;
25709 @end cartouche
25710 @end group
25711 @end smallexample
25712
25713 @noindent
25714 will obviously raise @code{Program_Error} at run time, because function
25715 One will be called before its body is elaborated. In this case GNAT will
25716 generate a warning that the call will raise @code{Program_Error}:
25717
25718 @smallexample
25719 @group
25720 @cartouche
25721 1. procedure y is
25722 2. function One return Float;
25723 3.
25724 4. Q : Float := One;
25725 |
25726 >>> warning: cannot call "One" before body is elaborated
25727 >>> warning: Program_Error will be raised at run time
25728
25729 5.
25730 6. function One return Float is
25731 7. begin
25732 8. return 1.0;
25733 9. end One;
25734 10.
25735 11. begin
25736 12. null;
25737 13. end;
25738 @end cartouche
25739 @end group
25740 @end smallexample
25741
25742 @noindent
25743 Note that in this particular case, it is likely that the call is safe, because
25744 the function @code{One} does not access any global variables.
25745 Nevertheless in Ada, we do not want the validity of the check to depend on
25746 the contents of the body (think about the separate compilation case), so this
25747 is still wrong, as we discussed in the previous sections.
25748
25749 The error is easily corrected by rearranging the declarations so that the
25750 body of @code{One} appears before the declaration containing the call
25751 (note that in Ada 95 and Ada 2005,
25752 declarations can appear in any order, so there is no restriction that
25753 would prevent this reordering, and if we write:
25754
25755 @smallexample @c ada
25756 @group
25757 @cartouche
25758 function One return Float;
25759
25760 function One return Float is
25761 begin
25762 return 1.0;
25763 end One;
25764
25765 Q : Float := One;
25766 @end cartouche
25767 @end group
25768 @end smallexample
25769
25770 @noindent
25771 then all is well, no warning is generated, and no
25772 @code{Program_Error} exception
25773 will be raised.
25774 Things are more complicated when a chain of subprograms is executed:
25775
25776 @smallexample @c ada
25777 @group
25778 @cartouche
25779 function A return Integer;
25780 function B return Integer;
25781 function C return Integer;
25782
25783 function B return Integer is begin return A; end;
25784 function C return Integer is begin return B; end;
25785
25786 X : Integer := C;
25787
25788 function A return Integer is begin return 1; end;
25789 @end cartouche
25790 @end group
25791 @end smallexample
25792
25793 @noindent
25794 Now the call to @code{C}
25795 at elaboration time in the declaration of @code{X} is correct, because
25796 the body of @code{C} is already elaborated,
25797 and the call to @code{B} within the body of
25798 @code{C} is correct, but the call
25799 to @code{A} within the body of @code{B} is incorrect, because the body
25800 of @code{A} has not been elaborated, so @code{Program_Error}
25801 will be raised on the call to @code{A}.
25802 In this case GNAT will generate a
25803 warning that @code{Program_Error} may be
25804 raised at the point of the call. Let's look at the warning:
25805
25806 @smallexample
25807 @group
25808 @cartouche
25809 1. procedure x is
25810 2. function A return Integer;
25811 3. function B return Integer;
25812 4. function C return Integer;
25813 5.
25814 6. function B return Integer is begin return A; end;
25815 |
25816 >>> warning: call to "A" before body is elaborated may
25817 raise Program_Error
25818 >>> warning: "B" called at line 7
25819 >>> warning: "C" called at line 9
25820
25821 7. function C return Integer is begin return B; end;
25822 8.
25823 9. X : Integer := C;
25824 10.
25825 11. function A return Integer is begin return 1; end;
25826 12.
25827 13. begin
25828 14. null;
25829 15. end;
25830 @end cartouche
25831 @end group
25832 @end smallexample
25833
25834 @noindent
25835 Note that the message here says ``may raise'', instead of the direct case,
25836 where the message says ``will be raised''. That's because whether
25837 @code{A} is
25838 actually called depends in general on run-time flow of control.
25839 For example, if the body of @code{B} said
25840
25841 @smallexample @c ada
25842 @group
25843 @cartouche
25844 function B return Integer is
25845 begin
25846 if some-condition-depending-on-input-data then
25847 return A;
25848 else
25849 return 1;
25850 end if;
25851 end B;
25852 @end cartouche
25853 @end group
25854 @end smallexample
25855
25856 @noindent
25857 then we could not know until run time whether the incorrect call to A would
25858 actually occur, so @code{Program_Error} might
25859 or might not be raised. It is possible for a compiler to
25860 do a better job of analyzing bodies, to
25861 determine whether or not @code{Program_Error}
25862 might be raised, but it certainly
25863 couldn't do a perfect job (that would require solving the halting problem
25864 and is provably impossible), and because this is a warning anyway, it does
25865 not seem worth the effort to do the analysis. Cases in which it
25866 would be relevant are rare.
25867
25868 In practice, warnings of either of the forms given
25869 above will usually correspond to
25870 real errors, and should be examined carefully and eliminated.
25871 In the rare case where a warning is bogus, it can be suppressed by any of
25872 the following methods:
25873
25874 @itemize @bullet
25875 @item
25876 Compile with the @option{-gnatws} switch set
25877
25878 @item
25879 Suppress @code{Elaboration_Check} for the called subprogram
25880
25881 @item
25882 Use pragma @code{Warnings_Off} to turn warnings off for the call
25883 @end itemize
25884
25885 @noindent
25886 For the internal elaboration check case,
25887 GNAT by default generates the
25888 necessary run-time checks to ensure
25889 that @code{Program_Error} is raised if any
25890 call fails an elaboration check. Of course this can only happen if a
25891 warning has been issued as described above. The use of pragma
25892 @code{Suppress (Elaboration_Check)} may (but is not guaranteed to) suppress
25893 some of these checks, meaning that it may be possible (but is not
25894 guaranteed) for a program to be able to call a subprogram whose body
25895 is not yet elaborated, without raising a @code{Program_Error} exception.
25896
25897 @node Controlling Elaboration in GNAT - External Calls
25898 @section Controlling Elaboration in GNAT - External Calls
25899
25900 @noindent
25901 The previous section discussed the case in which the execution of a
25902 particular thread of elaboration code occurred entirely within a
25903 single unit. This is the easy case to handle, because a programmer
25904 has direct and total control over the order of elaboration, and
25905 furthermore, checks need only be generated in cases which are rare
25906 and which the compiler can easily detect.
25907 The situation is more complex when separate compilation is taken into account.
25908 Consider the following:
25909
25910 @smallexample @c ada
25911 @cartouche
25912 @group
25913 package Math is
25914 function Sqrt (Arg : Float) return Float;
25915 end Math;
25916
25917 package body Math is
25918 function Sqrt (Arg : Float) return Float is
25919 begin
25920 @dots{}
25921 end Sqrt;
25922 end Math;
25923 @end group
25924 @group
25925 with Math;
25926 package Stuff is
25927 X : Float := Math.Sqrt (0.5);
25928 end Stuff;
25929
25930 with Stuff;
25931 procedure Main is
25932 begin
25933 @dots{}
25934 end Main;
25935 @end group
25936 @end cartouche
25937 @end smallexample
25938
25939 @noindent
25940 where @code{Main} is the main program. When this program is executed, the
25941 elaboration code must first be executed, and one of the jobs of the
25942 binder is to determine the order in which the units of a program are
25943 to be elaborated. In this case we have four units: the spec and body
25944 of @code{Math},
25945 the spec of @code{Stuff} and the body of @code{Main}).
25946 In what order should the four separate sections of elaboration code
25947 be executed?
25948
25949 There are some restrictions in the order of elaboration that the binder
25950 can choose. In particular, if unit U has a @code{with}
25951 for a package @code{X}, then you
25952 are assured that the spec of @code{X}
25953 is elaborated before U , but you are
25954 not assured that the body of @code{X}
25955 is elaborated before U.
25956 This means that in the above case, the binder is allowed to choose the
25957 order:
25958
25959 @smallexample
25960 spec of Math
25961 spec of Stuff
25962 body of Math
25963 body of Main
25964 @end smallexample
25965
25966 @noindent
25967 but that's not good, because now the call to @code{Math.Sqrt}
25968 that happens during
25969 the elaboration of the @code{Stuff}
25970 spec happens before the body of @code{Math.Sqrt} is
25971 elaborated, and hence causes @code{Program_Error} exception to be raised.
25972 At first glance, one might say that the binder is misbehaving, because
25973 obviously you want to elaborate the body of something you @code{with}
25974 first, but
25975 that is not a general rule that can be followed in all cases. Consider
25976
25977 @smallexample @c ada
25978 @group
25979 @cartouche
25980 package X is @dots{}
25981
25982 package Y is @dots{}
25983
25984 with X;
25985 package body Y is @dots{}
25986
25987 with Y;
25988 package body X is @dots{}
25989 @end cartouche
25990 @end group
25991 @end smallexample
25992
25993 @noindent
25994 This is a common arrangement, and, apart from the order of elaboration
25995 problems that might arise in connection with elaboration code, this works fine.
25996 A rule that says that you must first elaborate the body of anything you
25997 @code{with} cannot work in this case:
25998 the body of @code{X} @code{with}'s @code{Y},
25999 which means you would have to
26000 elaborate the body of @code{Y} first, but that @code{with}'s @code{X},
26001 which means
26002 you have to elaborate the body of @code{X} first, but @dots{} and we have a
26003 loop that cannot be broken.
26004
26005 It is true that the binder can in many cases guess an order of elaboration
26006 that is unlikely to cause a @code{Program_Error}
26007 exception to be raised, and it tries to do so (in the
26008 above example of @code{Math/Stuff/Spec}, the GNAT binder will
26009 by default
26010 elaborate the body of @code{Math} right after its spec, so all will be well).
26011
26012 However, a program that blindly relies on the binder to be helpful can
26013 get into trouble, as we discussed in the previous sections, so
26014 GNAT
26015 provides a number of facilities for assisting the programmer in
26016 developing programs that are robust with respect to elaboration order.
26017
26018 @node Default Behavior in GNAT - Ensuring Safety
26019 @section Default Behavior in GNAT - Ensuring Safety
26020
26021 @noindent
26022 The default behavior in GNAT ensures elaboration safety. In its
26023 default mode GNAT implements the
26024 rule we previously described as the right approach. Let's restate it:
26025
26026 @itemize
26027 @item
26028 @emph{If a unit has elaboration code that can directly or indirectly make a
26029 call to a subprogram in a @code{with}'ed unit, or instantiate a generic
26030 package in a @code{with}'ed unit, then if the @code{with}'ed unit
26031 does not have pragma @code{Pure} or
26032 @code{Preelaborate}, then the client should have an
26033 @code{Elaborate_All} pragma for the @code{with}'ed unit.}
26034
26035 @emph{In the case of instantiating a generic subprogram, it is always
26036 sufficient to have only an @code{Elaborate} pragma for the
26037 @code{with}'ed unit.}
26038 @end itemize
26039
26040 @noindent
26041 By following this rule a client is assured that calls and instantiations
26042 can be made without risk of an exception.
26043
26044 In this mode GNAT traces all calls that are potentially made from
26045 elaboration code, and puts in any missing implicit @code{Elaborate}
26046 and @code{Elaborate_All} pragmas.
26047 The advantage of this approach is that no elaboration problems
26048 are possible if the binder can find an elaboration order that is
26049 consistent with these implicit @code{Elaborate} and
26050 @code{Elaborate_All} pragmas. The
26051 disadvantage of this approach is that no such order may exist.
26052
26053 If the binder does not generate any diagnostics, then it means that it has
26054 found an elaboration order that is guaranteed to be safe. However, the binder
26055 may still be relying on implicitly generated @code{Elaborate} and
26056 @code{Elaborate_All} pragmas so portability to other compilers than GNAT is not
26057 guaranteed.
26058
26059 If it is important to guarantee portability, then the compilations should
26060 use the
26061 @option{-gnatel}
26062 (info messages for elaboration prag mas) switch. This will cause info messages
26063 to be generated indicating the missing @code{Elaborate} and
26064 @code{Elaborate_All} pragmas.
26065 Consider the following source program:
26066
26067 @smallexample @c ada
26068 @group
26069 @cartouche
26070 with k;
26071 package j is
26072 m : integer := k.r;
26073 end;
26074 @end cartouche
26075 @end group
26076 @end smallexample
26077
26078 @noindent
26079 where it is clear that there
26080 should be a pragma @code{Elaborate_All}
26081 for unit @code{k}. An implicit pragma will be generated, and it is
26082 likely that the binder will be able to honor it. However, if you want
26083 to port this program to some other Ada compiler than GNAT.
26084 it is safer to include the pragma explicitly in the source. If this
26085 unit is compiled with the
26086 @option{-gnatel}
26087 switch, then the compiler outputs an information message:
26088
26089 @smallexample
26090 @group
26091 @cartouche
26092 1. with k;
26093 2. package j is
26094 3. m : integer := k.r;
26095 |
26096 >>> info: call to "r" may raise Program_Error
26097 >>> info: missing pragma Elaborate_All for "k"
26098
26099 4. end;
26100 @end cartouche
26101 @end group
26102 @end smallexample
26103
26104 @noindent
26105 and these messages can be used as a guide for supplying manually
26106 the missing pragmas. It is usually a bad idea to use this
26107 option during development. That's because it will tell you when
26108 you need to put in a pragma, but cannot tell you when it is time
26109 to take it out. So the use of pragma @code{Elaborate_All} may lead to
26110 unnecessary dependencies and even false circularities.
26111
26112 This default mode is more restrictive than the Ada Reference
26113 Manual, and it is possible to construct programs which will compile
26114 using the dynamic model described there, but will run into a
26115 circularity using the safer static model we have described.
26116
26117 Of course any Ada compiler must be able to operate in a mode
26118 consistent with the requirements of the Ada Reference Manual,
26119 and in particular must have the capability of implementing the
26120 standard dynamic model of elaboration with run-time checks.
26121
26122 In GNAT, this standard mode can be achieved either by the use of
26123 the @option{-gnatE} switch on the compiler (@command{gcc} or
26124 @command{gnatmake}) command, or by the use of the configuration pragma:
26125
26126 @smallexample @c ada
26127 pragma Elaboration_Checks (DYNAMIC);
26128 @end smallexample
26129
26130 @noindent
26131 Either approach will cause the unit affected to be compiled using the
26132 standard dynamic run-time elaboration checks described in the Ada
26133 Reference Manual. The static model is generally preferable, since it
26134 is clearly safer to rely on compile and link time checks rather than
26135 run-time checks. However, in the case of legacy code, it may be
26136 difficult to meet the requirements of the static model. This
26137 issue is further discussed in
26138 @ref{What to Do If the Default Elaboration Behavior Fails}.
26139
26140 Note that the static model provides a strict subset of the allowed
26141 behavior and programs of the Ada Reference Manual, so if you do
26142 adhere to the static model and no circularities exist,
26143 then you are assured that your program will
26144 work using the dynamic model, providing that you remove any
26145 pragma Elaborate statements from the source.
26146
26147 @node Treatment of Pragma Elaborate
26148 @section Treatment of Pragma Elaborate
26149 @cindex Pragma Elaborate
26150
26151 @noindent
26152 The use of @code{pragma Elaborate}
26153 should generally be avoided in Ada 95 and Ada 2005 programs,
26154 since there is no guarantee that transitive calls
26155 will be properly handled. Indeed at one point, this pragma was placed
26156 in Annex J (Obsolescent Features), on the grounds that it is never useful.
26157
26158 Now that's a bit restrictive. In practice, the case in which
26159 @code{pragma Elaborate} is useful is when the caller knows that there
26160 are no transitive calls, or that the called unit contains all necessary
26161 transitive @code{pragma Elaborate} statements, and legacy code often
26162 contains such uses.
26163
26164 Strictly speaking the static mode in GNAT should ignore such pragmas,
26165 since there is no assurance at compile time that the necessary safety
26166 conditions are met. In practice, this would cause GNAT to be incompatible
26167 with correctly written Ada 83 code that had all necessary
26168 @code{pragma Elaborate} statements in place. Consequently, we made the
26169 decision that GNAT in its default mode will believe that if it encounters
26170 a @code{pragma Elaborate} then the programmer knows what they are doing,
26171 and it will trust that no elaboration errors can occur.
26172
26173 The result of this decision is two-fold. First to be safe using the
26174 static mode, you should remove all @code{pragma Elaborate} statements.
26175 Second, when fixing circularities in existing code, you can selectively
26176 use @code{pragma Elaborate} statements to convince the static mode of
26177 GNAT that it need not generate an implicit @code{pragma Elaborate_All}
26178 statement.
26179
26180 When using the static mode with @option{-gnatwl}, any use of
26181 @code{pragma Elaborate} will generate a warning about possible
26182 problems.
26183
26184 @node Elaboration Issues for Library Tasks
26185 @section Elaboration Issues for Library Tasks
26186 @cindex Library tasks, elaboration issues
26187 @cindex Elaboration of library tasks
26188
26189 @noindent
26190 In this section we examine special elaboration issues that arise for
26191 programs that declare library level tasks.
26192
26193 Generally the model of execution of an Ada program is that all units are
26194 elaborated, and then execution of the program starts. However, the
26195 declaration of library tasks definitely does not fit this model. The
26196 reason for this is that library tasks start as soon as they are declared
26197 (more precisely, as soon as the statement part of the enclosing package
26198 body is reached), that is to say before elaboration
26199 of the program is complete. This means that if such a task calls a
26200 subprogram, or an entry in another task, the callee may or may not be
26201 elaborated yet, and in the standard
26202 Reference Manual model of dynamic elaboration checks, you can even
26203 get timing dependent Program_Error exceptions, since there can be
26204 a race between the elaboration code and the task code.
26205
26206 The static model of elaboration in GNAT seeks to avoid all such
26207 dynamic behavior, by being conservative, and the conservative
26208 approach in this particular case is to assume that all the code
26209 in a task body is potentially executed at elaboration time if
26210 a task is declared at the library level.
26211
26212 This can definitely result in unexpected circularities. Consider
26213 the following example
26214
26215 @smallexample @c ada
26216 package Decls is
26217 task Lib_Task is
26218 entry Start;
26219 end Lib_Task;
26220
26221 type My_Int is new Integer;
26222
26223 function Ident (M : My_Int) return My_Int;
26224 end Decls;
26225
26226 with Utils;
26227 package body Decls is
26228 task body Lib_Task is
26229 begin
26230 accept Start;
26231 Utils.Put_Val (2);
26232 end Lib_Task;
26233
26234 function Ident (M : My_Int) return My_Int is
26235 begin
26236 return M;
26237 end Ident;
26238 end Decls;
26239
26240 with Decls;
26241 package Utils is
26242 procedure Put_Val (Arg : Decls.My_Int);
26243 end Utils;
26244
26245 with Text_IO;
26246 package body Utils is
26247 procedure Put_Val (Arg : Decls.My_Int) is
26248 begin
26249 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
26250 end Put_Val;
26251 end Utils;
26252
26253 with Decls;
26254 procedure Main is
26255 begin
26256 Decls.Lib_Task.Start;
26257 end;
26258 @end smallexample
26259
26260 @noindent
26261 If the above example is compiled in the default static elaboration
26262 mode, then a circularity occurs. The circularity comes from the call
26263 @code{Utils.Put_Val} in the task body of @code{Decls.Lib_Task}. Since
26264 this call occurs in elaboration code, we need an implicit pragma
26265 @code{Elaborate_All} for @code{Utils}. This means that not only must
26266 the spec and body of @code{Utils} be elaborated before the body
26267 of @code{Decls}, but also the spec and body of any unit that is
26268 @code{with'ed} by the body of @code{Utils} must also be elaborated before
26269 the body of @code{Decls}. This is the transitive implication of
26270 pragma @code{Elaborate_All} and it makes sense, because in general
26271 the body of @code{Put_Val} might have a call to something in a
26272 @code{with'ed} unit.
26273
26274 In this case, the body of Utils (actually its spec) @code{with's}
26275 @code{Decls}. Unfortunately this means that the body of @code{Decls}
26276 must be elaborated before itself, in case there is a call from the
26277 body of @code{Utils}.
26278
26279 Here is the exact chain of events we are worrying about:
26280
26281 @enumerate
26282 @item
26283 In the body of @code{Decls} a call is made from within the body of a library
26284 task to a subprogram in the package @code{Utils}. Since this call may
26285 occur at elaboration time (given that the task is activated at elaboration
26286 time), we have to assume the worst, i.e., that the
26287 call does happen at elaboration time.
26288
26289 @item
26290 This means that the body and spec of @code{Util} must be elaborated before
26291 the body of @code{Decls} so that this call does not cause an access before
26292 elaboration.
26293
26294 @item
26295 Within the body of @code{Util}, specifically within the body of
26296 @code{Util.Put_Val} there may be calls to any unit @code{with}'ed
26297 by this package.
26298
26299 @item
26300 One such @code{with}'ed package is package @code{Decls}, so there
26301 might be a call to a subprogram in @code{Decls} in @code{Put_Val}.
26302 In fact there is such a call in this example, but we would have to
26303 assume that there was such a call even if it were not there, since
26304 we are not supposed to write the body of @code{Decls} knowing what
26305 is in the body of @code{Utils}; certainly in the case of the
26306 static elaboration model, the compiler does not know what is in
26307 other bodies and must assume the worst.
26308
26309 @item
26310 This means that the spec and body of @code{Decls} must also be
26311 elaborated before we elaborate the unit containing the call, but
26312 that unit is @code{Decls}! This means that the body of @code{Decls}
26313 must be elaborated before itself, and that's a circularity.
26314 @end enumerate
26315
26316 @noindent
26317 Indeed, if you add an explicit pragma @code{Elaborate_All} for @code{Utils} in
26318 the body of @code{Decls} you will get a true Ada Reference Manual
26319 circularity that makes the program illegal.
26320
26321 In practice, we have found that problems with the static model of
26322 elaboration in existing code often arise from library tasks, so
26323 we must address this particular situation.
26324
26325 Note that if we compile and run the program above, using the dynamic model of
26326 elaboration (that is to say use the @option{-gnatE} switch),
26327 then it compiles, binds,
26328 links, and runs, printing the expected result of 2. Therefore in some sense
26329 the circularity here is only apparent, and we need to capture
26330 the properties of this program that distinguish it from other library-level
26331 tasks that have real elaboration problems.
26332
26333 We have four possible answers to this question:
26334
26335 @itemize @bullet
26336
26337 @item
26338 Use the dynamic model of elaboration.
26339
26340 If we use the @option{-gnatE} switch, then as noted above, the program works.
26341 Why is this? If we examine the task body, it is apparent that the task cannot
26342 proceed past the
26343 @code{accept} statement until after elaboration has been completed, because
26344 the corresponding entry call comes from the main program, not earlier.
26345 This is why the dynamic model works here. But that's really giving
26346 up on a precise analysis, and we prefer to take this approach only if we cannot
26347 solve the
26348 problem in any other manner. So let us examine two ways to reorganize
26349 the program to avoid the potential elaboration problem.
26350
26351 @item
26352 Split library tasks into separate packages.
26353
26354 Write separate packages, so that library tasks are isolated from
26355 other declarations as much as possible. Let us look at a variation on
26356 the above program.
26357
26358 @smallexample @c ada
26359 package Decls1 is
26360 task Lib_Task is
26361 entry Start;
26362 end Lib_Task;
26363 end Decls1;
26364
26365 with Utils;
26366 package body Decls1 is
26367 task body Lib_Task is
26368 begin
26369 accept Start;
26370 Utils.Put_Val (2);
26371 end Lib_Task;
26372 end Decls1;
26373
26374 package Decls2 is
26375 type My_Int is new Integer;
26376 function Ident (M : My_Int) return My_Int;
26377 end Decls2;
26378
26379 with Utils;
26380 package body Decls2 is
26381 function Ident (M : My_Int) return My_Int is
26382 begin
26383 return M;
26384 end Ident;
26385 end Decls2;
26386
26387 with Decls2;
26388 package Utils is
26389 procedure Put_Val (Arg : Decls2.My_Int);
26390 end Utils;
26391
26392 with Text_IO;
26393 package body Utils is
26394 procedure Put_Val (Arg : Decls2.My_Int) is
26395 begin
26396 Text_IO.Put_Line (Decls2.My_Int'Image (Decls2.Ident (Arg)));
26397 end Put_Val;
26398 end Utils;
26399
26400 with Decls1;
26401 procedure Main is
26402 begin
26403 Decls1.Lib_Task.Start;
26404 end;
26405 @end smallexample
26406
26407 @noindent
26408 All we have done is to split @code{Decls} into two packages, one
26409 containing the library task, and one containing everything else. Now
26410 there is no cycle, and the program compiles, binds, links and executes
26411 using the default static model of elaboration.
26412
26413 @item
26414 Declare separate task types.
26415
26416 A significant part of the problem arises because of the use of the
26417 single task declaration form. This means that the elaboration of
26418 the task type, and the elaboration of the task itself (i.e.@: the
26419 creation of the task) happen at the same time. A good rule
26420 of style in Ada is to always create explicit task types. By
26421 following the additional step of placing task objects in separate
26422 packages from the task type declaration, many elaboration problems
26423 are avoided. Here is another modified example of the example program:
26424
26425 @smallexample @c ada
26426 package Decls is
26427 task type Lib_Task_Type is
26428 entry Start;
26429 end Lib_Task_Type;
26430
26431 type My_Int is new Integer;
26432
26433 function Ident (M : My_Int) return My_Int;
26434 end Decls;
26435
26436 with Utils;
26437 package body Decls is
26438 task body Lib_Task_Type is
26439 begin
26440 accept Start;
26441 Utils.Put_Val (2);
26442 end Lib_Task_Type;
26443
26444 function Ident (M : My_Int) return My_Int is
26445 begin
26446 return M;
26447 end Ident;
26448 end Decls;
26449
26450 with Decls;
26451 package Utils is
26452 procedure Put_Val (Arg : Decls.My_Int);
26453 end Utils;
26454
26455 with Text_IO;
26456 package body Utils is
26457 procedure Put_Val (Arg : Decls.My_Int) is
26458 begin
26459 Text_IO.Put_Line (Decls.My_Int'Image (Decls.Ident (Arg)));
26460 end Put_Val;
26461 end Utils;
26462
26463 with Decls;
26464 package Declst is
26465 Lib_Task : Decls.Lib_Task_Type;
26466 end Declst;
26467
26468 with Declst;
26469 procedure Main is
26470 begin
26471 Declst.Lib_Task.Start;
26472 end;
26473 @end smallexample
26474
26475 @noindent
26476 What we have done here is to replace the @code{task} declaration in
26477 package @code{Decls} with a @code{task type} declaration. Then we
26478 introduce a separate package @code{Declst} to contain the actual
26479 task object. This separates the elaboration issues for
26480 the @code{task type}
26481 declaration, which causes no trouble, from the elaboration issues
26482 of the task object, which is also unproblematic, since it is now independent
26483 of the elaboration of @code{Utils}.
26484 This separation of concerns also corresponds to
26485 a generally sound engineering principle of separating declarations
26486 from instances. This version of the program also compiles, binds, links,
26487 and executes, generating the expected output.
26488
26489 @item
26490 Use No_Entry_Calls_In_Elaboration_Code restriction.
26491 @cindex No_Entry_Calls_In_Elaboration_Code
26492
26493 The previous two approaches described how a program can be restructured
26494 to avoid the special problems caused by library task bodies. in practice,
26495 however, such restructuring may be difficult to apply to existing legacy code,
26496 so we must consider solutions that do not require massive rewriting.
26497
26498 Let us consider more carefully why our original sample program works
26499 under the dynamic model of elaboration. The reason is that the code
26500 in the task body blocks immediately on the @code{accept}
26501 statement. Now of course there is nothing to prohibit elaboration
26502 code from making entry calls (for example from another library level task),
26503 so we cannot tell in isolation that
26504 the task will not execute the accept statement during elaboration.
26505
26506 However, in practice it is very unusual to see elaboration code
26507 make any entry calls, and the pattern of tasks starting
26508 at elaboration time and then immediately blocking on @code{accept} or
26509 @code{select} statements is very common. What this means is that
26510 the compiler is being too pessimistic when it analyzes the
26511 whole package body as though it might be executed at elaboration
26512 time.
26513
26514 If we know that the elaboration code contains no entry calls, (a very safe
26515 assumption most of the time, that could almost be made the default
26516 behavior), then we can compile all units of the program under control
26517 of the following configuration pragma:
26518
26519 @smallexample
26520 pragma Restrictions (No_Entry_Calls_In_Elaboration_Code);
26521 @end smallexample
26522
26523 @noindent
26524 This pragma can be placed in the @file{gnat.adc} file in the usual
26525 manner. If we take our original unmodified program and compile it
26526 in the presence of a @file{gnat.adc} containing the above pragma,
26527 then once again, we can compile, bind, link, and execute, obtaining
26528 the expected result. In the presence of this pragma, the compiler does
26529 not trace calls in a task body, that appear after the first @code{accept}
26530 or @code{select} statement, and therefore does not report a potential
26531 circularity in the original program.
26532
26533 The compiler will check to the extent it can that the above
26534 restriction is not violated, but it is not always possible to do a
26535 complete check at compile time, so it is important to use this
26536 pragma only if the stated restriction is in fact met, that is to say
26537 no task receives an entry call before elaboration of all units is completed.
26538
26539 @end itemize
26540
26541 @node Mixing Elaboration Models
26542 @section Mixing Elaboration Models
26543 @noindent
26544 So far, we have assumed that the entire program is either compiled
26545 using the dynamic model or static model, ensuring consistency. It
26546 is possible to mix the two models, but rules have to be followed
26547 if this mixing is done to ensure that elaboration checks are not
26548 omitted.
26549
26550 The basic rule is that @emph{a unit compiled with the static model cannot
26551 be @code{with'ed} by a unit compiled with the dynamic model}. The
26552 reason for this is that in the static model, a unit assumes that
26553 its clients guarantee to use (the equivalent of) pragma
26554 @code{Elaborate_All} so that no elaboration checks are required
26555 in inner subprograms, and this assumption is violated if the
26556 client is compiled with dynamic checks.
26557
26558 The precise rule is as follows. A unit that is compiled with dynamic
26559 checks can only @code{with} a unit that meets at least one of the
26560 following criteria:
26561
26562 @itemize @bullet
26563
26564 @item
26565 The @code{with'ed} unit is itself compiled with dynamic elaboration
26566 checks (that is with the @option{-gnatE} switch.
26567
26568 @item
26569 The @code{with'ed} unit is an internal GNAT implementation unit from
26570 the System, Interfaces, Ada, or GNAT hierarchies.
26571
26572 @item
26573 The @code{with'ed} unit has pragma Preelaborate or pragma Pure.
26574
26575 @item
26576 The @code{with'ing} unit (that is the client) has an explicit pragma
26577 @code{Elaborate_All} for the @code{with'ed} unit.
26578
26579 @end itemize
26580
26581 @noindent
26582 If this rule is violated, that is if a unit with dynamic elaboration
26583 checks @code{with's} a unit that does not meet one of the above four
26584 criteria, then the binder (@code{gnatbind}) will issue a warning
26585 similar to that in the following example:
26586
26587 @smallexample
26588 warning: "x.ads" has dynamic elaboration checks and with's
26589 warning: "y.ads" which has static elaboration checks
26590 @end smallexample
26591
26592 @noindent
26593 These warnings indicate that the rule has been violated, and that as a result
26594 elaboration checks may be missed in the resulting executable file.
26595 This warning may be suppressed using the @option{-ws} binder switch
26596 in the usual manner.
26597
26598 One useful application of this mixing rule is in the case of a subsystem
26599 which does not itself @code{with} units from the remainder of the
26600 application. In this case, the entire subsystem can be compiled with
26601 dynamic checks to resolve a circularity in the subsystem, while
26602 allowing the main application that uses this subsystem to be compiled
26603 using the more reliable default static model.
26604
26605 @node What to Do If the Default Elaboration Behavior Fails
26606 @section What to Do If the Default Elaboration Behavior Fails
26607
26608 @noindent
26609 If the binder cannot find an acceptable order, it outputs detailed
26610 diagnostics. For example:
26611 @smallexample
26612 @group
26613 @iftex
26614 @leftskip=0cm
26615 @end iftex
26616 error: elaboration circularity detected
26617 info: "proc (body)" must be elaborated before "pack (body)"
26618 info: reason: Elaborate_All probably needed in unit "pack (body)"
26619 info: recompile "pack (body)" with -gnatel
26620 info: for full details
26621 info: "proc (body)"
26622 info: is needed by its spec:
26623 info: "proc (spec)"
26624 info: which is withed by:
26625 info: "pack (body)"
26626 info: "pack (body)" must be elaborated before "proc (body)"
26627 info: reason: pragma Elaborate in unit "proc (body)"
26628 @end group
26629
26630 @end smallexample
26631
26632 @noindent
26633 In this case we have a cycle that the binder cannot break. On the one
26634 hand, there is an explicit pragma Elaborate in @code{proc} for
26635 @code{pack}. This means that the body of @code{pack} must be elaborated
26636 before the body of @code{proc}. On the other hand, there is elaboration
26637 code in @code{pack} that calls a subprogram in @code{proc}. This means
26638 that for maximum safety, there should really be a pragma
26639 Elaborate_All in @code{pack} for @code{proc} which would require that
26640 the body of @code{proc} be elaborated before the body of
26641 @code{pack}. Clearly both requirements cannot be satisfied.
26642 Faced with a circularity of this kind, you have three different options.
26643
26644 @table @asis
26645 @item Fix the program
26646 The most desirable option from the point of view of long-term maintenance
26647 is to rearrange the program so that the elaboration problems are avoided.
26648 One useful technique is to place the elaboration code into separate
26649 child packages. Another is to move some of the initialization code to
26650 explicitly called subprograms, where the program controls the order
26651 of initialization explicitly. Although this is the most desirable option,
26652 it may be impractical and involve too much modification, especially in
26653 the case of complex legacy code.
26654
26655 @item Perform dynamic checks
26656 If the compilations are done using the
26657 @option{-gnatE}
26658 (dynamic elaboration check) switch, then GNAT behaves in a quite different
26659 manner. Dynamic checks are generated for all calls that could possibly result
26660 in raising an exception. With this switch, the compiler does not generate
26661 implicit @code{Elaborate} or @code{Elaborate_All} pragmas. The behavior then is
26662 exactly as specified in the @cite{Ada Reference Manual}.
26663 The binder will generate
26664 an executable program that may or may not raise @code{Program_Error}, and then
26665 it is the programmer's job to ensure that it does not raise an exception. Note
26666 that it is important to compile all units with the switch, it cannot be used
26667 selectively.
26668
26669 @item Suppress checks
26670 The drawback of dynamic checks is that they generate a
26671 significant overhead at run time, both in space and time. If you
26672 are absolutely sure that your program cannot raise any elaboration
26673 exceptions, and you still want to use the dynamic elaboration model,
26674 then you can use the configuration pragma
26675 @code{Suppress (Elaboration_Check)} to suppress all such checks. For
26676 example this pragma could be placed in the @file{gnat.adc} file.
26677
26678 @item Suppress checks selectively
26679 When you know that certain calls or instantiations in elaboration code cannot
26680 possibly lead to an elaboration error, and the binder nevertheless complains
26681 about implicit @code{Elaborate} and @code{Elaborate_All} pragmas that lead to
26682 elaboration circularities, it is possible to remove those warnings locally and
26683 obtain a program that will bind. Clearly this can be unsafe, and it is the
26684 responsibility of the programmer to make sure that the resulting program has no
26685 elaboration anomalies. The pragma @code{Suppress (Elaboration_Check)} can be
26686 used with different granularity to suppress warnings and break elaboration
26687 circularities:
26688
26689 @itemize @bullet
26690 @item
26691 Place the pragma that names the called subprogram in the declarative part
26692 that contains the call.
26693
26694 @item
26695 Place the pragma in the declarative part, without naming an entity. This
26696 disables warnings on all calls in the corresponding declarative region.
26697
26698 @item
26699 Place the pragma in the package spec that declares the called subprogram,
26700 and name the subprogram. This disables warnings on all elaboration calls to
26701 that subprogram.
26702
26703 @item
26704 Place the pragma in the package spec that declares the called subprogram,
26705 without naming any entity. This disables warnings on all elaboration calls to
26706 all subprograms declared in this spec.
26707
26708 @item Use Pragma Elaborate
26709 As previously described in section @xref{Treatment of Pragma Elaborate},
26710 GNAT in static mode assumes that a @code{pragma} Elaborate indicates correctly
26711 that no elaboration checks are required on calls to the designated unit.
26712 There may be cases in which the caller knows that no transitive calls
26713 can occur, so that a @code{pragma Elaborate} will be sufficient in a
26714 case where @code{pragma Elaborate_All} would cause a circularity.
26715 @end itemize
26716
26717 @noindent
26718 These five cases are listed in order of decreasing safety, and therefore
26719 require increasing programmer care in their application. Consider the
26720 following program:
26721
26722 @smallexample @c adanocomment
26723 package Pack1 is
26724 function F1 return Integer;
26725 X1 : Integer;
26726 end Pack1;
26727
26728 package Pack2 is
26729 function F2 return Integer;
26730 function Pure (x : integer) return integer;
26731 -- pragma Suppress (Elaboration_Check, On => Pure); -- (3)
26732 -- pragma Suppress (Elaboration_Check); -- (4)
26733 end Pack2;
26734
26735 with Pack2;
26736 package body Pack1 is
26737 function F1 return Integer is
26738 begin
26739 return 100;
26740 end F1;
26741 Val : integer := Pack2.Pure (11); -- Elab. call (1)
26742 begin
26743 declare
26744 -- pragma Suppress(Elaboration_Check, Pack2.F2); -- (1)
26745 -- pragma Suppress(Elaboration_Check); -- (2)
26746 begin
26747 X1 := Pack2.F2 + 1; -- Elab. call (2)
26748 end;
26749 end Pack1;
26750
26751 with Pack1;
26752 package body Pack2 is
26753 function F2 return Integer is
26754 begin
26755 return Pack1.F1;
26756 end F2;
26757 function Pure (x : integer) return integer is
26758 begin
26759 return x ** 3 - 3 * x;
26760 end;
26761 end Pack2;
26762
26763 with Pack1, Ada.Text_IO;
26764 procedure Proc3 is
26765 begin
26766 Ada.Text_IO.Put_Line(Pack1.X1'Img); -- 101
26767 end Proc3;
26768 @end smallexample
26769 In the absence of any pragmas, an attempt to bind this program produces
26770 the following diagnostics:
26771 @smallexample
26772 @group
26773 @iftex
26774 @leftskip=.5cm
26775 @end iftex
26776 error: elaboration circularity detected
26777 info: "pack1 (body)" must be elaborated before "pack1 (body)"
26778 info: reason: Elaborate_All probably needed in unit "pack1 (body)"
26779 info: recompile "pack1 (body)" with -gnatel for full details
26780 info: "pack1 (body)"
26781 info: must be elaborated along with its spec:
26782 info: "pack1 (spec)"
26783 info: which is withed by:
26784 info: "pack2 (body)"
26785 info: which must be elaborated along with its spec:
26786 info: "pack2 (spec)"
26787 info: which is withed by:
26788 info: "pack1 (body)"
26789 @end group
26790 @end smallexample
26791 The sources of the circularity are the two calls to @code{Pack2.Pure} and
26792 @code{Pack2.F2} in the body of @code{Pack1}. We can see that the call to
26793 F2 is safe, even though F2 calls F1, because the call appears after the
26794 elaboration of the body of F1. Therefore the pragma (1) is safe, and will
26795 remove the warning on the call. It is also possible to use pragma (2)
26796 because there are no other potentially unsafe calls in the block.
26797
26798 @noindent
26799 The call to @code{Pure} is safe because this function does not depend on the
26800 state of @code{Pack2}. Therefore any call to this function is safe, and it
26801 is correct to place pragma (3) in the corresponding package spec.
26802
26803 @noindent
26804 Finally, we could place pragma (4) in the spec of @code{Pack2} to disable
26805 warnings on all calls to functions declared therein. Note that this is not
26806 necessarily safe, and requires more detailed examination of the subprogram
26807 bodies involved. In particular, a call to @code{F2} requires that @code{F1}
26808 be already elaborated.
26809 @end table
26810
26811 @noindent
26812 It is hard to generalize on which of these four approaches should be
26813 taken. Obviously if it is possible to fix the program so that the default
26814 treatment works, this is preferable, but this may not always be practical.
26815 It is certainly simple enough to use
26816 @option{-gnatE}
26817 but the danger in this case is that, even if the GNAT binder
26818 finds a correct elaboration order, it may not always do so,
26819 and certainly a binder from another Ada compiler might not. A
26820 combination of testing and analysis (for which the
26821 information messages generated with the
26822 @option{-gnatel}
26823 switch can be useful) must be used to ensure that the program is free
26824 of errors. One switch that is useful in this testing is the
26825 @option{^-p (pessimistic elaboration order)^/PESSIMISTIC_ELABORATION_ORDER^}
26826 switch for
26827 @code{gnatbind}.
26828 Normally the binder tries to find an order that has the best chance
26829 of avoiding elaboration problems. However, if this switch is used, the binder
26830 plays a devil's advocate role, and tries to choose the order that
26831 has the best chance of failing. If your program works even with this
26832 switch, then it has a better chance of being error free, but this is still
26833 not a guarantee.
26834
26835 For an example of this approach in action, consider the C-tests (executable
26836 tests) from the ACVC suite. If these are compiled and run with the default
26837 treatment, then all but one of them succeed without generating any error
26838 diagnostics from the binder. However, there is one test that fails, and
26839 this is not surprising, because the whole point of this test is to ensure
26840 that the compiler can handle cases where it is impossible to determine
26841 a correct order statically, and it checks that an exception is indeed
26842 raised at run time.
26843
26844 This one test must be compiled and run using the
26845 @option{-gnatE}
26846 switch, and then it passes. Alternatively, the entire suite can
26847 be run using this switch. It is never wrong to run with the dynamic
26848 elaboration switch if your code is correct, and we assume that the
26849 C-tests are indeed correct (it is less efficient, but efficiency is
26850 not a factor in running the ACVC tests.)
26851
26852 @node Elaboration for Indirect Calls
26853 @section Elaboration for Indirect Calls
26854 @cindex Dispatching calls
26855 @cindex Indirect calls
26856
26857 @noindent
26858 In rare cases, the static elaboration model fails to prevent
26859 dispatching calls to not-yet-elaborated subprograms. In such cases, we
26860 fall back to run-time checks; premature calls to any primitive
26861 operation of a tagged type before the body of the operation has been
26862 elaborated will raise @code{Program_Error}.
26863
26864 Access-to-subprogram types, however, are handled conservatively, and
26865 do not require run-time checks. This was not true in earlier versions
26866 of the compiler; you can use the @option{-gnatd.U} debug switch to
26867 revert to the old behavior if the new conservative behavior causes
26868 elaboration cycles. Here, ``conservative'' means that if you do
26869 @code{P'Access} during elaboration, the compiler will assume that you
26870 might call @code{P} indirectly during elaboration, so it adds an
26871 implicit @code{pragma Elaborate_All} on the library unit containing
26872 @code{P}. The @option{-gnatd.U} switch is safe if you know there are
26873 no such calls. If the program worked before, it will continue to work
26874 with @option{-gnatd.U}. But beware that code modifications such as
26875 adding an indirect call can cause erroneous behavior in the presence
26876 of @option{-gnatd.U}.
26877
26878 @node Summary of Procedures for Elaboration Control
26879 @section Summary of Procedures for Elaboration Control
26880 @cindex Elaboration control
26881
26882 @noindent
26883 First, compile your program with the default options, using none of
26884 the special elaboration control switches. If the binder successfully
26885 binds your program, then you can be confident that, apart from issues
26886 raised by the use of access-to-subprogram types and dynamic dispatching,
26887 the program is free of elaboration errors. If it is important that the
26888 program be portable to other compilers than GNAT, then use the
26889 @option{-gnatel}
26890 switch to generate messages about missing @code{Elaborate} or
26891 @code{Elaborate_All} pragmas, and supply the missing pragmas.
26892
26893 If the program fails to bind using the default static elaboration
26894 handling, then you can fix the program to eliminate the binder
26895 message, or recompile the entire program with the
26896 @option{-gnatE} switch to generate dynamic elaboration checks,
26897 and, if you are sure there really are no elaboration problems,
26898 use a global pragma @code{Suppress (Elaboration_Check)}.
26899
26900 @node Other Elaboration Order Considerations
26901 @section Other Elaboration Order Considerations
26902 @noindent
26903 This section has been entirely concerned with the issue of finding a valid
26904 elaboration order, as defined by the Ada Reference Manual. In a case
26905 where several elaboration orders are valid, the task is to find one
26906 of the possible valid elaboration orders (and the static model in GNAT
26907 will ensure that this is achieved).
26908
26909 The purpose of the elaboration rules in the Ada Reference Manual is to
26910 make sure that no entity is accessed before it has been elaborated. For
26911 a subprogram, this means that the spec and body must have been elaborated
26912 before the subprogram is called. For an object, this means that the object
26913 must have been elaborated before its value is read or written. A violation
26914 of either of these two requirements is an access before elaboration order,
26915 and this section has been all about avoiding such errors.
26916
26917 In the case where more than one order of elaboration is possible, in the
26918 sense that access before elaboration errors are avoided, then any one of
26919 the orders is ``correct'' in the sense that it meets the requirements of
26920 the Ada Reference Manual, and no such error occurs.
26921
26922 However, it may be the case for a given program, that there are
26923 constraints on the order of elaboration that come not from consideration
26924 of avoiding elaboration errors, but rather from extra-lingual logic
26925 requirements. Consider this example:
26926
26927 @smallexample @c ada
26928 with Init_Constants;
26929 package Constants is
26930 X : Integer := 0;
26931 Y : Integer := 0;
26932 end Constants;
26933
26934 package Init_Constants is
26935 procedure P; -- require a body
26936 end Init_Constants;
26937
26938 with Constants;
26939 package body Init_Constants is
26940 procedure P is begin null; end;
26941 begin
26942 Constants.X := 3;
26943 Constants.Y := 4;
26944 end Init_Constants;
26945
26946 with Constants;
26947 package Calc is
26948 Z : Integer := Constants.X + Constants.Y;
26949 end Calc;
26950
26951 with Calc;
26952 with Text_IO; use Text_IO;
26953 procedure Main is
26954 begin
26955 Put_Line (Calc.Z'Img);
26956 end Main;
26957 @end smallexample
26958
26959 @noindent
26960 In this example, there is more than one valid order of elaboration. For
26961 example both the following are correct orders:
26962
26963 @smallexample
26964 Init_Constants spec
26965 Constants spec
26966 Calc spec
26967 Init_Constants body
26968 Main body
26969
26970 and
26971
26972 Init_Constants spec
26973 Init_Constants body
26974 Constants spec
26975 Calc spec
26976 Main body
26977 @end smallexample
26978
26979 @noindent
26980 There is no language rule to prefer one or the other, both are correct
26981 from an order of elaboration point of view. But the programmatic effects
26982 of the two orders are very different. In the first, the elaboration routine
26983 of @code{Calc} initializes @code{Z} to zero, and then the main program
26984 runs with this value of zero. But in the second order, the elaboration
26985 routine of @code{Calc} runs after the body of Init_Constants has set
26986 @code{X} and @code{Y} and thus @code{Z} is set to 7 before @code{Main}
26987 runs.
26988
26989 One could perhaps by applying pretty clever non-artificial intelligence
26990 to the situation guess that it is more likely that the second order of
26991 elaboration is the one desired, but there is no formal linguistic reason
26992 to prefer one over the other. In fact in this particular case, GNAT will
26993 prefer the second order, because of the rule that bodies are elaborated
26994 as soon as possible, but it's just luck that this is what was wanted
26995 (if indeed the second order was preferred).
26996
26997 If the program cares about the order of elaboration routines in a case like
26998 this, it is important to specify the order required. In this particular
26999 case, that could have been achieved by adding to the spec of Calc:
27000
27001 @smallexample @c ada
27002 pragma Elaborate_All (Constants);
27003 @end smallexample
27004
27005 @noindent
27006 which requires that the body (if any) and spec of @code{Constants},
27007 as well as the body and spec of any unit @code{with}'ed by
27008 @code{Constants} be elaborated before @code{Calc} is elaborated.
27009
27010 Clearly no automatic method can always guess which alternative you require,
27011 and if you are working with legacy code that had constraints of this kind
27012 which were not properly specified by adding @code{Elaborate} or
27013 @code{Elaborate_All} pragmas, then indeed it is possible that two different
27014 compilers can choose different orders.
27015
27016 However, GNAT does attempt to diagnose the common situation where there
27017 are uninitialized variables in the visible part of a package spec, and the
27018 corresponding package body has an elaboration block that directly or
27019 indirectly initialized one or more of these variables. This is the situation
27020 in which a pragma Elaborate_Body is usually desirable, and GNAT will generate
27021 a warning that suggests this addition if it detects this situation.
27022
27023 The @code{gnatbind}
27024 @option{^-p^/PESSIMISTIC_ELABORATION^} switch may be useful in smoking
27025 out problems. This switch causes bodies to be elaborated as late as possible
27026 instead of as early as possible. In the example above, it would have forced
27027 the choice of the first elaboration order. If you get different results
27028 when using this switch, and particularly if one set of results is right,
27029 and one is wrong as far as you are concerned, it shows that you have some
27030 missing @code{Elaborate} pragmas. For the example above, we have the
27031 following output:
27032
27033 @smallexample
27034 gnatmake -f -q main
27035 main
27036 7
27037 gnatmake -f -q main -bargs -p
27038 main
27039 0
27040 @end smallexample
27041
27042 @noindent
27043 It is of course quite unlikely that both these results are correct, so
27044 it is up to you in a case like this to investigate the source of the
27045 difference, by looking at the two elaboration orders that are chosen,
27046 and figuring out which is correct, and then adding the necessary
27047 @code{Elaborate} or @code{Elaborate_All} pragmas to ensure the desired order.
27048
27049 @node Determining the Chosen Elaboration Order
27050 @section Determining the Chosen Elaboration Order
27051 @noindent
27052
27053 To see the elaboration order that the binder chooses, you can look at
27054 the last part of the b~xxx.adb binder output file. Here is an example:
27055
27056 @smallexample @c ada
27057 System.Soft_Links'Elab_Body;
27058 E14 := True;
27059 System.Secondary_Stack'Elab_Body;
27060 E18 := True;
27061 System.Exception_Table'Elab_Body;
27062 E24 := True;
27063 Ada.Io_Exceptions'Elab_Spec;
27064 E67 := True;
27065 Ada.Tags'Elab_Spec;
27066 Ada.Streams'Elab_Spec;
27067 E43 := True;
27068 Interfaces.C'Elab_Spec;
27069 E69 := True;
27070 System.Finalization_Root'Elab_Spec;
27071 E60 := True;
27072 System.Os_Lib'Elab_Body;
27073 E71 := True;
27074 System.Finalization_Implementation'Elab_Spec;
27075 System.Finalization_Implementation'Elab_Body;
27076 E62 := True;
27077 Ada.Finalization'Elab_Spec;
27078 E58 := True;
27079 Ada.Finalization.List_Controller'Elab_Spec;
27080 E76 := True;
27081 System.File_Control_Block'Elab_Spec;
27082 E74 := True;
27083 System.File_Io'Elab_Body;
27084 E56 := True;
27085 Ada.Tags'Elab_Body;
27086 E45 := True;
27087 Ada.Text_Io'Elab_Spec;
27088 Ada.Text_Io'Elab_Body;
27089 E07 := True;
27090 @end smallexample
27091
27092 @noindent
27093 Here Elab_Spec elaborates the spec
27094 and Elab_Body elaborates the body. The assignments to the Exx flags
27095 flag that the corresponding body is now elaborated.
27096
27097 You can also ask the binder to generate a more
27098 readable list of the elaboration order using the
27099 @code{-l} switch when invoking the binder. Here is
27100 an example of the output generated by this switch:
27101
27102 @smallexample
27103 ada (spec)
27104 interfaces (spec)
27105 system (spec)
27106 system.case_util (spec)
27107 system.case_util (body)
27108 system.concat_2 (spec)
27109 system.concat_2 (body)
27110 system.concat_3 (spec)
27111 system.concat_3 (body)
27112 system.htable (spec)
27113 system.parameters (spec)
27114 system.parameters (body)
27115 system.crtl (spec)
27116 interfaces.c_streams (spec)
27117 interfaces.c_streams (body)
27118 system.restrictions (spec)
27119 system.restrictions (body)
27120 system.standard_library (spec)
27121 system.exceptions (spec)
27122 system.exceptions (body)
27123 system.storage_elements (spec)
27124 system.storage_elements (body)
27125 system.secondary_stack (spec)
27126 system.stack_checking (spec)
27127 system.stack_checking (body)
27128 system.string_hash (spec)
27129 system.string_hash (body)
27130 system.htable (body)
27131 system.strings (spec)
27132 system.strings (body)
27133 system.traceback (spec)
27134 system.traceback (body)
27135 system.traceback_entries (spec)
27136 system.traceback_entries (body)
27137 ada.exceptions (spec)
27138 ada.exceptions.last_chance_handler (spec)
27139 system.soft_links (spec)
27140 system.soft_links (body)
27141 ada.exceptions.last_chance_handler (body)
27142 system.secondary_stack (body)
27143 system.exception_table (spec)
27144 system.exception_table (body)
27145 ada.io_exceptions (spec)
27146 ada.tags (spec)
27147 ada.streams (spec)
27148 interfaces.c (spec)
27149 interfaces.c (body)
27150 system.finalization_root (spec)
27151 system.finalization_root (body)
27152 system.memory (spec)
27153 system.memory (body)
27154 system.standard_library (body)
27155 system.os_lib (spec)
27156 system.os_lib (body)
27157 system.unsigned_types (spec)
27158 system.stream_attributes (spec)
27159 system.stream_attributes (body)
27160 system.finalization_implementation (spec)
27161 system.finalization_implementation (body)
27162 ada.finalization (spec)
27163 ada.finalization (body)
27164 ada.finalization.list_controller (spec)
27165 ada.finalization.list_controller (body)
27166 system.file_control_block (spec)
27167 system.file_io (spec)
27168 system.file_io (body)
27169 system.val_uns (spec)
27170 system.val_util (spec)
27171 system.val_util (body)
27172 system.val_uns (body)
27173 system.wch_con (spec)
27174 system.wch_con (body)
27175 system.wch_cnv (spec)
27176 system.wch_jis (spec)
27177 system.wch_jis (body)
27178 system.wch_cnv (body)
27179 system.wch_stw (spec)
27180 system.wch_stw (body)
27181 ada.tags (body)
27182 ada.exceptions (body)
27183 ada.text_io (spec)
27184 ada.text_io (body)
27185 text_io (spec)
27186 gdbstr (body)
27187 @end smallexample
27188
27189 @c **********************************
27190 @node Overflow Check Handling in GNAT
27191 @appendix Overflow Check Handling in GNAT
27192 @cindex Overflow checks
27193 @cindex Checks (overflow)
27194 @c **********************************
27195
27196 @menu
27197 * Background::
27198 * Overflow Checking Modes in GNAT::
27199 * Specifying the Desired Mode::
27200 * Default Settings::
27201 * Implementation Notes::
27202 @end menu
27203
27204
27205 @node Background
27206 @section Background
27207
27208 @noindent
27209 Overflow checks are checks that the compiler may make to ensure
27210 that intermediate results are not out of range. For example:
27211
27212 @smallexample @c ada
27213 A : Integer;
27214 ...
27215 A := A + 1;
27216 @end smallexample
27217
27218 @noindent
27219 if @code{A} has the value @code{Integer'Last}, then the addition may cause
27220 overflow since the result is out of range of the type @code{Integer}.
27221 In this case @code{Constraint_Error} will be raised if checks are
27222 enabled.
27223
27224 A trickier situation arises in examples like the following:
27225
27226 @smallexample @c ada
27227 A, C : Integer;
27228 ...
27229 A := (A + 1) + C;
27230 @end smallexample
27231
27232 @noindent
27233 where @code{A} is @code{Integer'Last} and @code{C} is @code{-1}.
27234 Now the final result of the expression on the right hand side is
27235 @code{Integer'Last} which is in range, but the question arises whether the
27236 intermediate addition of @code{(A + 1)} raises an overflow error.
27237
27238 The (perhaps surprising) answer is that the Ada language
27239 definition does not answer this question. Instead it leaves
27240 it up to the implementation to do one of two things if overflow
27241 checks are enabled.
27242
27243 @itemize @bullet
27244 @item
27245 raise an exception (@code{Constraint_Error}), or
27246
27247 @item
27248 yield the correct mathematical result which is then used in
27249 subsequent operations.
27250 @end itemize
27251
27252 @noindent
27253 If the compiler chooses the first approach, then the assignment of this
27254 example will indeed raise @code{Constraint_Error} if overflow checking is
27255 enabled, or result in erroneous execution if overflow checks are suppressed.
27256
27257 But if the compiler
27258 chooses the second approach, then it can perform both additions yielding
27259 the correct mathematical result, which is in range, so no exception
27260 will be raised, and the right result is obtained, regardless of whether
27261 overflow checks are suppressed.
27262
27263 Note that in the first example an
27264 exception will be raised in either case, since if the compiler
27265 gives the correct mathematical result for the addition, it will
27266 be out of range of the target type of the assignment, and thus
27267 fails the range check.
27268
27269 This lack of specified behavior in the handling of overflow for
27270 intermediate results is a source of non-portability, and can thus
27271 be problematic when programs are ported. Most typically this arises
27272 in a situation where the original compiler did not raise an exception,
27273 and then the application is moved to a compiler where the check is
27274 performed on the intermediate result and an unexpected exception is
27275 raised.
27276
27277 Furthermore, when using Ada 2012's preconditions and other
27278 assertion forms, another issue arises. Consider:
27279
27280 @smallexample @c ada
27281 procedure P (A, B : Integer) with
27282 Pre => A + B <= Integer'Last;
27283 @end smallexample
27284
27285 @noindent
27286 One often wants to regard arithmetic in a context like this from
27287 a mathematical point of view. So for example, if the two actual parameters
27288 for a call to @code{P} are both @code{Integer'Last}, then
27289 the precondition should be regarded as False. If we are executing
27290 in a mode with run-time checks enabled for preconditions, then we would
27291 like this precondition to fail, rather than raising an exception
27292 because of the intermediate overflow.
27293
27294 However, the language definition leaves the specification of
27295 whether the above condition fails (raising @code{Assert_Error}) or
27296 causes an intermediate overflow (raising @code{Constraint_Error})
27297 up to the implementation.
27298
27299 The situation is worse in a case such as the following:
27300
27301 @smallexample @c ada
27302 procedure Q (A, B, C : Integer) with
27303 Pre => A + B + C <= Integer'Last;
27304 @end smallexample
27305
27306 @noindent
27307 Consider the call
27308
27309 @smallexample @c ada
27310 Q (A => Integer'Last, B => 1, C => -1);
27311 @end smallexample
27312
27313 @noindent
27314 From a mathematical point of view the precondition
27315 is True, but at run time we may (but are not guaranteed to) get an
27316 exception raised because of the intermediate overflow (and we really
27317 would prefer this precondition to be considered True at run time).
27318
27319 @node Overflow Checking Modes in GNAT
27320 @section Overflow Checking Modes in GNAT
27321
27322 @noindent
27323 To deal with the portability issue, and with the problem of
27324 mathematical versus run-time interpretation of the expressions in
27325 assertions, GNAT provides comprehensive control over the handling
27326 of intermediate overflow. GNAT can operate in three modes, and
27327 furthemore, permits separate selection of operating modes for
27328 the expressions within assertions (here the term ``assertions''
27329 is used in the technical sense, which includes preconditions and so forth)
27330 and for expressions appearing outside assertions.
27331
27332 The three modes are:
27333
27334 @itemize @bullet
27335 @item @i{Use base type for intermediate operations} (@code{STRICT})
27336
27337 In this mode, all intermediate results for predefined arithmetic
27338 operators are computed using the base type, and the result must
27339 be in range of the base type. If this is not the
27340 case then either an exception is raised (if overflow checks are
27341 enabled) or the execution is erroneous (if overflow checks are suppressed).
27342 This is the normal default mode.
27343
27344 @item @i{Most intermediate overflows avoided} (@code{MINIMIZED})
27345
27346 In this mode, the compiler attempts to avoid intermediate overflows by
27347 using a larger integer type, typically @code{Long_Long_Integer},
27348 as the type in which arithmetic is
27349 performed for predefined arithmetic operators. This may be slightly more
27350 expensive at
27351 run time (compared to suppressing intermediate overflow checks), though
27352 the cost is negligible on modern 64-bit machines. For the examples given
27353 earlier, no intermediate overflows would have resulted in exceptions,
27354 since the intermediate results are all in the range of
27355 @code{Long_Long_Integer} (typically 64-bits on nearly all implementations
27356 of GNAT). In addition, if checks are enabled, this reduces the number of
27357 checks that must be made, so this choice may actually result in an
27358 improvement in space and time behavior.
27359
27360 However, there are cases where @code{Long_Long_Integer} is not large
27361 enough, consider the following example:
27362
27363 @smallexample @c ada
27364 procedure R (A, B, C, D : Integer) with
27365 Pre => (A**2 * B**2) / (C**2 * D**2) <= 10;
27366 @end smallexample
27367
27368 where @code{A} = @code{B} = @code{C} = @code{D} = @code{Integer'Last}.
27369 Now the intermediate results are
27370 out of the range of @code{Long_Long_Integer} even though the final result
27371 is in range and the precondition is True (from a mathematical point
27372 of view). In such a case, operating in this mode, an overflow occurs
27373 for the intermediate computation (which is why this mode
27374 says @i{most} intermediate overflows are avoided). In this case,
27375 an exception is raised if overflow checks are enabled, and the
27376 execution is erroneous if overflow checks are suppressed.
27377
27378 @item @i{All intermediate overflows avoided} (@code{ELIMINATED})
27379
27380 In this mode, the compiler avoids all intermediate overflows
27381 by using arbitrary precision arithmetic as required. In this
27382 mode, the above example with @code{A**2 * B**2} would
27383 not cause intermediate overflow, because the intermediate result
27384 would be evaluated using sufficient precision, and the result
27385 of evaluating the precondition would be True.
27386
27387 This mode has the advantage of avoiding any intermediate
27388 overflows, but at the expense of significant run-time overhead,
27389 including the use of a library (included automatically in this
27390 mode) for multiple-precision arithmetic.
27391
27392 This mode provides cleaner semantics for assertions, since now
27393 the run-time behavior emulates true arithmetic behavior for the
27394 predefined arithmetic operators, meaning that there is never a
27395 conflict between the mathematical view of the assertion, and its
27396 run-time behavior.
27397
27398 Note that in this mode, the behavior is unaffected by whether or
27399 not overflow checks are suppressed, since overflow does not occur.
27400 It is possible for gigantic intermediate expressions to raise
27401 @code{Storage_Error} as a result of attempting to compute the
27402 results of such expressions (e.g. @code{Integer'Last ** Integer'Last})
27403 but overflow is impossible.
27404
27405
27406 @end itemize
27407
27408 @noindent
27409 Note that these modes apply only to the evaluation of predefined
27410 arithmetic, membership, and comparison operators for signed integer
27411 aritmetic.
27412
27413 For fixed-point arithmetic, checks can be suppressed. But if checks
27414 are enabled
27415 then fixed-point values are always checked for overflow against the
27416 base type for intermediate expressions (that is such checks always
27417 operate in the equivalent of @code{STRICT} mode).
27418
27419 For floating-point, on nearly all architectures, @code{Machine_Overflows}
27420 is False, and IEEE infinities are generated, so overflow exceptions
27421 are never raised. If you want to avoid infinities, and check that
27422 final results of expressions are in range, then you can declare a
27423 constrained floating-point type, and range checks will be carried
27424 out in the normal manner (with infinite values always failing all
27425 range checks).
27426
27427
27428 @c -------------------------
27429 @node Specifying the Desired Mode
27430 @section Specifying the Desired Mode
27431
27432 @noindent
27433 The desired mode of for handling intermediate overflow can be specified using
27434 either the @code{Overflow_Mode} pragma or an equivalent compiler switch.
27435 The pragma has the form
27436 @cindex pragma @code{Overflow_Mode}
27437
27438 @smallexample @c ada
27439 pragma Overflow_Mode ([General =>] MODE [, [Assertions =>] MODE]);
27440 @end smallexample
27441
27442 @noindent
27443 where @code{MODE} is one of
27444
27445 @itemize @bullet
27446 @item @code{STRICT}: intermediate overflows checked (using base type)
27447 @item @code{MINIMIZED}: minimize intermediate overflows
27448 @item @code{ELIMINATED}: eliminate intermediate overflows
27449 @end itemize
27450
27451 @noindent
27452 The case is ignored, so @code{MINIMIZED}, @code{Minimized} and
27453 @code{minimized} all have the same effect.
27454
27455 If only the @code{General} parameter is present, then the given @code{MODE}
27456 applies
27457 to expressions both within and outside assertions. If both arguments
27458 are present, then @code{General} applies to expressions outside assertions,
27459 and @code{Assertions} applies to expressions within assertions. For example:
27460
27461 @smallexample @c ada
27462 pragma Overflow_Mode
27463 (General => Minimized, Assertions => Eliminated);
27464 @end smallexample
27465
27466 @noindent
27467 specifies that general expressions outside assertions be evaluated
27468 in ``minimize intermediate overflows'' mode, and expressions within
27469 assertions be evaluated in ``eliminate intermediate overflows'' mode.
27470 This is often a reasonable choice, avoiding excessive overhead
27471 outside assertions, but assuring a high degree of portability
27472 when importing code from another compiler, while incurring
27473 the extra overhead for assertion expressions to ensure that
27474 the behavior at run time matches the expected mathematical
27475 behavior.
27476
27477 The @code{Overflow_Mode} pragma has the same scoping and placement
27478 rules as pragma @code{Suppress}, so it can occur either as a
27479 configuration pragma, specifying a default for the whole
27480 program, or in a declarative scope, where it applies to the
27481 remaining declarations and statements in that scope.
27482
27483 Note that pragma @code{Overflow_Mode} does not affect whether
27484 overflow checks are enabled or suppressed. It only controls the
27485 method used to compute intermediate values. To control whether
27486 overflow checking is enabled or suppressed, use pragma @code{Suppress}
27487 or @code{Unsuppress} in the usual manner
27488
27489 Additionally, a compiler switch @option{-gnato?} or @option{-gnato??}
27490 can be used to control the checking mode default (which can be subsequently
27491 overridden using pragmas).
27492 @cindex @option{-gnato?} (gcc)
27493 @cindex @option{-gnato??} (gcc)
27494
27495 Here `@code{?}' is one of the digits `@code{1}' through `@code{3}':
27496
27497 @itemize @bullet
27498 @item @code{1}:
27499 use base type for intermediate operations (@code{STRICT})
27500 @item @code{2}:
27501 minimize intermediate overflows (@code{MINIMIZED})
27502 @item @code{3}:
27503 eliminate intermediate overflows (@code{ELIMINATED})
27504 @end itemize
27505
27506 @noindent
27507 As with the pragma, if only one digit appears then it applies to all
27508 cases; if two digits are given, then the first applies outside
27509 assertions, and the second within assertions. Thus the equivalent
27510 of the example pragma above would be
27511 @option{^-gnato23^/OVERFLOW_CHECKS=23^}.
27512
27513 If no digits follow the @option{-gnato}, then it is equivalent to
27514 @option{^-gnato11^/OVERFLOW_CHECKS=11^},
27515 causing all intermediate operations to be computed using the base
27516 type (@code{STRICT} mode).
27517
27518 In addition to setting the mode used for computation of intermediate
27519 results, the @code{-gnato} switch also enables overflow checking (which
27520 is suppressed by default). It thus combines the effect of using
27521 a pragma @code{Overflow_Mode} and pragma @code{Unsuppress}.
27522
27523
27524 @c -------------------------
27525 @node Default Settings
27526 @section Default Settings
27527
27528 The default mode for overflow checks is
27529
27530 @smallexample
27531 General => Strict
27532 @end smallexample
27533
27534 @noindent
27535 which causes all computations both inside and outside assertions to use
27536 the base type. In addition overflow checks are suppressed.
27537
27538 This retains compatibility with previous versions of
27539 GNAT which suppressed overflow checks by default and always
27540 used the base type for computation of intermediate results.
27541
27542 The switch @option{-gnato} (with no digits following) is equivalent to
27543 @cindex @option{-gnato} (gcc)
27544
27545 @smallexample
27546 General => Strict
27547 @end smallexample
27548
27549 @noindent
27550 which causes overflow checking of all intermediate overflows
27551 both inside and outside assertions against the base type.
27552 This provides compatibility
27553 with this switch as implemented in previous versions of GNAT.
27554
27555 The pragma @code{Suppress (Overflow_Check)} disables overflow
27556 checking, but it has no effect on the method used for computing
27557 intermediate results.
27558
27559 The pragma @code{Unsuppress (Overflow_Check)} enables overflow
27560 checking, but it has no effect on the method used for computing
27561 intermediate results.
27562
27563 @c -------------------------
27564 @node Implementation Notes
27565 @section Implementation Notes
27566
27567 In practice on typical 64-bit machines, the @code{MINIMIZED} mode is
27568 reasonably efficient, and can be generally used. It also helps
27569 to ensure compatibility with code imported from some other
27570 compiler to GNAT.
27571
27572 Setting all intermediate overflows checking (@code{CHECKED} mode)
27573 makes sense if you want to
27574 make sure that your code is compatible with any other possible
27575 Ada implementation. This may be useful in ensuring portability
27576 for code that is to be exported to some other compiler than GNAT.
27577
27578
27579 The Ada standard allows the reassociation of expressions at
27580 the same precedence level if no parentheses are present. For
27581 example, @w{@code{A+B+C}} parses as though it were @w{@code{(A+B)+C}}, but
27582 the compiler can reintepret this as @w{@code{A+(B+C)}}, possibly
27583 introducing or eliminating an overflow exception. The GNAT
27584 compiler never takes advantage of this freedom, and the
27585 expression @w{@code{A+B+C}} will be evaluated as @w{@code{(A+B)+C}}.
27586 If you need the other order, you can write the parentheses
27587 explicitly @w{@code{A+(B+C)}} and GNAT will respect this order.
27588
27589 The use of @code{ELIMINATED} mode will cause the compiler to
27590 automatically include an appropriate arbitrary precision
27591 integer arithmetic package. The compiler will make calls
27592 to this package, though only in cases where it cannot be
27593 sure that @code{Long_Long_Integer} is sufficient to guard against
27594 intermediate overflows. This package does not use dynamic
27595 alllocation, but it does use the secondary stack, so an
27596 appropriate secondary stack package must be present (this
27597 is always true for standard full Ada, but may require
27598 specific steps for restricted run times such as ZFP).
27599
27600 Although @code{ELIMINATED} mode causes expressions to use arbitrary
27601 precision arithmetic, avoiding overflow, the final result
27602 must be in an appropriate range. This is true even if the
27603 final result is of type @code{[Long_[Long_]]Integer'Base}, which
27604 still has the same bounds as its associated constrained
27605 type at run-time.
27606
27607 Currently, the @code{ELIMINATED} mode is only available on target
27608 platforms for which @code{Long_Long_Integer} is 64-bits (nearly all GNAT
27609 platforms).
27610
27611 @c *******************************
27612 @node Conditional Compilation
27613 @appendix Conditional Compilation
27614 @c *******************************
27615 @cindex Conditional compilation
27616
27617 @noindent
27618 It is often necessary to arrange for a single source program
27619 to serve multiple purposes, where it is compiled in different
27620 ways to achieve these different goals. Some examples of the
27621 need for this feature are
27622
27623 @itemize @bullet
27624 @item Adapting a program to a different hardware environment
27625 @item Adapting a program to a different target architecture
27626 @item Turning debugging features on and off
27627 @item Arranging for a program to compile with different compilers
27628 @end itemize
27629
27630 @noindent
27631 In C, or C++, the typical approach would be to use the preprocessor
27632 that is defined as part of the language. The Ada language does not
27633 contain such a feature. This is not an oversight, but rather a very
27634 deliberate design decision, based on the experience that overuse of
27635 the preprocessing features in C and C++ can result in programs that
27636 are extremely difficult to maintain. For example, if we have ten
27637 switches that can be on or off, this means that there are a thousand
27638 separate programs, any one of which might not even be syntactically
27639 correct, and even if syntactically correct, the resulting program
27640 might not work correctly. Testing all combinations can quickly become
27641 impossible.
27642
27643 Nevertheless, the need to tailor programs certainly exists, and in
27644 this Appendix we will discuss how this can
27645 be achieved using Ada in general, and GNAT in particular.
27646
27647 @menu
27648 * Use of Boolean Constants::
27649 * Debugging - A Special Case::
27650 * Conditionalizing Declarations::
27651 * Use of Alternative Implementations::
27652 * Preprocessing::
27653 @end menu
27654
27655 @node Use of Boolean Constants
27656 @section Use of Boolean Constants
27657
27658 @noindent
27659 In the case where the difference is simply which code
27660 sequence is executed, the cleanest solution is to use Boolean
27661 constants to control which code is executed.
27662
27663 @smallexample @c ada
27664 @group
27665 FP_Initialize_Required : constant Boolean := True;
27666 @dots{}
27667 if FP_Initialize_Required then
27668 @dots{}
27669 end if;
27670 @end group
27671 @end smallexample
27672
27673 @noindent
27674 Not only will the code inside the @code{if} statement not be executed if
27675 the constant Boolean is @code{False}, but it will also be completely
27676 deleted from the program.
27677 However, the code is only deleted after the @code{if} statement
27678 has been checked for syntactic and semantic correctness.
27679 (In contrast, with preprocessors the code is deleted before the
27680 compiler ever gets to see it, so it is not checked until the switch
27681 is turned on.)
27682 @cindex Preprocessors (contrasted with conditional compilation)
27683
27684 Typically the Boolean constants will be in a separate package,
27685 something like:
27686
27687 @smallexample @c ada
27688 @group
27689 package Config is
27690 FP_Initialize_Required : constant Boolean := True;
27691 Reset_Available : constant Boolean := False;
27692 @dots{}
27693 end Config;
27694 @end group
27695 @end smallexample
27696
27697 @noindent
27698 The @code{Config} package exists in multiple forms for the various targets,
27699 with an appropriate script selecting the version of @code{Config} needed.
27700 Then any other unit requiring conditional compilation can do a @code{with}
27701 of @code{Config} to make the constants visible.
27702
27703
27704 @node Debugging - A Special Case
27705 @section Debugging - A Special Case
27706
27707 @noindent
27708 A common use of conditional code is to execute statements (for example
27709 dynamic checks, or output of intermediate results) under control of a
27710 debug switch, so that the debugging behavior can be turned on and off.
27711 This can be done using a Boolean constant to control whether the code
27712 is active:
27713
27714 @smallexample @c ada
27715 @group
27716 if Debugging then
27717 Put_Line ("got to the first stage!");
27718 end if;
27719 @end group
27720 @end smallexample
27721
27722 @noindent
27723 or
27724
27725 @smallexample @c ada
27726 @group
27727 if Debugging and then Temperature > 999.0 then
27728 raise Temperature_Crazy;
27729 end if;
27730 @end group
27731 @end smallexample
27732
27733 @noindent
27734 Since this is a common case, there are special features to deal with
27735 this in a convenient manner. For the case of tests, Ada 2005 has added
27736 a pragma @code{Assert} that can be used for such tests. This pragma is modeled
27737 @cindex pragma @code{Assert}
27738 on the @code{Assert} pragma that has always been available in GNAT, so this
27739 feature may be used with GNAT even if you are not using Ada 2005 features.
27740 The use of pragma @code{Assert} is described in
27741 @ref{Pragma Assert,,, gnat_rm, GNAT Reference Manual}, but as an
27742 example, the last test could be written:
27743
27744 @smallexample @c ada
27745 pragma Assert (Temperature <= 999.0, "Temperature Crazy");
27746 @end smallexample
27747
27748 @noindent
27749 or simply
27750
27751 @smallexample @c ada
27752 pragma Assert (Temperature <= 999.0);
27753 @end smallexample
27754
27755 @noindent
27756 In both cases, if assertions are active and the temperature is excessive,
27757 the exception @code{Assert_Failure} will be raised, with the given string in
27758 the first case or a string indicating the location of the pragma in the second
27759 case used as the exception message.
27760
27761 You can turn assertions on and off by using the @code{Assertion_Policy}
27762 pragma.
27763 @cindex pragma @code{Assertion_Policy}
27764 This is an Ada 2005 pragma which is implemented in all modes by
27765 GNAT, but only in the latest versions of GNAT which include Ada 2005
27766 capability. Alternatively, you can use the @option{-gnata} switch
27767 @cindex @option{-gnata} switch
27768 to enable assertions from the command line (this is recognized by all versions
27769 of GNAT).
27770
27771 For the example above with the @code{Put_Line}, the GNAT-specific pragma
27772 @code{Debug} can be used:
27773 @cindex pragma @code{Debug}
27774
27775 @smallexample @c ada
27776 pragma Debug (Put_Line ("got to the first stage!"));
27777 @end smallexample
27778
27779 @noindent
27780 If debug pragmas are enabled, the argument, which must be of the form of
27781 a procedure call, is executed (in this case, @code{Put_Line} will be called).
27782 Only one call can be present, but of course a special debugging procedure
27783 containing any code you like can be included in the program and then
27784 called in a pragma @code{Debug} argument as needed.
27785
27786 One advantage of pragma @code{Debug} over the @code{if Debugging then}
27787 construct is that pragma @code{Debug} can appear in declarative contexts,
27788 such as at the very beginning of a procedure, before local declarations have
27789 been elaborated.
27790
27791 Debug pragmas are enabled using either the @option{-gnata} switch that also
27792 controls assertions, or with a separate Debug_Policy pragma.
27793 @cindex pragma @code{Debug_Policy}
27794 The latter pragma is new in the Ada 2005 versions of GNAT (but it can be used
27795 in Ada 95 and Ada 83 programs as well), and is analogous to
27796 pragma @code{Assertion_Policy} to control assertions.
27797
27798 @code{Assertion_Policy} and @code{Debug_Policy} are configuration pragmas,
27799 and thus they can appear in @file{gnat.adc} if you are not using a
27800 project file, or in the file designated to contain configuration pragmas
27801 in a project file.
27802 They then apply to all subsequent compilations. In practice the use of
27803 the @option{-gnata} switch is often the most convenient method of controlling
27804 the status of these pragmas.
27805
27806 Note that a pragma is not a statement, so in contexts where a statement
27807 sequence is required, you can't just write a pragma on its own. You have
27808 to add a @code{null} statement.
27809
27810 @smallexample @c ada
27811 @group
27812 if @dots{} then
27813 @dots{} -- some statements
27814 else
27815 pragma Assert (Num_Cases < 10);
27816 null;
27817 end if;
27818 @end group
27819 @end smallexample
27820
27821
27822 @node Conditionalizing Declarations
27823 @section Conditionalizing Declarations
27824
27825 @noindent
27826 In some cases, it may be necessary to conditionalize declarations to meet
27827 different requirements. For example we might want a bit string whose length
27828 is set to meet some hardware message requirement.
27829
27830 In some cases, it may be possible to do this using declare blocks controlled
27831 by conditional constants:
27832
27833 @smallexample @c ada
27834 @group
27835 if Small_Machine then
27836 declare
27837 X : Bit_String (1 .. 10);
27838 begin
27839 @dots{}
27840 end;
27841 else
27842 declare
27843 X : Large_Bit_String (1 .. 1000);
27844 begin
27845 @dots{}
27846 end;
27847 end if;
27848 @end group
27849 @end smallexample
27850
27851 @noindent
27852 Note that in this approach, both declarations are analyzed by the
27853 compiler so this can only be used where both declarations are legal,
27854 even though one of them will not be used.
27855
27856 Another approach is to define integer constants, e.g.@: @code{Bits_Per_Word},
27857 or Boolean constants, e.g.@: @code{Little_Endian}, and then write declarations
27858 that are parameterized by these constants. For example
27859
27860 @smallexample @c ada
27861 @group
27862 for Rec use
27863 Field1 at 0 range Boolean'Pos (Little_Endian) * 10 .. Bits_Per_Word;
27864 end record;
27865 @end group
27866 @end smallexample
27867
27868 @noindent
27869 If @code{Bits_Per_Word} is set to 32, this generates either
27870
27871 @smallexample @c ada
27872 @group
27873 for Rec use
27874 Field1 at 0 range 0 .. 32;
27875 end record;
27876 @end group
27877 @end smallexample
27878
27879 @noindent
27880 for the big endian case, or
27881
27882 @smallexample @c ada
27883 @group
27884 for Rec use record
27885 Field1 at 0 range 10 .. 32;
27886 end record;
27887 @end group
27888 @end smallexample
27889
27890 @noindent
27891 for the little endian case. Since a powerful subset of Ada expression
27892 notation is usable for creating static constants, clever use of this
27893 feature can often solve quite difficult problems in conditionalizing
27894 compilation (note incidentally that in Ada 95, the little endian
27895 constant was introduced as @code{System.Default_Bit_Order}, so you do not
27896 need to define this one yourself).
27897
27898
27899 @node Use of Alternative Implementations
27900 @section Use of Alternative Implementations
27901
27902 @noindent
27903 In some cases, none of the approaches described above are adequate. This
27904 can occur for example if the set of declarations required is radically
27905 different for two different configurations.
27906
27907 In this situation, the official Ada way of dealing with conditionalizing
27908 such code is to write separate units for the different cases. As long as
27909 this does not result in excessive duplication of code, this can be done
27910 without creating maintenance problems. The approach is to share common
27911 code as far as possible, and then isolate the code and declarations
27912 that are different. Subunits are often a convenient method for breaking
27913 out a piece of a unit that is to be conditionalized, with separate files
27914 for different versions of the subunit for different targets, where the
27915 build script selects the right one to give to the compiler.
27916 @cindex Subunits (and conditional compilation)
27917
27918 As an example, consider a situation where a new feature in Ada 2005
27919 allows something to be done in a really nice way. But your code must be able
27920 to compile with an Ada 95 compiler. Conceptually you want to say:
27921
27922 @smallexample @c ada
27923 @group
27924 if Ada_2005 then
27925 @dots{} neat Ada 2005 code
27926 else
27927 @dots{} not quite as neat Ada 95 code
27928 end if;
27929 @end group
27930 @end smallexample
27931
27932 @noindent
27933 where @code{Ada_2005} is a Boolean constant.
27934
27935 But this won't work when @code{Ada_2005} is set to @code{False},
27936 since the @code{then} clause will be illegal for an Ada 95 compiler.
27937 (Recall that although such unreachable code would eventually be deleted
27938 by the compiler, it still needs to be legal. If it uses features
27939 introduced in Ada 2005, it will be illegal in Ada 95.)
27940
27941 So instead we write
27942
27943 @smallexample @c ada
27944 procedure Insert is separate;
27945 @end smallexample
27946
27947 @noindent
27948 Then we have two files for the subunit @code{Insert}, with the two sets of
27949 code.
27950 If the package containing this is called @code{File_Queries}, then we might
27951 have two files
27952
27953 @itemize @bullet
27954 @item @file{file_queries-insert-2005.adb}
27955 @item @file{file_queries-insert-95.adb}
27956 @end itemize
27957
27958 @noindent
27959 and the build script renames the appropriate file to
27960
27961 @smallexample
27962 file_queries-insert.adb
27963 @end smallexample
27964
27965 @noindent
27966 and then carries out the compilation.
27967
27968 This can also be done with project files' naming schemes. For example:
27969
27970 @smallexample @c project
27971 For Body ("File_Queries.Insert") use "file_queries-insert-2005.ada";
27972 @end smallexample
27973
27974 @noindent
27975 Note also that with project files it is desirable to use a different extension
27976 than @file{ads} / @file{adb} for alternative versions. Otherwise a naming
27977 conflict may arise through another commonly used feature: to declare as part
27978 of the project a set of directories containing all the sources obeying the
27979 default naming scheme.
27980
27981 The use of alternative units is certainly feasible in all situations,
27982 and for example the Ada part of the GNAT run-time is conditionalized
27983 based on the target architecture using this approach. As a specific example,
27984 consider the implementation of the AST feature in VMS. There is one
27985 spec:
27986
27987 @smallexample
27988 s-asthan.ads
27989 @end smallexample
27990
27991 @noindent
27992 which is the same for all architectures, and three bodies:
27993
27994 @table @file
27995 @item s-asthan.adb
27996 used for all non-VMS operating systems
27997 @item s-asthan-vms-alpha.adb
27998 used for VMS on the Alpha
27999 @item s-asthan-vms-ia64.adb
28000 used for VMS on the ia64
28001 @end table
28002
28003 @noindent
28004 The dummy version @file{s-asthan.adb} simply raises exceptions noting that
28005 this operating system feature is not available, and the two remaining
28006 versions interface with the corresponding versions of VMS to provide
28007 VMS-compatible AST handling. The GNAT build script knows the architecture
28008 and operating system, and automatically selects the right version,
28009 renaming it if necessary to @file{s-asthan.adb} before the run-time build.
28010
28011 Another style for arranging alternative implementations is through Ada's
28012 access-to-subprogram facility.
28013 In case some functionality is to be conditionally included,
28014 you can declare an access-to-procedure variable @code{Ref} that is initialized
28015 to designate a ``do nothing'' procedure, and then invoke @code{Ref.all}
28016 when appropriate.
28017 In some library package, set @code{Ref} to @code{Proc'Access} for some
28018 procedure @code{Proc} that performs the relevant processing.
28019 The initialization only occurs if the library package is included in the
28020 program.
28021 The same idea can also be implemented using tagged types and dispatching
28022 calls.
28023
28024
28025 @node Preprocessing
28026 @section Preprocessing
28027 @cindex Preprocessing
28028
28029 @noindent
28030 Although it is quite possible to conditionalize code without the use of
28031 C-style preprocessing, as described earlier in this section, it is
28032 nevertheless convenient in some cases to use the C approach. Moreover,
28033 older Ada compilers have often provided some preprocessing capability,
28034 so legacy code may depend on this approach, even though it is not
28035 standard.
28036
28037 To accommodate such use, GNAT provides a preprocessor (modeled to a large
28038 extent on the various preprocessors that have been used
28039 with legacy code on other compilers, to enable easier transition).
28040
28041 The preprocessor may be used in two separate modes. It can be used quite
28042 separately from the compiler, to generate a separate output source file
28043 that is then fed to the compiler as a separate step. This is the
28044 @code{gnatprep} utility, whose use is fully described in
28045 @ref{Preprocessing with gnatprep}.
28046 @cindex @code{gnatprep}
28047
28048 The preprocessing language allows such constructs as
28049
28050 @smallexample
28051 @group
28052 #if DEBUG or else (PRIORITY > 4) then
28053 bunch of declarations
28054 #else
28055 completely different bunch of declarations
28056 #end if;
28057 @end group
28058 @end smallexample
28059
28060 @noindent
28061 The values of the symbols @code{DEBUG} and @code{PRIORITY} can be
28062 defined either on the command line or in a separate file.
28063
28064 The other way of running the preprocessor is even closer to the C style and
28065 often more convenient. In this approach the preprocessing is integrated into
28066 the compilation process. The compiler is fed the preprocessor input which
28067 includes @code{#if} lines etc, and then the compiler carries out the
28068 preprocessing internally and processes the resulting output.
28069 For more details on this approach, see @ref{Integrated Preprocessing}.
28070
28071
28072 @c *******************************
28073 @node Inline Assembler
28074 @appendix Inline Assembler
28075 @c *******************************
28076
28077 @noindent
28078 If you need to write low-level software that interacts directly
28079 with the hardware, Ada provides two ways to incorporate assembly
28080 language code into your program. First, you can import and invoke
28081 external routines written in assembly language, an Ada feature fully
28082 supported by GNAT@. However, for small sections of code it may be simpler
28083 or more efficient to include assembly language statements directly
28084 in your Ada source program, using the facilities of the implementation-defined
28085 package @code{System.Machine_Code}, which incorporates the gcc
28086 Inline Assembler. The Inline Assembler approach offers a number of advantages,
28087 including the following:
28088
28089 @itemize @bullet
28090 @item No need to use non-Ada tools
28091 @item Consistent interface over different targets
28092 @item Automatic usage of the proper calling conventions
28093 @item Access to Ada constants and variables
28094 @item Definition of intrinsic routines
28095 @item Possibility of inlining a subprogram comprising assembler code
28096 @item Code optimizer can take Inline Assembler code into account
28097 @end itemize
28098
28099 This chapter presents a series of examples to show you how to use
28100 the Inline Assembler. Although it focuses on the Intel x86,
28101 the general approach applies also to other processors.
28102 It is assumed that you are familiar with Ada
28103 and with assembly language programming.
28104
28105 @menu
28106 * Basic Assembler Syntax::
28107 * A Simple Example of Inline Assembler::
28108 * Output Variables in Inline Assembler::
28109 * Input Variables in Inline Assembler::
28110 * Inlining Inline Assembler Code::
28111 * Other Asm Functionality::
28112 @end menu
28113
28114 @c ---------------------------------------------------------------------------
28115 @node Basic Assembler Syntax
28116 @section Basic Assembler Syntax
28117
28118 @noindent
28119 The assembler used by GNAT and gcc is based not on the Intel assembly
28120 language, but rather on a language that descends from the AT&T Unix
28121 assembler @emph{as} (and which is often referred to as ``AT&T syntax'').
28122 The following table summarizes the main features of @emph{as} syntax
28123 and points out the differences from the Intel conventions.
28124 See the gcc @emph{as} and @emph{gas} (an @emph{as} macro
28125 pre-processor) documentation for further information.
28126
28127 @table @asis
28128 @item Register names
28129 gcc / @emph{as}: Prefix with ``%''; for example @code{%eax}
28130 @*
28131 Intel: No extra punctuation; for example @code{eax}
28132
28133 @item Immediate operand
28134 gcc / @emph{as}: Prefix with ``$''; for example @code{$4}
28135 @*
28136 Intel: No extra punctuation; for example @code{4}
28137
28138 @item Address
28139 gcc / @emph{as}: Prefix with ``$''; for example @code{$loc}
28140 @*
28141 Intel: No extra punctuation; for example @code{loc}
28142
28143 @item Memory contents
28144 gcc / @emph{as}: No extra punctuation; for example @code{loc}
28145 @*
28146 Intel: Square brackets; for example @code{[loc]}
28147
28148 @item Register contents
28149 gcc / @emph{as}: Parentheses; for example @code{(%eax)}
28150 @*
28151 Intel: Square brackets; for example @code{[eax]}
28152
28153 @item Hexadecimal numbers
28154 gcc / @emph{as}: Leading ``0x'' (C language syntax); for example @code{0xA0}
28155 @*
28156 Intel: Trailing ``h''; for example @code{A0h}
28157
28158 @item Operand size
28159 gcc / @emph{as}: Explicit in op code; for example @code{movw} to move
28160 a 16-bit word
28161 @*
28162 Intel: Implicit, deduced by assembler; for example @code{mov}
28163
28164 @item Instruction repetition
28165 gcc / @emph{as}: Split into two lines; for example
28166 @*
28167 @code{rep}
28168 @*
28169 @code{stosl}
28170 @*
28171 Intel: Keep on one line; for example @code{rep stosl}
28172
28173 @item Order of operands
28174 gcc / @emph{as}: Source first; for example @code{movw $4, %eax}
28175 @*
28176 Intel: Destination first; for example @code{mov eax, 4}
28177 @end table
28178
28179 @c ---------------------------------------------------------------------------
28180 @node A Simple Example of Inline Assembler
28181 @section A Simple Example of Inline Assembler
28182
28183 @noindent
28184 The following example will generate a single assembly language statement,
28185 @code{nop}, which does nothing. Despite its lack of run-time effect,
28186 the example will be useful in illustrating the basics of
28187 the Inline Assembler facility.
28188
28189 @smallexample @c ada
28190 @group
28191 with System.Machine_Code; use System.Machine_Code;
28192 procedure Nothing is
28193 begin
28194 Asm ("nop");
28195 end Nothing;
28196 @end group
28197 @end smallexample
28198
28199 @code{Asm} is a procedure declared in package @code{System.Machine_Code};
28200 here it takes one parameter, a @emph{template string} that must be a static
28201 expression and that will form the generated instruction.
28202 @code{Asm} may be regarded as a compile-time procedure that parses
28203 the template string and additional parameters (none here),
28204 from which it generates a sequence of assembly language instructions.
28205
28206 The examples in this chapter will illustrate several of the forms
28207 for invoking @code{Asm}; a complete specification of the syntax
28208 is found in @ref{Machine Code Insertions,,, gnat_rm, GNAT Reference
28209 Manual}.
28210
28211 Under the standard GNAT conventions, the @code{Nothing} procedure
28212 should be in a file named @file{nothing.adb}.
28213 You can build the executable in the usual way:
28214 @smallexample
28215 gnatmake nothing
28216 @end smallexample
28217 However, the interesting aspect of this example is not its run-time behavior
28218 but rather the generated assembly code.
28219 To see this output, invoke the compiler as follows:
28220 @smallexample
28221 gcc -c -S -fomit-frame-pointer -gnatp @file{nothing.adb}
28222 @end smallexample
28223 where the options are:
28224
28225 @table @code
28226 @item -c
28227 compile only (no bind or link)
28228 @item -S
28229 generate assembler listing
28230 @item -fomit-frame-pointer
28231 do not set up separate stack frames
28232 @item -gnatp
28233 do not add runtime checks
28234 @end table
28235
28236 This gives a human-readable assembler version of the code. The resulting
28237 file will have the same name as the Ada source file, but with a @code{.s}
28238 extension. In our example, the file @file{nothing.s} has the following
28239 contents:
28240
28241 @smallexample
28242 @group
28243 .file "nothing.adb"
28244 gcc2_compiled.:
28245 ___gnu_compiled_ada:
28246 .text
28247 .align 4
28248 .globl __ada_nothing
28249 __ada_nothing:
28250 #APP
28251 nop
28252 #NO_APP
28253 jmp L1
28254 .align 2,0x90
28255 L1:
28256 ret
28257 @end group
28258 @end smallexample
28259
28260 The assembly code you included is clearly indicated by
28261 the compiler, between the @code{#APP} and @code{#NO_APP}
28262 delimiters. The character before the 'APP' and 'NOAPP'
28263 can differ on different targets. For example, GNU/Linux uses '#APP' while
28264 on NT you will see '/APP'.
28265
28266 If you make a mistake in your assembler code (such as using the
28267 wrong size modifier, or using a wrong operand for the instruction) GNAT
28268 will report this error in a temporary file, which will be deleted when
28269 the compilation is finished. Generating an assembler file will help
28270 in such cases, since you can assemble this file separately using the
28271 @emph{as} assembler that comes with gcc.
28272
28273 Assembling the file using the command
28274
28275 @smallexample
28276 as @file{nothing.s}
28277 @end smallexample
28278 @noindent
28279 will give you error messages whose lines correspond to the assembler
28280 input file, so you can easily find and correct any mistakes you made.
28281 If there are no errors, @emph{as} will generate an object file
28282 @file{nothing.out}.
28283
28284 @c ---------------------------------------------------------------------------
28285 @node Output Variables in Inline Assembler
28286 @section Output Variables in Inline Assembler
28287
28288 @noindent
28289 The examples in this section, showing how to access the processor flags,
28290 illustrate how to specify the destination operands for assembly language
28291 statements.
28292
28293 @smallexample @c ada
28294 @group
28295 with Interfaces; use Interfaces;
28296 with Ada.Text_IO; use Ada.Text_IO;
28297 with System.Machine_Code; use System.Machine_Code;
28298 procedure Get_Flags is
28299 Flags : Unsigned_32;
28300 use ASCII;
28301 begin
28302 Asm ("pushfl" & LF & HT & -- push flags on stack
28303 "popl %%eax" & LF & HT & -- load eax with flags
28304 "movl %%eax, %0", -- store flags in variable
28305 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28306 Put_Line ("Flags register:" & Flags'Img);
28307 end Get_Flags;
28308 @end group
28309 @end smallexample
28310
28311 In order to have a nicely aligned assembly listing, we have separated
28312 multiple assembler statements in the Asm template string with linefeed
28313 (ASCII.LF) and horizontal tab (ASCII.HT) characters.
28314 The resulting section of the assembly output file is:
28315
28316 @smallexample
28317 @group
28318 #APP
28319 pushfl
28320 popl %eax
28321 movl %eax, -40(%ebp)
28322 #NO_APP
28323 @end group
28324 @end smallexample
28325
28326 It would have been legal to write the Asm invocation as:
28327
28328 @smallexample
28329 Asm ("pushfl popl %%eax movl %%eax, %0")
28330 @end smallexample
28331
28332 but in the generated assembler file, this would come out as:
28333
28334 @smallexample
28335 #APP
28336 pushfl popl %eax movl %eax, -40(%ebp)
28337 #NO_APP
28338 @end smallexample
28339
28340 which is not so convenient for the human reader.
28341
28342 We use Ada comments
28343 at the end of each line to explain what the assembler instructions
28344 actually do. This is a useful convention.
28345
28346 When writing Inline Assembler instructions, you need to precede each register
28347 and variable name with a percent sign. Since the assembler already requires
28348 a percent sign at the beginning of a register name, you need two consecutive
28349 percent signs for such names in the Asm template string, thus @code{%%eax}.
28350 In the generated assembly code, one of the percent signs will be stripped off.
28351
28352 Names such as @code{%0}, @code{%1}, @code{%2}, etc., denote input or output
28353 variables: operands you later define using @code{Input} or @code{Output}
28354 parameters to @code{Asm}.
28355 An output variable is illustrated in
28356 the third statement in the Asm template string:
28357 @smallexample
28358 movl %%eax, %0
28359 @end smallexample
28360 The intent is to store the contents of the eax register in a variable that can
28361 be accessed in Ada. Simply writing @code{movl %%eax, Flags} would not
28362 necessarily work, since the compiler might optimize by using a register
28363 to hold Flags, and the expansion of the @code{movl} instruction would not be
28364 aware of this optimization. The solution is not to store the result directly
28365 but rather to advise the compiler to choose the correct operand form;
28366 that is the purpose of the @code{%0} output variable.
28367
28368 Information about the output variable is supplied in the @code{Outputs}
28369 parameter to @code{Asm}:
28370 @smallexample
28371 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28372 @end smallexample
28373
28374 The output is defined by the @code{Asm_Output} attribute of the target type;
28375 the general format is
28376 @smallexample
28377 Type'Asm_Output (constraint_string, variable_name)
28378 @end smallexample
28379
28380 The constraint string directs the compiler how
28381 to store/access the associated variable. In the example
28382 @smallexample
28383 Unsigned_32'Asm_Output ("=m", Flags);
28384 @end smallexample
28385 the @code{"m"} (memory) constraint tells the compiler that the variable
28386 @code{Flags} should be stored in a memory variable, thus preventing
28387 the optimizer from keeping it in a register. In contrast,
28388 @smallexample
28389 Unsigned_32'Asm_Output ("=r", Flags);
28390 @end smallexample
28391 uses the @code{"r"} (register) constraint, telling the compiler to
28392 store the variable in a register.
28393
28394 If the constraint is preceded by the equal character (@strong{=}), it tells
28395 the compiler that the variable will be used to store data into it.
28396
28397 In the @code{Get_Flags} example, we used the @code{"g"} (global) constraint,
28398 allowing the optimizer to choose whatever it deems best.
28399
28400 There are a fairly large number of constraints, but the ones that are
28401 most useful (for the Intel x86 processor) are the following:
28402
28403 @table @code
28404 @item =
28405 output constraint
28406 @item g
28407 global (i.e.@: can be stored anywhere)
28408 @item m
28409 in memory
28410 @item I
28411 a constant
28412 @item a
28413 use eax
28414 @item b
28415 use ebx
28416 @item c
28417 use ecx
28418 @item d
28419 use edx
28420 @item S
28421 use esi
28422 @item D
28423 use edi
28424 @item r
28425 use one of eax, ebx, ecx or edx
28426 @item q
28427 use one of eax, ebx, ecx, edx, esi or edi
28428 @end table
28429
28430 The full set of constraints is described in the gcc and @emph{as}
28431 documentation; note that it is possible to combine certain constraints
28432 in one constraint string.
28433
28434 You specify the association of an output variable with an assembler operand
28435 through the @code{%}@emph{n} notation, where @emph{n} is a non-negative
28436 integer. Thus in
28437 @smallexample @c ada
28438 @group
28439 Asm ("pushfl" & LF & HT & -- push flags on stack
28440 "popl %%eax" & LF & HT & -- load eax with flags
28441 "movl %%eax, %0", -- store flags in variable
28442 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28443 @end group
28444 @end smallexample
28445 @noindent
28446 @code{%0} will be replaced in the expanded code by the appropriate operand,
28447 whatever
28448 the compiler decided for the @code{Flags} variable.
28449
28450 In general, you may have any number of output variables:
28451 @itemize @bullet
28452 @item
28453 Count the operands starting at 0; thus @code{%0}, @code{%1}, etc.
28454 @item
28455 Specify the @code{Outputs} parameter as a parenthesized comma-separated list
28456 of @code{Asm_Output} attributes
28457 @end itemize
28458
28459 For example:
28460 @smallexample @c ada
28461 @group
28462 Asm ("movl %%eax, %0" & LF & HT &
28463 "movl %%ebx, %1" & LF & HT &
28464 "movl %%ecx, %2",
28465 Outputs => (Unsigned_32'Asm_Output ("=g", Var_A), -- %0 = Var_A
28466 Unsigned_32'Asm_Output ("=g", Var_B), -- %1 = Var_B
28467 Unsigned_32'Asm_Output ("=g", Var_C))); -- %2 = Var_C
28468 @end group
28469 @end smallexample
28470 @noindent
28471 where @code{Var_A}, @code{Var_B}, and @code{Var_C} are variables
28472 in the Ada program.
28473
28474 As a variation on the @code{Get_Flags} example, we can use the constraints
28475 string to direct the compiler to store the eax register into the @code{Flags}
28476 variable, instead of including the store instruction explicitly in the
28477 @code{Asm} template string:
28478
28479 @smallexample @c ada
28480 @group
28481 with Interfaces; use Interfaces;
28482 with Ada.Text_IO; use Ada.Text_IO;
28483 with System.Machine_Code; use System.Machine_Code;
28484 procedure Get_Flags_2 is
28485 Flags : Unsigned_32;
28486 use ASCII;
28487 begin
28488 Asm ("pushfl" & LF & HT & -- push flags on stack
28489 "popl %%eax", -- save flags in eax
28490 Outputs => Unsigned_32'Asm_Output ("=a", Flags));
28491 Put_Line ("Flags register:" & Flags'Img);
28492 end Get_Flags_2;
28493 @end group
28494 @end smallexample
28495
28496 @noindent
28497 The @code{"a"} constraint tells the compiler that the @code{Flags}
28498 variable will come from the eax register. Here is the resulting code:
28499
28500 @smallexample
28501 @group
28502 #APP
28503 pushfl
28504 popl %eax
28505 #NO_APP
28506 movl %eax,-40(%ebp)
28507 @end group
28508 @end smallexample
28509
28510 @noindent
28511 The compiler generated the store of eax into Flags after
28512 expanding the assembler code.
28513
28514 Actually, there was no need to pop the flags into the eax register;
28515 more simply, we could just pop the flags directly into the program variable:
28516
28517 @smallexample @c ada
28518 @group
28519 with Interfaces; use Interfaces;
28520 with Ada.Text_IO; use Ada.Text_IO;
28521 with System.Machine_Code; use System.Machine_Code;
28522 procedure Get_Flags_3 is
28523 Flags : Unsigned_32;
28524 use ASCII;
28525 begin
28526 Asm ("pushfl" & LF & HT & -- push flags on stack
28527 "pop %0", -- save flags in Flags
28528 Outputs => Unsigned_32'Asm_Output ("=g", Flags));
28529 Put_Line ("Flags register:" & Flags'Img);
28530 end Get_Flags_3;
28531 @end group
28532 @end smallexample
28533
28534 @c ---------------------------------------------------------------------------
28535 @node Input Variables in Inline Assembler
28536 @section Input Variables in Inline Assembler
28537
28538 @noindent
28539 The example in this section illustrates how to specify the source operands
28540 for assembly language statements.
28541 The program simply increments its input value by 1:
28542
28543 @smallexample @c ada
28544 @group
28545 with Interfaces; use Interfaces;
28546 with Ada.Text_IO; use Ada.Text_IO;
28547 with System.Machine_Code; use System.Machine_Code;
28548 procedure Increment is
28549
28550 function Incr (Value : Unsigned_32) return Unsigned_32 is
28551 Result : Unsigned_32;
28552 begin
28553 Asm ("incl %0",
28554 Outputs => Unsigned_32'Asm_Output ("=a", Result),
28555 Inputs => Unsigned_32'Asm_Input ("a", Value));
28556 return Result;
28557 end Incr;
28558
28559 Value : Unsigned_32;
28560
28561 begin
28562 Value := 5;
28563 Put_Line ("Value before is" & Value'Img);
28564 Value := Incr (Value);
28565 Put_Line ("Value after is" & Value'Img);
28566 end Increment;
28567 @end group
28568 @end smallexample
28569
28570 The @code{Outputs} parameter to @code{Asm} specifies
28571 that the result will be in the eax register and that it is to be stored
28572 in the @code{Result} variable.
28573
28574 The @code{Inputs} parameter looks much like the @code{Outputs} parameter,
28575 but with an @code{Asm_Input} attribute.
28576 The @code{"="} constraint, indicating an output value, is not present.
28577
28578 You can have multiple input variables, in the same way that you can have more
28579 than one output variable.
28580
28581 The parameter count (%0, %1) etc, still starts at the first output statement,
28582 and continues with the input statements.
28583
28584 Just as the @code{Outputs} parameter causes the register to be stored into the
28585 target variable after execution of the assembler statements, so does the
28586 @code{Inputs} parameter cause its variable to be loaded into the register
28587 before execution of the assembler statements.
28588
28589 Thus the effect of the @code{Asm} invocation is:
28590 @enumerate
28591 @item load the 32-bit value of @code{Value} into eax
28592 @item execute the @code{incl %eax} instruction
28593 @item store the contents of eax into the @code{Result} variable
28594 @end enumerate
28595
28596 The resulting assembler file (with @option{-O2} optimization) contains:
28597 @smallexample
28598 @group
28599 _increment__incr.1:
28600 subl $4,%esp
28601 movl 8(%esp),%eax
28602 #APP
28603 incl %eax
28604 #NO_APP
28605 movl %eax,%edx
28606 movl %ecx,(%esp)
28607 addl $4,%esp
28608 ret
28609 @end group
28610 @end smallexample
28611
28612 @c ---------------------------------------------------------------------------
28613 @node Inlining Inline Assembler Code
28614 @section Inlining Inline Assembler Code
28615
28616 @noindent
28617 For a short subprogram such as the @code{Incr} function in the previous
28618 section, the overhead of the call and return (creating / deleting the stack
28619 frame) can be significant, compared to the amount of code in the subprogram
28620 body. A solution is to apply Ada's @code{Inline} pragma to the subprogram,
28621 which directs the compiler to expand invocations of the subprogram at the
28622 point(s) of call, instead of setting up a stack frame for out-of-line calls.
28623 Here is the resulting program:
28624
28625 @smallexample @c ada
28626 @group
28627 with Interfaces; use Interfaces;
28628 with Ada.Text_IO; use Ada.Text_IO;
28629 with System.Machine_Code; use System.Machine_Code;
28630 procedure Increment_2 is
28631
28632 function Incr (Value : Unsigned_32) return Unsigned_32 is
28633 Result : Unsigned_32;
28634 begin
28635 Asm ("incl %0",
28636 Outputs => Unsigned_32'Asm_Output ("=a", Result),
28637 Inputs => Unsigned_32'Asm_Input ("a", Value));
28638 return Result;
28639 end Incr;
28640 pragma Inline (Increment);
28641
28642 Value : Unsigned_32;
28643
28644 begin
28645 Value := 5;
28646 Put_Line ("Value before is" & Value'Img);
28647 Value := Increment (Value);
28648 Put_Line ("Value after is" & Value'Img);
28649 end Increment_2;
28650 @end group
28651 @end smallexample
28652
28653 Compile the program with both optimization (@option{-O2}) and inlining
28654 (@option{-gnatn}) enabled.
28655
28656 The @code{Incr} function is still compiled as usual, but at the
28657 point in @code{Increment} where our function used to be called:
28658
28659 @smallexample
28660 @group
28661 pushl %edi
28662 call _increment__incr.1
28663 @end group
28664 @end smallexample
28665
28666 @noindent
28667 the code for the function body directly appears:
28668
28669 @smallexample
28670 @group
28671 movl %esi,%eax
28672 #APP
28673 incl %eax
28674 #NO_APP
28675 movl %eax,%edx
28676 @end group
28677 @end smallexample
28678
28679 @noindent
28680 thus saving the overhead of stack frame setup and an out-of-line call.
28681
28682 @c ---------------------------------------------------------------------------
28683 @node Other Asm Functionality
28684 @section Other @code{Asm} Functionality
28685
28686 @noindent
28687 This section describes two important parameters to the @code{Asm}
28688 procedure: @code{Clobber}, which identifies register usage;
28689 and @code{Volatile}, which inhibits unwanted optimizations.
28690
28691 @menu
28692 * The Clobber Parameter::
28693 * The Volatile Parameter::
28694 @end menu
28695
28696 @c ---------------------------------------------------------------------------
28697 @node The Clobber Parameter
28698 @subsection The @code{Clobber} Parameter
28699
28700 @noindent
28701 One of the dangers of intermixing assembly language and a compiled language
28702 such as Ada is that the compiler needs to be aware of which registers are
28703 being used by the assembly code. In some cases, such as the earlier examples,
28704 the constraint string is sufficient to indicate register usage (e.g.,
28705 @code{"a"} for
28706 the eax register). But more generally, the compiler needs an explicit
28707 identification of the registers that are used by the Inline Assembly
28708 statements.
28709
28710 Using a register that the compiler doesn't know about
28711 could be a side effect of an instruction (like @code{mull}
28712 storing its result in both eax and edx).
28713 It can also arise from explicit register usage in your
28714 assembly code; for example:
28715 @smallexample
28716 @group
28717 Asm ("movl %0, %%ebx" & LF & HT &
28718 "movl %%ebx, %1",
28719 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28720 Inputs => Unsigned_32'Asm_Input ("g", Var_In));
28721 @end group
28722 @end smallexample
28723 @noindent
28724 where the compiler (since it does not analyze the @code{Asm} template string)
28725 does not know you are using the ebx register.
28726
28727 In such cases you need to supply the @code{Clobber} parameter to @code{Asm},
28728 to identify the registers that will be used by your assembly code:
28729
28730 @smallexample
28731 @group
28732 Asm ("movl %0, %%ebx" & LF & HT &
28733 "movl %%ebx, %1",
28734 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28735 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28736 Clobber => "ebx");
28737 @end group
28738 @end smallexample
28739
28740 The Clobber parameter is a static string expression specifying the
28741 register(s) you are using. Note that register names are @emph{not} prefixed
28742 by a percent sign. Also, if more than one register is used then their names
28743 are separated by commas; e.g., @code{"eax, ebx"}
28744
28745 The @code{Clobber} parameter has several additional uses:
28746 @enumerate
28747 @item Use ``register'' name @code{cc} to indicate that flags might have changed
28748 @item Use ``register'' name @code{memory} if you changed a memory location
28749 @end enumerate
28750
28751 @c ---------------------------------------------------------------------------
28752 @node The Volatile Parameter
28753 @subsection The @code{Volatile} Parameter
28754 @cindex Volatile parameter
28755
28756 @noindent
28757 Compiler optimizations in the presence of Inline Assembler may sometimes have
28758 unwanted effects. For example, when an @code{Asm} invocation with an input
28759 variable is inside a loop, the compiler might move the loading of the input
28760 variable outside the loop, regarding it as a one-time initialization.
28761
28762 If this effect is not desired, you can disable such optimizations by setting
28763 the @code{Volatile} parameter to @code{True}; for example:
28764
28765 @smallexample @c ada
28766 @group
28767 Asm ("movl %0, %%ebx" & LF & HT &
28768 "movl %%ebx, %1",
28769 Outputs => Unsigned_32'Asm_Output ("=g", Var_Out),
28770 Inputs => Unsigned_32'Asm_Input ("g", Var_In),
28771 Clobber => "ebx",
28772 Volatile => True);
28773 @end group
28774 @end smallexample
28775
28776 By default, @code{Volatile} is set to @code{False} unless there is no
28777 @code{Outputs} parameter.
28778
28779 Although setting @code{Volatile} to @code{True} prevents unwanted
28780 optimizations, it will also disable other optimizations that might be
28781 important for efficiency. In general, you should set @code{Volatile}
28782 to @code{True} only if the compiler's optimizations have created
28783 problems.
28784 @c END OF INLINE ASSEMBLER CHAPTER
28785 @c ===============================
28786
28787 @c ***********************************
28788 @c * Compatibility and Porting Guide *
28789 @c ***********************************
28790 @node Compatibility and Porting Guide
28791 @appendix Compatibility and Porting Guide
28792
28793 @noindent
28794 This chapter describes the compatibility issues that may arise between
28795 GNAT and other Ada compilation systems (including those for Ada 83),
28796 and shows how GNAT can expedite porting
28797 applications developed in other Ada environments.
28798
28799 @menu
28800 * Compatibility with Ada 83::
28801 * Compatibility between Ada 95 and Ada 2005::
28802 * Implementation-dependent characteristics::
28803 * Compatibility with Other Ada Systems::
28804 * Representation Clauses::
28805 @ifclear vms
28806 @c Brief section is only in non-VMS version
28807 @c Full chapter is in VMS version
28808 * Compatibility with HP Ada 83::
28809 @end ifclear
28810 @ifset vms
28811 * Transitioning to 64-Bit GNAT for OpenVMS::
28812 @end ifset
28813 @end menu
28814
28815 @node Compatibility with Ada 83
28816 @section Compatibility with Ada 83
28817 @cindex Compatibility (between Ada 83 and Ada 95 / Ada 2005)
28818
28819 @noindent
28820 Ada 95 and Ada 2005 are highly upwards compatible with Ada 83. In
28821 particular, the design intention was that the difficulties associated
28822 with moving from Ada 83 to Ada 95 or Ada 2005 should be no greater than those
28823 that occur when moving from one Ada 83 system to another.
28824
28825 However, there are a number of points at which there are minor
28826 incompatibilities. The @cite{Ada 95 Annotated Reference Manual} contains
28827 full details of these issues,
28828 and should be consulted for a complete treatment.
28829 In practice the
28830 following subsections treat the most likely issues to be encountered.
28831
28832 @menu
28833 * Legal Ada 83 programs that are illegal in Ada 95::
28834 * More deterministic semantics::
28835 * Changed semantics::
28836 * Other language compatibility issues::
28837 @end menu
28838
28839 @node Legal Ada 83 programs that are illegal in Ada 95
28840 @subsection Legal Ada 83 programs that are illegal in Ada 95
28841
28842 Some legal Ada 83 programs are illegal (i.e., they will fail to compile) in
28843 Ada 95 and thus also in Ada 2005:
28844
28845 @table @emph
28846 @item Character literals
28847 Some uses of character literals are ambiguous. Since Ada 95 has introduced
28848 @code{Wide_Character} as a new predefined character type, some uses of
28849 character literals that were legal in Ada 83 are illegal in Ada 95.
28850 For example:
28851 @smallexample @c ada
28852 for Char in 'A' .. 'Z' loop @dots{} end loop;
28853 @end smallexample
28854
28855 @noindent
28856 The problem is that @code{'A'} and @code{'Z'} could be from either
28857 @code{Character} or @code{Wide_Character}. The simplest correction
28858 is to make the type explicit; e.g.:
28859 @smallexample @c ada
28860 for Char in Character range 'A' .. 'Z' loop @dots{} end loop;
28861 @end smallexample
28862
28863 @item New reserved words
28864 The identifiers @code{abstract}, @code{aliased}, @code{protected},
28865 @code{requeue}, @code{tagged}, and @code{until} are reserved in Ada 95.
28866 Existing Ada 83 code using any of these identifiers must be edited to
28867 use some alternative name.
28868
28869 @item Freezing rules
28870 The rules in Ada 95 are slightly different with regard to the point at
28871 which entities are frozen, and representation pragmas and clauses are
28872 not permitted past the freeze point. This shows up most typically in
28873 the form of an error message complaining that a representation item
28874 appears too late, and the appropriate corrective action is to move
28875 the item nearer to the declaration of the entity to which it refers.
28876
28877 A particular case is that representation pragmas
28878 @ifset vms
28879 (including the
28880 extended HP Ada 83 compatibility pragmas such as @code{Export_Procedure})
28881 @end ifset
28882 cannot be applied to a subprogram body. If necessary, a separate subprogram
28883 declaration must be introduced to which the pragma can be applied.
28884
28885 @item Optional bodies for library packages
28886 In Ada 83, a package that did not require a package body was nevertheless
28887 allowed to have one. This lead to certain surprises in compiling large
28888 systems (situations in which the body could be unexpectedly ignored by the
28889 binder). In Ada 95, if a package does not require a body then it is not
28890 permitted to have a body. To fix this problem, simply remove a redundant
28891 body if it is empty, or, if it is non-empty, introduce a dummy declaration
28892 into the spec that makes the body required. One approach is to add a private
28893 part to the package declaration (if necessary), and define a parameterless
28894 procedure called @code{Requires_Body}, which must then be given a dummy
28895 procedure body in the package body, which then becomes required.
28896 Another approach (assuming that this does not introduce elaboration
28897 circularities) is to add an @code{Elaborate_Body} pragma to the package spec,
28898 since one effect of this pragma is to require the presence of a package body.
28899
28900 @item @code{Numeric_Error} is now the same as @code{Constraint_Error}
28901 In Ada 95, the exception @code{Numeric_Error} is a renaming of
28902 @code{Constraint_Error}.
28903 This means that it is illegal to have separate exception handlers for
28904 the two exceptions. The fix is simply to remove the handler for the
28905 @code{Numeric_Error} case (since even in Ada 83, a compiler was free to raise
28906 @code{Constraint_Error} in place of @code{Numeric_Error} in all cases).
28907
28908 @item Indefinite subtypes in generics
28909 In Ada 83, it was permissible to pass an indefinite type (e.g.@: @code{String})
28910 as the actual for a generic formal private type, but then the instantiation
28911 would be illegal if there were any instances of declarations of variables
28912 of this type in the generic body. In Ada 95, to avoid this clear violation
28913 of the methodological principle known as the ``contract model'',
28914 the generic declaration explicitly indicates whether
28915 or not such instantiations are permitted. If a generic formal parameter
28916 has explicit unknown discriminants, indicated by using @code{(<>)} after the
28917 subtype name, then it can be instantiated with indefinite types, but no
28918 stand-alone variables can be declared of this type. Any attempt to declare
28919 such a variable will result in an illegality at the time the generic is
28920 declared. If the @code{(<>)} notation is not used, then it is illegal
28921 to instantiate the generic with an indefinite type.
28922 This is the potential incompatibility issue when porting Ada 83 code to Ada 95.
28923 It will show up as a compile time error, and
28924 the fix is usually simply to add the @code{(<>)} to the generic declaration.
28925 @end table
28926
28927 @node More deterministic semantics
28928 @subsection More deterministic semantics
28929
28930 @table @emph
28931 @item Conversions
28932 Conversions from real types to integer types round away from 0. In Ada 83
28933 the conversion Integer(2.5) could deliver either 2 or 3 as its value. This
28934 implementation freedom was intended to support unbiased rounding in
28935 statistical applications, but in practice it interfered with portability.
28936 In Ada 95 the conversion semantics are unambiguous, and rounding away from 0
28937 is required. Numeric code may be affected by this change in semantics.
28938 Note, though, that this issue is no worse than already existed in Ada 83
28939 when porting code from one vendor to another.
28940
28941 @item Tasking
28942 The Real-Time Annex introduces a set of policies that define the behavior of
28943 features that were implementation dependent in Ada 83, such as the order in
28944 which open select branches are executed.
28945 @end table
28946
28947 @node Changed semantics
28948 @subsection Changed semantics
28949
28950 @noindent
28951 The worst kind of incompatibility is one where a program that is legal in
28952 Ada 83 is also legal in Ada 95 but can have an effect in Ada 95 that was not
28953 possible in Ada 83. Fortunately this is extremely rare, but the one
28954 situation that you should be alert to is the change in the predefined type
28955 @code{Character} from 7-bit ASCII to 8-bit Latin-1.
28956
28957 @table @emph
28958 @item Range of type @code{Character}
28959 The range of @code{Standard.Character} is now the full 256 characters
28960 of Latin-1, whereas in most Ada 83 implementations it was restricted
28961 to 128 characters. Although some of the effects of
28962 this change will be manifest in compile-time rejection of legal
28963 Ada 83 programs it is possible for a working Ada 83 program to have
28964 a different effect in Ada 95, one that was not permitted in Ada 83.
28965 As an example, the expression
28966 @code{Character'Pos(Character'Last)} returned @code{127} in Ada 83 and now
28967 delivers @code{255} as its value.
28968 In general, you should look at the logic of any
28969 character-processing Ada 83 program and see whether it needs to be adapted
28970 to work correctly with Latin-1. Note that the predefined Ada 95 API has a
28971 character handling package that may be relevant if code needs to be adapted
28972 to account for the additional Latin-1 elements.
28973 The desirable fix is to
28974 modify the program to accommodate the full character set, but in some cases
28975 it may be convenient to define a subtype or derived type of Character that
28976 covers only the restricted range.
28977 @cindex Latin-1
28978 @end table
28979
28980 @node Other language compatibility issues
28981 @subsection Other language compatibility issues
28982
28983 @table @emph
28984 @item @option{-gnat83} switch
28985 All implementations of GNAT provide a switch that causes GNAT to operate
28986 in Ada 83 mode. In this mode, some but not all compatibility problems
28987 of the type described above are handled automatically. For example, the
28988 new reserved words introduced in Ada 95 and Ada 2005 are treated simply
28989 as identifiers as in Ada 83.
28990 However,
28991 in practice, it is usually advisable to make the necessary modifications
28992 to the program to remove the need for using this switch.
28993 See @ref{Compiling Different Versions of Ada}.
28994
28995 @item Support for removed Ada 83 pragmas and attributes
28996 A number of pragmas and attributes from Ada 83 were removed from Ada 95,
28997 generally because they were replaced by other mechanisms. Ada 95 and Ada 2005
28998 compilers are allowed, but not required, to implement these missing
28999 elements. In contrast with some other compilers, GNAT implements all
29000 such pragmas and attributes, eliminating this compatibility concern. These
29001 include @code{pragma Interface} and the floating point type attributes
29002 (@code{Emax}, @code{Mantissa}, etc.), among other items.
29003 @end table
29004
29005
29006 @node Compatibility between Ada 95 and Ada 2005
29007 @section Compatibility between Ada 95 and Ada 2005
29008 @cindex Compatibility between Ada 95 and Ada 2005
29009
29010 @noindent
29011 Although Ada 2005 was designed to be upwards compatible with Ada 95, there are
29012 a number of incompatibilities. Several are enumerated below;
29013 for a complete description please see the
29014 Annotated Ada 2005 Reference Manual, or section 9.1.1 in
29015 @cite{Rationale for Ada 2005}.
29016
29017 @table @emph
29018 @item New reserved words.
29019 The words @code{interface}, @code{overriding} and @code{synchronized} are
29020 reserved in Ada 2005.
29021 A pre-Ada 2005 program that uses any of these as an identifier will be
29022 illegal.
29023
29024 @item New declarations in predefined packages.
29025 A number of packages in the predefined environment contain new declarations:
29026 @code{Ada.Exceptions}, @code{Ada.Real_Time}, @code{Ada.Strings},
29027 @code{Ada.Strings.Fixed}, @code{Ada.Strings.Bounded},
29028 @code{Ada.Strings.Unbounded}, @code{Ada.Strings.Wide_Fixed},
29029 @code{Ada.Strings.Wide_Bounded}, @code{Ada.Strings.Wide_Unbounded},
29030 @code{Ada.Tags}, @code{Ada.Text_IO}, and @code{Interfaces.C}.
29031 If an Ada 95 program does a @code{with} and @code{use} of any of these
29032 packages, the new declarations may cause name clashes.
29033
29034 @item Access parameters.
29035 A nondispatching subprogram with an access parameter cannot be renamed
29036 as a dispatching operation. This was permitted in Ada 95.
29037
29038 @item Access types, discriminants, and constraints.
29039 Rule changes in this area have led to some incompatibilities; for example,
29040 constrained subtypes of some access types are not permitted in Ada 2005.
29041
29042 @item Aggregates for limited types.
29043 The allowance of aggregates for limited types in Ada 2005 raises the
29044 possibility of ambiguities in legal Ada 95 programs, since additional types
29045 now need to be considered in expression resolution.
29046
29047 @item Fixed-point multiplication and division.
29048 Certain expressions involving ``*'' or ``/'' for a fixed-point type, which
29049 were legal in Ada 95 and invoked the predefined versions of these operations,
29050 are now ambiguous.
29051 The ambiguity may be resolved either by applying a type conversion to the
29052 expression, or by explicitly invoking the operation from package
29053 @code{Standard}.
29054
29055 @item Return-by-reference types.
29056 The Ada 95 return-by-reference mechanism has been removed. Instead, the user
29057 can declare a function returning a value from an anonymous access type.
29058 @end table
29059
29060
29061 @node Implementation-dependent characteristics
29062 @section Implementation-dependent characteristics
29063 @noindent
29064 Although the Ada language defines the semantics of each construct as
29065 precisely as practical, in some situations (for example for reasons of
29066 efficiency, or where the effect is heavily dependent on the host or target
29067 platform) the implementation is allowed some freedom. In porting Ada 83
29068 code to GNAT, you need to be aware of whether / how the existing code
29069 exercised such implementation dependencies. Such characteristics fall into
29070 several categories, and GNAT offers specific support in assisting the
29071 transition from certain Ada 83 compilers.
29072
29073 @menu
29074 * Implementation-defined pragmas::
29075 * Implementation-defined attributes::
29076 * Libraries::
29077 * Elaboration order::
29078 * Target-specific aspects::
29079 @end menu
29080
29081 @node Implementation-defined pragmas
29082 @subsection Implementation-defined pragmas
29083
29084 @noindent
29085 Ada compilers are allowed to supplement the language-defined pragmas, and
29086 these are a potential source of non-portability. All GNAT-defined pragmas
29087 are described in @ref{Implementation Defined Pragmas,,, gnat_rm, GNAT
29088 Reference Manual}, and these include several that are specifically
29089 intended to correspond to other vendors' Ada 83 pragmas.
29090 For migrating from VADS, the pragma @code{Use_VADS_Size} may be useful.
29091 For compatibility with HP Ada 83, GNAT supplies the pragmas
29092 @code{Extend_System}, @code{Ident}, @code{Inline_Generic},
29093 @code{Interface_Name}, @code{Passive}, @code{Suppress_All},
29094 and @code{Volatile}.
29095 Other relevant pragmas include @code{External} and @code{Link_With}.
29096 Some vendor-specific
29097 Ada 83 pragmas (@code{Share_Generic}, @code{Subtitle}, and @code{Title}) are
29098 recognized, thus
29099 avoiding compiler rejection of units that contain such pragmas; they are not
29100 relevant in a GNAT context and hence are not otherwise implemented.
29101
29102 @node Implementation-defined attributes
29103 @subsection Implementation-defined attributes
29104
29105 Analogous to pragmas, the set of attributes may be extended by an
29106 implementation. All GNAT-defined attributes are described in
29107 @ref{Implementation Defined Attributes,,, gnat_rm, GNAT Reference
29108 Manual}, and these include several that are specifically intended
29109 to correspond to other vendors' Ada 83 attributes. For migrating from VADS,
29110 the attribute @code{VADS_Size} may be useful. For compatibility with HP
29111 Ada 83, GNAT supplies the attributes @code{Bit}, @code{Machine_Size} and
29112 @code{Type_Class}.
29113
29114 @node Libraries
29115 @subsection Libraries
29116 @noindent
29117 Vendors may supply libraries to supplement the standard Ada API. If Ada 83
29118 code uses vendor-specific libraries then there are several ways to manage
29119 this in Ada 95 or Ada 2005:
29120 @enumerate
29121 @item
29122 If the source code for the libraries (specs and bodies) are
29123 available, then the libraries can be migrated in the same way as the
29124 application.
29125 @item
29126 If the source code for the specs but not the bodies are
29127 available, then you can reimplement the bodies.
29128 @item
29129 Some features introduced by Ada 95 obviate the need for library support. For
29130 example most Ada 83 vendors supplied a package for unsigned integers. The
29131 Ada 95 modular type feature is the preferred way to handle this need, so
29132 instead of migrating or reimplementing the unsigned integer package it may
29133 be preferable to retrofit the application using modular types.
29134 @end enumerate
29135
29136 @node Elaboration order
29137 @subsection Elaboration order
29138 @noindent
29139 The implementation can choose any elaboration order consistent with the unit
29140 dependency relationship. This freedom means that some orders can result in
29141 Program_Error being raised due to an ``Access Before Elaboration'': an attempt
29142 to invoke a subprogram its body has been elaborated, or to instantiate a
29143 generic before the generic body has been elaborated. By default GNAT
29144 attempts to choose a safe order (one that will not encounter access before
29145 elaboration problems) by implicitly inserting @code{Elaborate} or
29146 @code{Elaborate_All} pragmas where
29147 needed. However, this can lead to the creation of elaboration circularities
29148 and a resulting rejection of the program by gnatbind. This issue is
29149 thoroughly described in @ref{Elaboration Order Handling in GNAT}.
29150 In brief, there are several
29151 ways to deal with this situation:
29152
29153 @itemize @bullet
29154 @item
29155 Modify the program to eliminate the circularities, e.g.@: by moving
29156 elaboration-time code into explicitly-invoked procedures
29157 @item
29158 Constrain the elaboration order by including explicit @code{Elaborate_Body} or
29159 @code{Elaborate} pragmas, and then inhibit the generation of implicit
29160 @code{Elaborate_All}
29161 pragmas either globally (as an effect of the @option{-gnatE} switch) or locally
29162 (by selectively suppressing elaboration checks via pragma
29163 @code{Suppress(Elaboration_Check)} when it is safe to do so).
29164 @end itemize
29165
29166 @node Target-specific aspects
29167 @subsection Target-specific aspects
29168 @noindent
29169 Low-level applications need to deal with machine addresses, data
29170 representations, interfacing with assembler code, and similar issues. If
29171 such an Ada 83 application is being ported to different target hardware (for
29172 example where the byte endianness has changed) then you will need to
29173 carefully examine the program logic; the porting effort will heavily depend
29174 on the robustness of the original design. Moreover, Ada 95 (and thus
29175 Ada 2005) are sometimes
29176 incompatible with typical Ada 83 compiler practices regarding implicit
29177 packing, the meaning of the Size attribute, and the size of access values.
29178 GNAT's approach to these issues is described in @ref{Representation Clauses}.
29179
29180 @node Compatibility with Other Ada Systems
29181 @section Compatibility with Other Ada Systems
29182
29183 @noindent
29184 If programs avoid the use of implementation dependent and
29185 implementation defined features, as documented in the @cite{Ada
29186 Reference Manual}, there should be a high degree of portability between
29187 GNAT and other Ada systems. The following are specific items which
29188 have proved troublesome in moving Ada 95 programs from GNAT to other Ada 95
29189 compilers, but do not affect porting code to GNAT@.
29190 (As of @value{NOW}, GNAT is the only compiler available for Ada 2005;
29191 the following issues may or may not arise for Ada 2005 programs
29192 when other compilers appear.)
29193
29194 @table @emph
29195 @item Ada 83 Pragmas and Attributes
29196 Ada 95 compilers are allowed, but not required, to implement the missing
29197 Ada 83 pragmas and attributes that are no longer defined in Ada 95.
29198 GNAT implements all such pragmas and attributes, eliminating this as
29199 a compatibility concern, but some other Ada 95 compilers reject these
29200 pragmas and attributes.
29201
29202 @item Specialized Needs Annexes
29203 GNAT implements the full set of special needs annexes. At the
29204 current time, it is the only Ada 95 compiler to do so. This means that
29205 programs making use of these features may not be portable to other Ada
29206 95 compilation systems.
29207
29208 @item Representation Clauses
29209 Some other Ada 95 compilers implement only the minimal set of
29210 representation clauses required by the Ada 95 reference manual. GNAT goes
29211 far beyond this minimal set, as described in the next section.
29212 @end table
29213
29214 @node Representation Clauses
29215 @section Representation Clauses
29216
29217 @noindent
29218 The Ada 83 reference manual was quite vague in describing both the minimal
29219 required implementation of representation clauses, and also their precise
29220 effects. Ada 95 (and thus also Ada 2005) are much more explicit, but the
29221 minimal set of capabilities required is still quite limited.
29222
29223 GNAT implements the full required set of capabilities in
29224 Ada 95 and Ada 2005, but also goes much further, and in particular
29225 an effort has been made to be compatible with existing Ada 83 usage to the
29226 greatest extent possible.
29227
29228 A few cases exist in which Ada 83 compiler behavior is incompatible with
29229 the requirements in Ada 95 (and thus also Ada 2005). These are instances of
29230 intentional or accidental dependence on specific implementation dependent
29231 characteristics of these Ada 83 compilers. The following is a list of
29232 the cases most likely to arise in existing Ada 83 code.
29233
29234 @table @emph
29235 @item Implicit Packing
29236 Some Ada 83 compilers allowed a Size specification to cause implicit
29237 packing of an array or record. This could cause expensive implicit
29238 conversions for change of representation in the presence of derived
29239 types, and the Ada design intends to avoid this possibility.
29240 Subsequent AI's were issued to make it clear that such implicit
29241 change of representation in response to a Size clause is inadvisable,
29242 and this recommendation is represented explicitly in the Ada 95 (and Ada 2005)
29243 Reference Manuals as implementation advice that is followed by GNAT@.
29244 The problem will show up as an error
29245 message rejecting the size clause. The fix is simply to provide
29246 the explicit pragma @code{Pack}, or for more fine tuned control, provide
29247 a Component_Size clause.
29248
29249 @item Meaning of Size Attribute
29250 The Size attribute in Ada 95 (and Ada 2005) for discrete types is defined as
29251 the minimal number of bits required to hold values of the type. For example,
29252 on a 32-bit machine, the size of @code{Natural} will typically be 31 and not
29253 32 (since no sign bit is required). Some Ada 83 compilers gave 31, and
29254 some 32 in this situation. This problem will usually show up as a compile
29255 time error, but not always. It is a good idea to check all uses of the
29256 'Size attribute when porting Ada 83 code. The GNAT specific attribute
29257 Object_Size can provide a useful way of duplicating the behavior of
29258 some Ada 83 compiler systems.
29259
29260 @item Size of Access Types
29261 A common assumption in Ada 83 code is that an access type is in fact a pointer,
29262 and that therefore it will be the same size as a System.Address value. This
29263 assumption is true for GNAT in most cases with one exception. For the case of
29264 a pointer to an unconstrained array type (where the bounds may vary from one
29265 value of the access type to another), the default is to use a ``fat pointer'',
29266 which is represented as two separate pointers, one to the bounds, and one to
29267 the array. This representation has a number of advantages, including improved
29268 efficiency. However, it may cause some difficulties in porting existing Ada 83
29269 code which makes the assumption that, for example, pointers fit in 32 bits on
29270 a machine with 32-bit addressing.
29271
29272 To get around this problem, GNAT also permits the use of ``thin pointers'' for
29273 access types in this case (where the designated type is an unconstrained array
29274 type). These thin pointers are indeed the same size as a System.Address value.
29275 To specify a thin pointer, use a size clause for the type, for example:
29276
29277 @smallexample @c ada
29278 type X is access all String;
29279 for X'Size use Standard'Address_Size;
29280 @end smallexample
29281
29282 @noindent
29283 which will cause the type X to be represented using a single pointer.
29284 When using this representation, the bounds are right behind the array.
29285 This representation is slightly less efficient, and does not allow quite
29286 such flexibility in the use of foreign pointers or in using the
29287 Unrestricted_Access attribute to create pointers to non-aliased objects.
29288 But for any standard portable use of the access type it will work in
29289 a functionally correct manner and allow porting of existing code.
29290 Note that another way of forcing a thin pointer representation
29291 is to use a component size clause for the element size in an array,
29292 or a record representation clause for an access field in a record.
29293
29294 See the documentation of Unrestricted_Access in the GNAT RM for a
29295 full discussion of possible problems using this attribute in conjunction
29296 with thin pointers.
29297 @end table
29298
29299 @ifclear vms
29300 @c This brief section is only in the non-VMS version
29301 @c The complete chapter on HP Ada is in the VMS version
29302 @node Compatibility with HP Ada 83
29303 @section Compatibility with HP Ada 83
29304
29305 @noindent
29306 The VMS version of GNAT fully implements all the pragmas and attributes
29307 provided by HP Ada 83, as well as providing the standard HP Ada 83
29308 libraries, including Starlet. In addition, data layouts and parameter
29309 passing conventions are highly compatible. This means that porting
29310 existing HP Ada 83 code to GNAT in VMS systems should be easier than
29311 most other porting efforts. The following are some of the most
29312 significant differences between GNAT and HP Ada 83.
29313
29314 @table @emph
29315 @item Default floating-point representation
29316 In GNAT, the default floating-point format is IEEE, whereas in HP Ada 83,
29317 it is VMS format. GNAT does implement the necessary pragmas
29318 (Long_Float, Float_Representation) for changing this default.
29319
29320 @item System
29321 The package System in GNAT exactly corresponds to the definition in the
29322 Ada 95 reference manual, which means that it excludes many of the
29323 HP Ada 83 extensions. However, a separate package Aux_DEC is provided
29324 that contains the additional definitions, and a special pragma,
29325 Extend_System allows this package to be treated transparently as an
29326 extension of package System.
29327
29328 @item To_Address
29329 The definitions provided by Aux_DEC are exactly compatible with those
29330 in the HP Ada 83 version of System, with one exception.
29331 HP Ada provides the following declarations:
29332
29333 @smallexample @c ada
29334 TO_ADDRESS (INTEGER)
29335 TO_ADDRESS (UNSIGNED_LONGWORD)
29336 TO_ADDRESS (@i{universal_integer})
29337 @end smallexample
29338
29339 @noindent
29340 The version of TO_ADDRESS taking a @i{universal integer} argument is in fact
29341 an extension to Ada 83 not strictly compatible with the reference manual.
29342 In GNAT, we are constrained to be exactly compatible with the standard,
29343 and this means we cannot provide this capability. In HP Ada 83, the
29344 point of this definition is to deal with a call like:
29345
29346 @smallexample @c ada
29347 TO_ADDRESS (16#12777#);
29348 @end smallexample
29349
29350 @noindent
29351 Normally, according to the Ada 83 standard, one would expect this to be
29352 ambiguous, since it matches both the INTEGER and UNSIGNED_LONGWORD forms
29353 of TO_ADDRESS@. However, in HP Ada 83, there is no ambiguity, since the
29354 definition using @i{universal_integer} takes precedence.
29355
29356 In GNAT, since the version with @i{universal_integer} cannot be supplied, it
29357 is not possible to be 100% compatible. Since there are many programs using
29358 numeric constants for the argument to TO_ADDRESS, the decision in GNAT was
29359 to change the name of the function in the UNSIGNED_LONGWORD case, so the
29360 declarations provided in the GNAT version of AUX_Dec are:
29361
29362 @smallexample @c ada
29363 function To_Address (X : Integer) return Address;
29364 pragma Pure_Function (To_Address);
29365
29366 function To_Address_Long (X : Unsigned_Longword)
29367 return Address;
29368 pragma Pure_Function (To_Address_Long);
29369 @end smallexample
29370
29371 @noindent
29372 This means that programs using TO_ADDRESS for UNSIGNED_LONGWORD must
29373 change the name to TO_ADDRESS_LONG@.
29374
29375 @item Task_Id values
29376 The Task_Id values assigned will be different in the two systems, and GNAT
29377 does not provide a specified value for the Task_Id of the environment task,
29378 which in GNAT is treated like any other declared task.
29379 @end table
29380
29381 @noindent
29382 For full details on these and other less significant compatibility issues,
29383 see appendix E of the HP publication entitled @cite{HP Ada, Technical
29384 Overview and Comparison on HP Platforms}.
29385
29386 For GNAT running on other than VMS systems, all the HP Ada 83 pragmas and
29387 attributes are recognized, although only a subset of them can sensibly
29388 be implemented. The description of pragmas in @ref{Implementation
29389 Defined Pragmas,,, gnat_rm, GNAT Reference Manual}
29390 indicates whether or not they are applicable to non-VMS systems.
29391 @end ifclear
29392
29393 @ifset vms
29394 @node Transitioning to 64-Bit GNAT for OpenVMS
29395 @section Transitioning to 64-Bit @value{EDITION} for OpenVMS
29396
29397 @noindent
29398 This section is meant to assist users of pre-2006 @value{EDITION}
29399 for Alpha OpenVMS who are transitioning to 64-bit @value{EDITION},
29400 the version of the GNAT technology supplied in 2006 and later for
29401 OpenVMS on both Alpha and I64.
29402
29403 @menu
29404 * Introduction to transitioning::
29405 * Migration of 32 bit code::
29406 * Taking advantage of 64 bit addressing::
29407 * Technical details::
29408 @end menu
29409
29410 @node Introduction to transitioning
29411 @subsection Introduction
29412
29413 @noindent
29414 64-bit @value{EDITION} for Open VMS has been designed to meet
29415 three main goals:
29416
29417 @enumerate
29418 @item
29419 Providing a full conforming implementation of Ada 95 and Ada 2005
29420
29421 @item
29422 Allowing maximum backward compatibility, thus easing migration of existing
29423 Ada source code
29424
29425 @item
29426 Supplying a path for exploiting the full 64-bit address range
29427 @end enumerate
29428
29429 @noindent
29430 Ada's strong typing semantics has made it
29431 impractical to have different 32-bit and 64-bit modes. As soon as
29432 one object could possibly be outside the 32-bit address space, this
29433 would make it necessary for the @code{System.Address} type to be 64 bits.
29434 In particular, this would cause inconsistencies if 32-bit code is
29435 called from 64-bit code that raises an exception.
29436
29437 This issue has been resolved by always using 64-bit addressing
29438 at the system level, but allowing for automatic conversions between
29439 32-bit and 64-bit addresses where required. Thus users who
29440 do not currently require 64-bit addressing capabilities, can
29441 recompile their code with only minimal changes (and indeed
29442 if the code is written in portable Ada, with no assumptions about
29443 the size of the @code{Address} type, then no changes at all are necessary).
29444 At the same time,
29445 this approach provides a simple, gradual upgrade path to future
29446 use of larger memories than available for 32-bit systems.
29447 Also, newly written applications or libraries will by default
29448 be fully compatible with future systems exploiting 64-bit
29449 addressing capabilities.
29450
29451 @ref{Migration of 32 bit code}, will focus on porting applications
29452 that do not require more than 2 GB of
29453 addressable memory. This code will be referred to as
29454 @emph{32-bit code}.
29455 For applications intending to exploit the full 64-bit address space,
29456 @ref{Taking advantage of 64 bit addressing},
29457 will consider further changes that may be required.
29458 Such code will be referred to below as @emph{64-bit code}.
29459
29460 @node Migration of 32 bit code
29461 @subsection Migration of 32-bit code
29462
29463 @menu
29464 * Address types::
29465 * Access types and 32/64-bit allocation::
29466 * Unchecked conversions::
29467 * Predefined constants::
29468 * Interfacing with C::
29469 * 32/64-bit descriptors::
29470 * Experience with source compatibility::
29471 @end menu
29472
29473 @node Address types
29474 @subsubsection Address types
29475
29476 @noindent
29477 To solve the problem of mixing 64-bit and 32-bit addressing,
29478 while maintaining maximum backward compatibility, the following
29479 approach has been taken:
29480
29481 @itemize @bullet
29482 @item
29483 @code{System.Address} always has a size of 64 bits
29484 @cindex @code{System.Address} size
29485 @cindex @code{Address} size
29486
29487 @item
29488 @code{System.Short_Address} is a 32-bit subtype of @code{System.Address}
29489 @cindex @code{System.Short_Address} size
29490 @cindex @code{Short_Address} size
29491 @end itemize
29492
29493 @noindent
29494 Since @code{System.Short_Address} is a subtype of @code{System.Address},
29495 a @code{Short_Address}
29496 may be used where an @code{Address} is required, and vice versa, without
29497 needing explicit type conversions.
29498 By virtue of the Open VMS parameter passing conventions,
29499 even imported
29500 and exported subprograms that have 32-bit address parameters are
29501 compatible with those that have 64-bit address parameters.
29502 (See @ref{Making code 64 bit clean} for details.)
29503
29504 The areas that may need attention are those where record types have
29505 been defined that contain components of the type @code{System.Address}, and
29506 where objects of this type are passed to code expecting a record layout with
29507 32-bit addresses.
29508
29509 Different compilers on different platforms cannot be
29510 expected to represent the same type in the same way,
29511 since alignment constraints
29512 and other system-dependent properties affect the compiler's decision.
29513 For that reason, Ada code
29514 generally uses representation clauses to specify the expected
29515 layout where required.
29516
29517 If such a representation clause uses 32 bits for a component having
29518 the type @code{System.Address}, 64-bit @value{EDITION} for OpenVMS
29519 will detect that error and produce a specific diagnostic message.
29520 The developer should then determine whether the representation
29521 should be 64 bits or not and make either of two changes:
29522 change the size to 64 bits and leave the type as @code{System.Address}, or
29523 leave the size as 32 bits and change the type to @code{System.Short_Address}.
29524 Since @code{Short_Address} is a subtype of @code{Address}, no changes are
29525 required in any code setting or accessing the field; the compiler will
29526 automatically perform any needed conversions between address
29527 formats.
29528
29529 @node Access types and 32/64-bit allocation
29530 @subsubsection Access types and 32/64-bit allocation
29531 @cindex 32-bit allocation
29532 @cindex 64-bit allocation
29533
29534 @noindent
29535 By default, objects designated by access values are always allocated in
29536 the 64-bit address space, and access values themselves are represented
29537 in 64 bits. If these defaults are not appropriate, and 32-bit allocation
29538 is required (for example if the address of an allocated object is assigned
29539 to a @code{Short_Address} variable), then several alternatives are available:
29540
29541 @itemize @bullet
29542 @item
29543 A pool-specific access type (ie, an @w{Ada 83} access type, whose
29544 definition is @code{access T} versus @code{access all T} or
29545 @code{access constant T}), may be declared with a @code{'Size} representation
29546 clause that establishes the size as 32 bits.
29547 In such circumstances allocations for that type will
29548 be from the 32-bit heap. Such a clause is not permitted
29549 for a general access type (declared with @code{access all} or
29550 @code{access constant}) as values of such types must be able to refer
29551 to any object of the designated type, including objects residing outside
29552 the 32-bit address range. Existing @w{Ada 83} code will not contain such
29553 type definitions, however, since general access types were introduced
29554 in @w{Ada 95}.
29555
29556 @item
29557 Switches for @command{GNAT BIND} control whether the internal GNAT
29558 allocation routine @code{__gnat_malloc} uses 64-bit or 32-bit allocations.
29559 @cindex @code{__gnat_malloc}
29560 The switches are respectively @option{-H64} (the default) and
29561 @option{-H32}.
29562 @cindex @option{-H32} (@command{gnatbind})
29563 @cindex @option{-H64} (@command{gnatbind})
29564
29565 @item
29566 The environment variable (logical name) @code{GNAT$NO_MALLOC_64}
29567 @cindex @code{GNAT$NO_MALLOC_64} environment variable
29568 may be used to force @code{__gnat_malloc} to use 32-bit allocation.
29569 If this variable is left
29570 undefined, or defined as @code{"DISABLE"}, @code{"FALSE"}, or @code{"0"},
29571 then the default (64-bit) allocation is used.
29572 If defined as @code{"ENABLE"}, @code{"TRUE"}, or @code{"1"},
29573 then 32-bit allocation is used. The gnatbind qualifiers described above
29574 override this logical name.
29575
29576 @item
29577 A ^gcc switch^gcc switch^ for OpenVMS, @option{-mno-malloc64}, operates
29578 @cindex @option{-mno-malloc64} (^gcc^gcc^)
29579 at a low level to convert explicit calls to @code{malloc} and related
29580 functions from the C run-time library so that they perform allocations
29581 in the 32-bit heap.
29582 Since all internal allocations from GNAT use @code{__gnat_malloc},
29583 this switch is not required unless the program makes explicit calls on
29584 @code{malloc} (or related functions) from interfaced C code.
29585 @end itemize
29586
29587
29588 @node Unchecked conversions
29589 @subsubsection Unchecked conversions
29590
29591 @noindent
29592 In the case of an @code{Unchecked_Conversion} where the source type is a
29593 64-bit access type or the type @code{System.Address}, and the target
29594 type is a 32-bit type, the compiler will generate a warning.
29595 Even though the generated code will still perform the required
29596 conversions, it is highly recommended in these cases to use
29597 respectively a 32-bit access type or @code{System.Short_Address}
29598 as the source type.
29599
29600 @node Predefined constants
29601 @subsubsection Predefined constants
29602
29603 @noindent
29604 The following table shows the correspondence between pre-2006 versions of
29605 @value{EDITION} on Alpha OpenVMS (``Old'') and 64-bit @value{EDITION}
29606 (``New''):
29607
29608 @multitable {@code{System.Short_Memory_Size}} {2**32} {2**64}
29609 @item @b{Constant} @tab @b{Old} @tab @b{New}
29610 @item @code{System.Word_Size} @tab 32 @tab 64
29611 @item @code{System.Memory_Size} @tab 2**32 @tab 2**64
29612 @item @code{System.Short_Memory_Size} @tab 2**32 @tab 2**32
29613 @item @code{System.Address_Size} @tab 32 @tab 64
29614 @end multitable
29615
29616 @noindent
29617 If you need to refer to the specific
29618 memory size of a 32-bit implementation, instead of the
29619 actual memory size, use @code{System.Short_Memory_Size}
29620 rather than @code{System.Memory_Size}.
29621 Similarly, references to @code{System.Address_Size} may need
29622 to be replaced by @code{System.Short_Address'Size}.
29623 The program @command{gnatfind} may be useful for locating
29624 references to the above constants, so that you can verify that they
29625 are still correct.
29626
29627 @node Interfacing with C
29628 @subsubsection Interfacing with C
29629
29630 @noindent
29631 In order to minimize the impact of the transition to 64-bit addresses on
29632 legacy programs, some fundamental types in the @code{Interfaces.C}
29633 package hierarchy continue to be represented in 32 bits.
29634 These types are: @code{ptrdiff_t}, @code{size_t}, and @code{chars_ptr}.
29635 This eases integration with the default HP C layout choices, for example
29636 as found in the system routines in @code{DECC$SHR.EXE}.
29637 Because of this implementation choice, the type fully compatible with
29638 @code{chars_ptr} is now @code{Short_Address} and not @code{Address}.
29639 Depending on the context the compiler will issue a
29640 warning or an error when type @code{Address} is used, alerting the user to a
29641 potential problem. Otherwise 32-bit programs that use
29642 @code{Interfaces.C} should normally not require code modifications
29643
29644 The other issue arising with C interfacing concerns pragma @code{Convention}.
29645 For VMS 64-bit systems, there is an issue of the appropriate default size
29646 of C convention pointers in the absence of an explicit size clause. The HP
29647 C compiler can choose either 32 or 64 bits depending on compiler options.
29648 GNAT chooses 32-bits rather than 64-bits in the default case where no size
29649 clause is given. This proves a better choice for porting 32-bit legacy
29650 applications. In order to have a 64-bit representation, it is necessary to
29651 specify a size representation clause. For example:
29652
29653 @smallexample @c ada
29654 type int_star is access Interfaces.C.int;
29655 pragma Convention(C, int_star);
29656 for int_star'Size use 64; -- Necessary to get 64 and not 32 bits
29657 @end smallexample
29658
29659 @node 32/64-bit descriptors
29660 @subsubsection 32/64-bit descriptors
29661
29662 @noindent
29663 By default, GNAT uses a 64-bit descriptor mechanism. For an imported
29664 subprogram (i.e., a subprogram identified by pragma @code{Import_Function},
29665 @code{Import_Procedure}, or @code{Import_Valued_Procedure}) that specifies
29666 @code{Short_Descriptor} as its mechanism, a 32-bit descriptor is used.
29667 @cindex @code{Short_Descriptor} mechanism for imported subprograms
29668
29669 If the configuration pragma @code{Short_Descriptors} is supplied, then
29670 all descriptors will be 32 bits.
29671 @cindex pragma @code{Short_Descriptors}
29672
29673 @node Experience with source compatibility
29674 @subsubsection Experience with source compatibility
29675
29676 @noindent
29677 The Security Server and STARLET on I64 provide an interesting ``test case''
29678 for source compatibility issues, since it is in such system code
29679 where assumptions about @code{Address} size might be expected to occur.
29680 Indeed, there were a small number of occasions in the Security Server
29681 file @file{jibdef.ads}
29682 where a representation clause for a record type specified
29683 32 bits for a component of type @code{Address}.
29684 All of these errors were detected by the compiler.
29685 The repair was obvious and immediate; to simply replace @code{Address} by
29686 @code{Short_Address}.
29687
29688 In the case of STARLET, there were several record types that should
29689 have had representation clauses but did not. In these record types
29690 there was an implicit assumption that an @code{Address} value occupied
29691 32 bits.
29692 These compiled without error, but their usage resulted in run-time error
29693 returns from STARLET system calls.
29694 Future GNAT technology enhancements may include a tool that detects and flags
29695 these sorts of potential source code porting problems.
29696
29697 @c ****************************************
29698 @node Taking advantage of 64 bit addressing
29699 @subsection Taking advantage of 64-bit addressing
29700
29701 @menu
29702 * Making code 64 bit clean::
29703 * Allocating memory from the 64 bit storage pool::
29704 * Restrictions on use of 64 bit objects::
29705 * STARLET and other predefined libraries::
29706 @end menu
29707
29708 @node Making code 64 bit clean
29709 @subsubsection Making code 64-bit clean
29710
29711 @noindent
29712 In order to prevent problems that may occur when (parts of) a
29713 system start using memory outside the 32-bit address range,
29714 we recommend some additional guidelines:
29715
29716 @itemize @bullet
29717 @item
29718 For imported subprograms that take parameters of the
29719 type @code{System.Address}, ensure that these subprograms can
29720 indeed handle 64-bit addresses. If not, or when in doubt,
29721 change the subprogram declaration to specify
29722 @code{System.Short_Address} instead.
29723
29724 @item
29725 Resolve all warnings related to size mismatches in
29726 unchecked conversions. Failing to do so causes
29727 erroneous execution if the source object is outside
29728 the 32-bit address space.
29729
29730 @item
29731 (optional) Explicitly use the 32-bit storage pool
29732 for access types used in a 32-bit context, or use
29733 generic access types where possible
29734 (@pxref{Restrictions on use of 64 bit objects}).
29735 @end itemize
29736
29737 @noindent
29738 If these rules are followed, the compiler will automatically insert
29739 any necessary checks to ensure that no addresses or access values
29740 passed to 32-bit code ever refer to objects outside the 32-bit
29741 address range.
29742 Any attempt to do this will raise @code{Constraint_Error}.
29743
29744 @node Allocating memory from the 64 bit storage pool
29745 @subsubsection Allocating memory from the 64-bit storage pool
29746
29747 @noindent
29748 By default, all allocations -- for both pool-specific and general
29749 access types -- use the 64-bit storage pool. To override
29750 this default, for an individual access type or globally, see
29751 @ref{Access types and 32/64-bit allocation}.
29752
29753 @node Restrictions on use of 64 bit objects
29754 @subsubsection Restrictions on use of 64-bit objects
29755
29756 @noindent
29757 Taking the address of an object allocated from a 64-bit storage pool,
29758 and then passing this address to a subprogram expecting
29759 @code{System.Short_Address},
29760 or assigning it to a variable of type @code{Short_Address}, will cause
29761 @code{Constraint_Error} to be raised. In case the code is not 64-bit clean
29762 (@pxref{Making code 64 bit clean}), or checks are suppressed,
29763 no exception is raised and execution
29764 will become erroneous.
29765
29766 @node STARLET and other predefined libraries
29767 @subsubsection STARLET and other predefined libraries
29768
29769 @noindent
29770 All code that comes as part of GNAT is 64-bit clean, but the
29771 restrictions given in @ref{Restrictions on use of 64 bit objects},
29772 still apply. Look at the package
29773 specs to see in which contexts objects allocated
29774 in 64-bit address space are acceptable.
29775
29776 @node Technical details
29777 @subsection Technical details
29778
29779 @noindent
29780 64-bit @value{EDITION} for Open VMS takes advantage of the freedom given in the
29781 Ada standard with respect to the type of @code{System.Address}. Previous
29782 versions of @value{EDITION} have defined this type as private and implemented it as a
29783 modular type.
29784
29785 In order to allow defining @code{System.Short_Address} as a proper subtype,
29786 and to match the implicit sign extension in parameter passing,
29787 in 64-bit @value{EDITION} for Open VMS, @code{System.Address} is defined as a
29788 visible (i.e., non-private) integer type.
29789 Standard operations on the type, such as the binary operators ``+'', ``-'',
29790 etc., that take @code{Address} operands and return an @code{Address} result,
29791 have been hidden by declaring these
29792 @code{abstract}, a feature introduced in Ada 95 that helps avoid the potential
29793 ambiguities that would otherwise result from overloading.
29794 (Note that, although @code{Address} is a visible integer type,
29795 good programming practice dictates against exploiting the type's
29796 integer properties such as literals, since this will compromise
29797 code portability.)
29798
29799 Defining @code{Address} as a visible integer type helps achieve
29800 maximum compatibility for existing Ada code,
29801 without sacrificing the capabilities of the 64-bit architecture.
29802 @end ifset
29803
29804 @c ************************************************
29805 @node Microsoft Windows Topics
29806 @appendix Microsoft Windows Topics
29807 @cindex Windows NT
29808 @cindex Windows 95
29809 @cindex Windows 98
29810
29811 @noindent
29812 This chapter describes topics that are specific to the Microsoft Windows
29813 platforms (NT, 2000, and XP Professional).
29814
29815 @menu
29816 @ifclear FSFEDITION
29817 * Installing from the Command Line::
29818 @end ifclear
29819 * Using GNAT on Windows::
29820 * Using a network installation of GNAT::
29821 * CONSOLE and WINDOWS subsystems::
29822 * Temporary Files::
29823 * Mixed-Language Programming on Windows::
29824 * Windows Calling Conventions::
29825 * Introduction to Dynamic Link Libraries (DLLs)::
29826 * Using DLLs with GNAT::
29827 * Building DLLs with GNAT Project files::
29828 * Building DLLs with GNAT::
29829 * Building DLLs with gnatdll::
29830 * GNAT and Windows Resources::
29831 * Debugging a DLL::
29832 * Setting Stack Size from gnatlink::
29833 * Setting Heap Size from gnatlink::
29834 @end menu
29835
29836 @ifclear FSFEDITION
29837 @node Installing from the Command Line
29838 @section Installing from the Command Line
29839 @cindex Batch installation
29840 @cindex Silent installation
29841 @cindex Unassisted installation
29842
29843 @noindent
29844 By default the @value{EDITION} installers display a GUI that prompts the user
29845 to enter installation path and similar information, and guide him through the
29846 installation process. It is also possible to perform silent installations
29847 using the command-line interface.
29848
29849 In order to install one of the @value{EDITION} installers from the command
29850 line you should pass parameter @code{/S} (and, optionally,
29851 @code{/D=<directory>}) as command-line arguments.
29852
29853 @ifset PROEDITION
29854 For example, for an unattended installation of
29855 @value{EDITION} 7.0.2 into the default directory
29856 @code{C:\GNATPRO\7.0.2} you would run:
29857
29858 @smallexample
29859 gnatpro-7.0.2-i686-pc-mingw32-bin.exe /S
29860 @end smallexample
29861
29862 To install into a custom directory, say, @code{C:\TOOLS\GNATPRO\7.0.2}:
29863
29864 @smallexample
29865 gnatpro-7.0.2-i686-pc-mingw32-bin /S /D=C:\TOOLS\GNATPRO\7.0.2
29866 @end smallexample
29867 @end ifset
29868
29869 @ifset GPLEDITION
29870 For example, for an unattended installation of
29871 @value{EDITION} 2012 into @code{C:\GNAT\2012}:
29872
29873 @smallexample
29874 gnat-gpl-2012-i686-pc-mingw32-bin /S /D=C:\GNAT\2012
29875 @end smallexample
29876 @end ifset
29877
29878 You can use the same syntax for all installers.
29879
29880 Note that unattended installations don't modify system path, nor create file
29881 associations, so such activities need to be done by hand.
29882 @end ifclear
29883
29884 @node Using GNAT on Windows
29885 @section Using GNAT on Windows
29886
29887 @noindent
29888 One of the strengths of the GNAT technology is that its tool set
29889 (@command{gcc}, @command{gnatbind}, @command{gnatlink}, @command{gnatmake}, the
29890 @code{gdb} debugger, etc.) is used in the same way regardless of the
29891 platform.
29892
29893 On Windows this tool set is complemented by a number of Microsoft-specific
29894 tools that have been provided to facilitate interoperability with Windows
29895 when this is required. With these tools:
29896
29897 @itemize @bullet
29898
29899 @item
29900 You can build applications using the @code{CONSOLE} or @code{WINDOWS}
29901 subsystems.
29902
29903 @item
29904 You can use any Dynamically Linked Library (DLL) in your Ada code (both
29905 relocatable and non-relocatable DLLs are supported).
29906
29907 @item
29908 You can build Ada DLLs for use in other applications. These applications
29909 can be written in a language other than Ada (e.g., C, C++, etc). Again both
29910 relocatable and non-relocatable Ada DLLs are supported.
29911
29912 @item
29913 You can include Windows resources in your Ada application.
29914
29915 @item
29916 You can use or create COM/DCOM objects.
29917 @end itemize
29918
29919 @noindent
29920 Immediately below are listed all known general GNAT-for-Windows restrictions.
29921 Other restrictions about specific features like Windows Resources and DLLs
29922 are listed in separate sections below.
29923
29924 @itemize @bullet
29925
29926 @item
29927 It is not possible to use @code{GetLastError} and @code{SetLastError}
29928 when tasking, protected records, or exceptions are used. In these
29929 cases, in order to implement Ada semantics, the GNAT run-time system
29930 calls certain Win32 routines that set the last error variable to 0 upon
29931 success. It should be possible to use @code{GetLastError} and
29932 @code{SetLastError} when tasking, protected record, and exception
29933 features are not used, but it is not guaranteed to work.
29934
29935 @item
29936 It is not possible to link against Microsoft C++ libraries except for
29937 import libraries. Interfacing must be done by the mean of DLLs.
29938
29939 @item
29940 It is possible to link against Microsoft C libraries. Yet the preferred
29941 solution is to use C/C++ compiler that comes with @value{EDITION}, since it
29942 doesn't require having two different development environments and makes the
29943 inter-language debugging experience smoother.
29944
29945 @item
29946 When the compilation environment is located on FAT32 drives, users may
29947 experience recompilations of the source files that have not changed if
29948 Daylight Saving Time (DST) state has changed since the last time files
29949 were compiled. NTFS drives do not have this problem.
29950
29951 @item
29952 No components of the GNAT toolset use any entries in the Windows
29953 registry. The only entries that can be created are file associations and
29954 PATH settings, provided the user has chosen to create them at installation
29955 time, as well as some minimal book-keeping information needed to correctly
29956 uninstall or integrate different GNAT products.
29957 @end itemize
29958
29959 @node Using a network installation of GNAT
29960 @section Using a network installation of GNAT
29961
29962 @noindent
29963 Make sure the system on which GNAT is installed is accessible from the
29964 current machine, i.e., the install location is shared over the network.
29965 Shared resources are accessed on Windows by means of UNC paths, which
29966 have the format @code{\\server\sharename\path}
29967
29968 In order to use such a network installation, simply add the UNC path of the
29969 @file{bin} directory of your GNAT installation in front of your PATH. For
29970 example, if GNAT is installed in @file{\GNAT} directory of a share location
29971 called @file{c-drive} on a machine @file{LOKI}, the following command will
29972 make it available:
29973
29974 @code{@ @ @ path \\loki\c-drive\gnat\bin;%path%}
29975
29976 Be aware that every compilation using the network installation results in the
29977 transfer of large amounts of data across the network and will likely cause
29978 serious performance penalty.
29979
29980 @node CONSOLE and WINDOWS subsystems
29981 @section CONSOLE and WINDOWS subsystems
29982 @cindex CONSOLE Subsystem
29983 @cindex WINDOWS Subsystem
29984 @cindex -mwindows
29985
29986 @noindent
29987 There are two main subsystems under Windows. The @code{CONSOLE} subsystem
29988 (which is the default subsystem) will always create a console when
29989 launching the application. This is not something desirable when the
29990 application has a Windows GUI. To get rid of this console the
29991 application must be using the @code{WINDOWS} subsystem. To do so
29992 the @option{-mwindows} linker option must be specified.
29993
29994 @smallexample
29995 $ gnatmake winprog -largs -mwindows
29996 @end smallexample
29997
29998 @node Temporary Files
29999 @section Temporary Files
30000 @cindex Temporary files
30001
30002 @noindent
30003 It is possible to control where temporary files gets created by setting
30004 the @env{TMP} environment variable. The file will be created:
30005
30006 @itemize
30007 @item Under the directory pointed to by the @env{TMP} environment variable if
30008 this directory exists.
30009
30010 @item Under @file{c:\temp}, if the @env{TMP} environment variable is not
30011 set (or not pointing to a directory) and if this directory exists.
30012
30013 @item Under the current working directory otherwise.
30014 @end itemize
30015
30016 @noindent
30017 This allows you to determine exactly where the temporary
30018 file will be created. This is particularly useful in networked
30019 environments where you may not have write access to some
30020 directories.
30021
30022 @node Mixed-Language Programming on Windows
30023 @section Mixed-Language Programming on Windows
30024
30025 @noindent
30026 Developing pure Ada applications on Windows is no different than on
30027 other GNAT-supported platforms. However, when developing or porting an
30028 application that contains a mix of Ada and C/C++, the choice of your
30029 Windows C/C++ development environment conditions your overall
30030 interoperability strategy.
30031
30032 If you use @command{gcc} or Microsoft C to compile the non-Ada part of
30033 your application, there are no Windows-specific restrictions that
30034 affect the overall interoperability with your Ada code. If you do want
30035 to use the Microsoft tools for your C++ code, you have two choices:
30036
30037 @enumerate
30038 @item
30039 Encapsulate your C++ code in a DLL to be linked with your Ada
30040 application. In this case, use the Microsoft or whatever environment to
30041 build the DLL and use GNAT to build your executable
30042 (@pxref{Using DLLs with GNAT}).
30043
30044 @item
30045 Or you can encapsulate your Ada code in a DLL to be linked with the
30046 other part of your application. In this case, use GNAT to build the DLL
30047 (@pxref{Building DLLs with GNAT Project files}) and use the Microsoft
30048 or whatever environment to build your executable.
30049 @end enumerate
30050
30051 In addition to the description about C main in
30052 @pxref{Mixed Language Programming} section, if the C main uses a
30053 stand-alone library it is required on x86-windows to
30054 setup the SEH context. For this the C main must looks like this:
30055
30056 @smallexample
30057 /* main.c */
30058 extern void adainit (void);
30059 extern void adafinal (void);
30060 extern void __gnat_initialize(void*);
30061 extern void call_to_ada (void);
30062
30063 int main (int argc, char *argv[])
30064 @{
30065 int SEH [2];
30066
30067 /* Initialize the SEH context */
30068 __gnat_initialize (&SEH);
30069
30070 adainit();
30071
30072 /* Then call Ada services in the stand-alone library */
30073
30074 call_to_ada();
30075
30076 adafinal();
30077 @}
30078 @end smallexample
30079
30080 Note that this is not needed on x86_64-windows where the Windows
30081 native SEH support is used.
30082
30083 @node Windows Calling Conventions
30084 @section Windows Calling Conventions
30085 @findex Stdcall
30086 @findex APIENTRY
30087
30088 This section pertain only to Win32. On Win64 there is a single native
30089 calling convention. All convention specifiers are ignored on this
30090 platform.
30091
30092 @menu
30093 * C Calling Convention::
30094 * Stdcall Calling Convention::
30095 * Win32 Calling Convention::
30096 * DLL Calling Convention::
30097 @end menu
30098
30099 @noindent
30100 When a subprogram @code{F} (caller) calls a subprogram @code{G}
30101 (callee), there are several ways to push @code{G}'s parameters on the
30102 stack and there are several possible scenarios to clean up the stack
30103 upon @code{G}'s return. A calling convention is an agreed upon software
30104 protocol whereby the responsibilities between the caller (@code{F}) and
30105 the callee (@code{G}) are clearly defined. Several calling conventions
30106 are available for Windows:
30107
30108 @itemize @bullet
30109 @item
30110 @code{C} (Microsoft defined)
30111
30112 @item
30113 @code{Stdcall} (Microsoft defined)
30114
30115 @item
30116 @code{Win32} (GNAT specific)
30117
30118 @item
30119 @code{DLL} (GNAT specific)
30120 @end itemize
30121
30122 @node C Calling Convention
30123 @subsection @code{C} Calling Convention
30124
30125 @noindent
30126 This is the default calling convention used when interfacing to C/C++
30127 routines compiled with either @command{gcc} or Microsoft Visual C++.
30128
30129 In the @code{C} calling convention subprogram parameters are pushed on the
30130 stack by the caller from right to left. The caller itself is in charge of
30131 cleaning up the stack after the call. In addition, the name of a routine
30132 with @code{C} calling convention is mangled by adding a leading underscore.
30133
30134 The name to use on the Ada side when importing (or exporting) a routine
30135 with @code{C} calling convention is the name of the routine. For
30136 instance the C function:
30137
30138 @smallexample
30139 int get_val (long);
30140 @end smallexample
30141
30142 @noindent
30143 should be imported from Ada as follows:
30144
30145 @smallexample @c ada
30146 @group
30147 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30148 pragma Import (C, Get_Val, External_Name => "get_val");
30149 @end group
30150 @end smallexample
30151
30152 @noindent
30153 Note that in this particular case the @code{External_Name} parameter could
30154 have been omitted since, when missing, this parameter is taken to be the
30155 name of the Ada entity in lower case. When the @code{Link_Name} parameter
30156 is missing, as in the above example, this parameter is set to be the
30157 @code{External_Name} with a leading underscore.
30158
30159 When importing a variable defined in C, you should always use the @code{C}
30160 calling convention unless the object containing the variable is part of a
30161 DLL (in which case you should use the @code{Stdcall} calling
30162 convention, @pxref{Stdcall Calling Convention}).
30163
30164 @node Stdcall Calling Convention
30165 @subsection @code{Stdcall} Calling Convention
30166
30167 @noindent
30168 This convention, which was the calling convention used for Pascal
30169 programs, is used by Microsoft for all the routines in the Win32 API for
30170 efficiency reasons. It must be used to import any routine for which this
30171 convention was specified.
30172
30173 In the @code{Stdcall} calling convention subprogram parameters are pushed
30174 on the stack by the caller from right to left. The callee (and not the
30175 caller) is in charge of cleaning the stack on routine exit. In addition,
30176 the name of a routine with @code{Stdcall} calling convention is mangled by
30177 adding a leading underscore (as for the @code{C} calling convention) and a
30178 trailing @code{@@}@code{@var{nn}}, where @var{nn} is the overall size (in
30179 bytes) of the parameters passed to the routine.
30180
30181 The name to use on the Ada side when importing a C routine with a
30182 @code{Stdcall} calling convention is the name of the C routine. The leading
30183 underscore and trailing @code{@@}@code{@var{nn}} are added automatically by
30184 the compiler. For instance the Win32 function:
30185
30186 @smallexample
30187 @b{APIENTRY} int get_val (long);
30188 @end smallexample
30189
30190 @noindent
30191 should be imported from Ada as follows:
30192
30193 @smallexample @c ada
30194 @group
30195 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30196 pragma Import (Stdcall, Get_Val);
30197 -- On the x86 a long is 4 bytes, so the Link_Name is "_get_val@@4"
30198 @end group
30199 @end smallexample
30200
30201 @noindent
30202 As for the @code{C} calling convention, when the @code{External_Name}
30203 parameter is missing, it is taken to be the name of the Ada entity in lower
30204 case. If instead of writing the above import pragma you write:
30205
30206 @smallexample @c ada
30207 @group
30208 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30209 pragma Import (Stdcall, Get_Val, External_Name => "retrieve_val");
30210 @end group
30211 @end smallexample
30212
30213 @noindent
30214 then the imported routine is @code{_retrieve_val@@4}. However, if instead
30215 of specifying the @code{External_Name} parameter you specify the
30216 @code{Link_Name} as in the following example:
30217
30218 @smallexample @c ada
30219 @group
30220 function Get_Val (V : Interfaces.C.long) return Interfaces.C.int;
30221 pragma Import (Stdcall, Get_Val, Link_Name => "retrieve_val");
30222 @end group
30223 @end smallexample
30224
30225 @noindent
30226 then the imported routine is @code{retrieve_val}, that is, there is no
30227 decoration at all. No leading underscore and no Stdcall suffix
30228 @code{@@}@code{@var{nn}}.
30229
30230 @noindent
30231 This is especially important as in some special cases a DLL's entry
30232 point name lacks a trailing @code{@@}@code{@var{nn}} while the exported
30233 name generated for a call has it.
30234
30235 @noindent
30236 It is also possible to import variables defined in a DLL by using an
30237 import pragma for a variable. As an example, if a DLL contains a
30238 variable defined as:
30239
30240 @smallexample
30241 int my_var;
30242 @end smallexample
30243
30244 @noindent
30245 then, to access this variable from Ada you should write:
30246
30247 @smallexample @c ada
30248 @group
30249 My_Var : Interfaces.C.int;
30250 pragma Import (Stdcall, My_Var);
30251 @end group
30252 @end smallexample
30253
30254 @noindent
30255 Note that to ease building cross-platform bindings this convention
30256 will be handled as a @code{C} calling convention on non-Windows platforms.
30257
30258 @node Win32 Calling Convention
30259 @subsection @code{Win32} Calling Convention
30260
30261 @noindent
30262 This convention, which is GNAT-specific is fully equivalent to the
30263 @code{Stdcall} calling convention described above.
30264
30265 @node DLL Calling Convention
30266 @subsection @code{DLL} Calling Convention
30267
30268 @noindent
30269 This convention, which is GNAT-specific is fully equivalent to the
30270 @code{Stdcall} calling convention described above.
30271
30272 @node Introduction to Dynamic Link Libraries (DLLs)
30273 @section Introduction to Dynamic Link Libraries (DLLs)
30274 @findex DLL
30275
30276 @noindent
30277 A Dynamically Linked Library (DLL) is a library that can be shared by
30278 several applications running under Windows. A DLL can contain any number of
30279 routines and variables.
30280
30281 One advantage of DLLs is that you can change and enhance them without
30282 forcing all the applications that depend on them to be relinked or
30283 recompiled. However, you should be aware than all calls to DLL routines are
30284 slower since, as you will understand below, such calls are indirect.
30285
30286 To illustrate the remainder of this section, suppose that an application
30287 wants to use the services of a DLL @file{API.dll}. To use the services
30288 provided by @file{API.dll} you must statically link against the DLL or
30289 an import library which contains a jump table with an entry for each
30290 routine and variable exported by the DLL. In the Microsoft world this
30291 import library is called @file{API.lib}. When using GNAT this import
30292 library is called either @file{libAPI.dll.a}, @file{libapi.dll.a},
30293 @file{libAPI.a} or @file{libapi.a} (names are case insensitive).
30294
30295 After you have linked your application with the DLL or the import library
30296 and you run your application, here is what happens:
30297
30298 @enumerate
30299 @item
30300 Your application is loaded into memory.
30301
30302 @item
30303 The DLL @file{API.dll} is mapped into the address space of your
30304 application. This means that:
30305
30306 @itemize @bullet
30307 @item
30308 The DLL will use the stack of the calling thread.
30309
30310 @item
30311 The DLL will use the virtual address space of the calling process.
30312
30313 @item
30314 The DLL will allocate memory from the virtual address space of the calling
30315 process.
30316
30317 @item
30318 Handles (pointers) can be safely exchanged between routines in the DLL
30319 routines and routines in the application using the DLL.
30320 @end itemize
30321
30322 @item
30323 The entries in the jump table (from the import library @file{libAPI.dll.a}
30324 or @file{API.lib} or automatically created when linking against a DLL)
30325 which is part of your application are initialized with the addresses
30326 of the routines and variables in @file{API.dll}.
30327
30328 @item
30329 If present in @file{API.dll}, routines @code{DllMain} or
30330 @code{DllMainCRTStartup} are invoked. These routines typically contain
30331 the initialization code needed for the well-being of the routines and
30332 variables exported by the DLL.
30333 @end enumerate
30334
30335 @noindent
30336 There is an additional point which is worth mentioning. In the Windows
30337 world there are two kind of DLLs: relocatable and non-relocatable
30338 DLLs. Non-relocatable DLLs can only be loaded at a very specific address
30339 in the target application address space. If the addresses of two
30340 non-relocatable DLLs overlap and these happen to be used by the same
30341 application, a conflict will occur and the application will run
30342 incorrectly. Hence, when possible, it is always preferable to use and
30343 build relocatable DLLs. Both relocatable and non-relocatable DLLs are
30344 supported by GNAT. Note that the @option{-s} linker option (see GNU Linker
30345 User's Guide) removes the debugging symbols from the DLL but the DLL can
30346 still be relocated.
30347
30348 As a side note, an interesting difference between Microsoft DLLs and
30349 Unix shared libraries, is the fact that on most Unix systems all public
30350 routines are exported by default in a Unix shared library, while under
30351 Windows it is possible (but not required) to list exported routines in
30352 a definition file (@pxref{The Definition File}).
30353
30354 @node Using DLLs with GNAT
30355 @section Using DLLs with GNAT
30356
30357 @menu
30358 * Creating an Ada Spec for the DLL Services::
30359 * Creating an Import Library::
30360 @end menu
30361
30362 @noindent
30363 To use the services of a DLL, say @file{API.dll}, in your Ada application
30364 you must have:
30365
30366 @enumerate
30367 @item
30368 The Ada spec for the routines and/or variables you want to access in
30369 @file{API.dll}. If not available this Ada spec must be built from the C/C++
30370 header files provided with the DLL.
30371
30372 @item
30373 The import library (@file{libAPI.dll.a} or @file{API.lib}). As previously
30374 mentioned an import library is a statically linked library containing the
30375 import table which will be filled at load time to point to the actual
30376 @file{API.dll} routines. Sometimes you don't have an import library for the
30377 DLL you want to use. The following sections will explain how to build
30378 one. Note that this is optional.
30379
30380 @item
30381 The actual DLL, @file{API.dll}.
30382 @end enumerate
30383
30384 @noindent
30385 Once you have all the above, to compile an Ada application that uses the
30386 services of @file{API.dll} and whose main subprogram is @code{My_Ada_App},
30387 you simply issue the command
30388
30389 @smallexample
30390 $ gnatmake my_ada_app -largs -lAPI
30391 @end smallexample
30392
30393 @noindent
30394 The argument @option{-largs -lAPI} at the end of the @command{gnatmake} command
30395 tells the GNAT linker to look for an import library. The linker will
30396 look for a library name in this specific order:
30397
30398 @enumerate
30399 @item @file{libAPI.dll.a}
30400 @item @file{API.dll.a}
30401 @item @file{libAPI.a}
30402 @item @file{API.lib}
30403 @item @file{libAPI.dll}
30404 @item @file{API.dll}
30405 @end enumerate
30406
30407 The first three are the GNU style import libraries. The third is the
30408 Microsoft style import libraries. The last two are the actual DLL names.
30409
30410 Note that if the Ada package spec for @file{API.dll} contains the
30411 following pragma
30412
30413 @smallexample @c ada
30414 pragma Linker_Options ("-lAPI");
30415 @end smallexample
30416
30417 @noindent
30418 you do not have to add @option{-largs -lAPI} at the end of the
30419 @command{gnatmake} command.
30420
30421 If any one of the items above is missing you will have to create it
30422 yourself. The following sections explain how to do so using as an
30423 example a fictitious DLL called @file{API.dll}.
30424
30425 @node Creating an Ada Spec for the DLL Services
30426 @subsection Creating an Ada Spec for the DLL Services
30427
30428 @noindent
30429 A DLL typically comes with a C/C++ header file which provides the
30430 definitions of the routines and variables exported by the DLL. The Ada
30431 equivalent of this header file is a package spec that contains definitions
30432 for the imported entities. If the DLL you intend to use does not come with
30433 an Ada spec you have to generate one such spec yourself. For example if
30434 the header file of @file{API.dll} is a file @file{api.h} containing the
30435 following two definitions:
30436
30437 @smallexample
30438 @group
30439 @cartouche
30440 int some_var;
30441 int get (char *);
30442 @end cartouche
30443 @end group
30444 @end smallexample
30445
30446 @noindent
30447 then the equivalent Ada spec could be:
30448
30449 @smallexample @c ada
30450 @group
30451 @cartouche
30452 with Interfaces.C.Strings;
30453 package API is
30454 use Interfaces;
30455
30456 Some_Var : C.int;
30457 function Get (Str : C.Strings.Chars_Ptr) return C.int;
30458
30459 private
30460 pragma Import (C, Get);
30461 pragma Import (DLL, Some_Var);
30462 end API;
30463 @end cartouche
30464 @end group
30465 @end smallexample
30466
30467 @node Creating an Import Library
30468 @subsection Creating an Import Library
30469 @cindex Import library
30470
30471 @menu
30472 * The Definition File::
30473 * GNAT-Style Import Library::
30474 * Microsoft-Style Import Library::
30475 @end menu
30476
30477 @noindent
30478 If a Microsoft-style import library @file{API.lib} or a GNAT-style
30479 import library @file{libAPI.dll.a} or @file{libAPI.a} is available
30480 with @file{API.dll} you can skip this section. You can also skip this
30481 section if @file{API.dll} or @file{libAPI.dll} is built with GNU tools
30482 as in this case it is possible to link directly against the
30483 DLL. Otherwise read on.
30484
30485 @node The Definition File
30486 @subsubsection The Definition File
30487 @cindex Definition file
30488 @findex .def
30489
30490 @noindent
30491 As previously mentioned, and unlike Unix systems, the list of symbols
30492 that are exported from a DLL must be provided explicitly in Windows.
30493 The main goal of a definition file is precisely that: list the symbols
30494 exported by a DLL. A definition file (usually a file with a @code{.def}
30495 suffix) has the following structure:
30496
30497 @smallexample
30498 @group
30499 @cartouche
30500 @r{[}LIBRARY @var{name}@r{]}
30501 @r{[}DESCRIPTION @var{string}@r{]}
30502 EXPORTS
30503 @var{symbol1}
30504 @var{symbol2}
30505 @dots{}
30506 @end cartouche
30507 @end group
30508 @end smallexample
30509
30510 @table @code
30511 @item LIBRARY @var{name}
30512 This section, which is optional, gives the name of the DLL.
30513
30514 @item DESCRIPTION @var{string}
30515 This section, which is optional, gives a description string that will be
30516 embedded in the import library.
30517
30518 @item EXPORTS
30519 This section gives the list of exported symbols (procedures, functions or
30520 variables). For instance in the case of @file{API.dll} the @code{EXPORTS}
30521 section of @file{API.def} looks like:
30522
30523 @smallexample
30524 @group
30525 @cartouche
30526 EXPORTS
30527 some_var
30528 get
30529 @end cartouche
30530 @end group
30531 @end smallexample
30532 @end table
30533
30534 @noindent
30535 Note that you must specify the correct suffix (@code{@@}@code{@var{nn}})
30536 (@pxref{Windows Calling Conventions}) for a Stdcall
30537 calling convention function in the exported symbols list.
30538
30539 @noindent
30540 There can actually be other sections in a definition file, but these
30541 sections are not relevant to the discussion at hand.
30542
30543 @node GNAT-Style Import Library
30544 @subsubsection GNAT-Style Import Library
30545
30546 @noindent
30547 To create a static import library from @file{API.dll} with the GNAT tools
30548 you should proceed as follows:
30549
30550 @enumerate
30551 @item
30552 Create the definition file @file{API.def} (@pxref{The Definition File}).
30553 For that use the @code{dll2def} tool as follows:
30554
30555 @smallexample
30556 $ dll2def API.dll > API.def
30557 @end smallexample
30558
30559 @noindent
30560 @code{dll2def} is a very simple tool: it takes as input a DLL and prints
30561 to standard output the list of entry points in the DLL. Note that if
30562 some routines in the DLL have the @code{Stdcall} convention
30563 (@pxref{Windows Calling Conventions}) with stripped @code{@@}@var{nn}
30564 suffix then you'll have to edit @file{api.def} to add it, and specify
30565 @option{-k} to @command{gnatdll} when creating the import library.
30566
30567 @noindent
30568 Here are some hints to find the right @code{@@}@var{nn} suffix.
30569
30570 @enumerate
30571 @item
30572 If you have the Microsoft import library (.lib), it is possible to get
30573 the right symbols by using Microsoft @code{dumpbin} tool (see the
30574 corresponding Microsoft documentation for further details).
30575
30576 @smallexample
30577 $ dumpbin /exports api.lib
30578 @end smallexample
30579
30580 @item
30581 If you have a message about a missing symbol at link time the compiler
30582 tells you what symbol is expected. You just have to go back to the
30583 definition file and add the right suffix.
30584 @end enumerate
30585
30586 @item
30587 Build the import library @code{libAPI.dll.a}, using @code{gnatdll}
30588 (@pxref{Using gnatdll}) as follows:
30589
30590 @smallexample
30591 $ gnatdll -e API.def -d API.dll
30592 @end smallexample
30593
30594 @noindent
30595 @code{gnatdll} takes as input a definition file @file{API.def} and the
30596 name of the DLL containing the services listed in the definition file
30597 @file{API.dll}. The name of the static import library generated is
30598 computed from the name of the definition file as follows: if the
30599 definition file name is @var{xyz}@code{.def}, the import library name will
30600 be @code{lib}@var{xyz}@code{.a}. Note that in the previous example option
30601 @option{-e} could have been removed because the name of the definition
30602 file (before the ``@code{.def}'' suffix) is the same as the name of the
30603 DLL (@pxref{Using gnatdll} for more information about @code{gnatdll}).
30604 @end enumerate
30605
30606 @node Microsoft-Style Import Library
30607 @subsubsection Microsoft-Style Import Library
30608
30609 @noindent
30610 With GNAT you can either use a GNAT-style or Microsoft-style import
30611 library. A Microsoft import library is needed only if you plan to make an
30612 Ada DLL available to applications developed with Microsoft
30613 tools (@pxref{Mixed-Language Programming on Windows}).
30614
30615 To create a Microsoft-style import library for @file{API.dll} you
30616 should proceed as follows:
30617
30618 @enumerate
30619 @item
30620 Create the definition file @file{API.def} from the DLL. For this use either
30621 the @code{dll2def} tool as described above or the Microsoft @code{dumpbin}
30622 tool (see the corresponding Microsoft documentation for further details).
30623
30624 @item
30625 Build the actual import library using Microsoft's @code{lib} utility:
30626
30627 @smallexample
30628 $ lib -machine:IX86 -def:API.def -out:API.lib
30629 @end smallexample
30630
30631 @noindent
30632 If you use the above command the definition file @file{API.def} must
30633 contain a line giving the name of the DLL:
30634
30635 @smallexample
30636 LIBRARY "API"
30637 @end smallexample
30638
30639 @noindent
30640 See the Microsoft documentation for further details about the usage of
30641 @code{lib}.
30642 @end enumerate
30643
30644 @node Building DLLs with GNAT Project files
30645 @section Building DLLs with GNAT Project files
30646 @cindex DLLs, building
30647
30648 @noindent
30649 There is nothing specific to Windows in the build process.
30650 @pxref{Library Projects}.
30651
30652 @noindent
30653 Due to a system limitation, it is not possible under Windows to create threads
30654 when inside the @code{DllMain} routine which is used for auto-initialization
30655 of shared libraries, so it is not possible to have library level tasks in SALs.
30656
30657 @node Building DLLs with GNAT
30658 @section Building DLLs with GNAT
30659 @cindex DLLs, building
30660
30661 @noindent
30662 This section explain how to build DLLs using the GNAT built-in DLL
30663 support. With the following procedure it is straight forward to build
30664 and use DLLs with GNAT.
30665
30666 @enumerate
30667
30668 @item building object files
30669
30670 The first step is to build all objects files that are to be included
30671 into the DLL. This is done by using the standard @command{gnatmake} tool.
30672
30673 @item building the DLL
30674
30675 To build the DLL you must use @command{gcc}'s @option{-shared} and
30676 @option{-shared-libgcc} options. It is quite simple to use this method:
30677
30678 @smallexample
30679 $ gcc -shared -shared-libgcc -o api.dll obj1.o obj2.o @dots{}
30680 @end smallexample
30681
30682 It is important to note that in this case all symbols found in the
30683 object files are automatically exported. It is possible to restrict
30684 the set of symbols to export by passing to @command{gcc} a definition
30685 file, @pxref{The Definition File}. For example:
30686
30687 @smallexample
30688 $ gcc -shared -shared-libgcc -o api.dll api.def obj1.o obj2.o @dots{}
30689 @end smallexample
30690
30691 If you use a definition file you must export the elaboration procedures
30692 for every package that required one. Elaboration procedures are named
30693 using the package name followed by "_E".
30694
30695 @item preparing DLL to be used
30696
30697 For the DLL to be used by client programs the bodies must be hidden
30698 from it and the .ali set with read-only attribute. This is very important
30699 otherwise GNAT will recompile all packages and will not actually use
30700 the code in the DLL. For example:
30701
30702 @smallexample
30703 $ mkdir apilib
30704 $ copy *.ads *.ali api.dll apilib
30705 $ attrib +R apilib\*.ali
30706 @end smallexample
30707
30708 @end enumerate
30709
30710 At this point it is possible to use the DLL by directly linking
30711 against it. Note that you must use the GNAT shared runtime when using
30712 GNAT shared libraries. This is achieved by using @option{-shared} binder's
30713 option.
30714
30715 @smallexample
30716 $ gnatmake main -Iapilib -bargs -shared -largs -Lapilib -lAPI
30717 @end smallexample
30718
30719 @node Building DLLs with gnatdll
30720 @section Building DLLs with gnatdll
30721 @cindex DLLs, building
30722
30723 @menu
30724 * Limitations When Using Ada DLLs from Ada::
30725 * Exporting Ada Entities::
30726 * Ada DLLs and Elaboration::
30727 * Ada DLLs and Finalization::
30728 * Creating a Spec for Ada DLLs::
30729 * Creating the Definition File::
30730 * Using gnatdll::
30731 @end menu
30732
30733 @noindent
30734 Note that it is preferred to use GNAT Project files
30735 (@pxref{Building DLLs with GNAT Project files}) or the built-in GNAT
30736 DLL support (@pxref{Building DLLs with GNAT}) or to build DLLs.
30737
30738 This section explains how to build DLLs containing Ada code using
30739 @code{gnatdll}. These DLLs will be referred to as Ada DLLs in the
30740 remainder of this section.
30741
30742 The steps required to build an Ada DLL that is to be used by Ada as well as
30743 non-Ada applications are as follows:
30744
30745 @enumerate
30746 @item
30747 You need to mark each Ada @i{entity} exported by the DLL with a @code{C} or
30748 @code{Stdcall} calling convention to avoid any Ada name mangling for the
30749 entities exported by the DLL (@pxref{Exporting Ada Entities}). You can
30750 skip this step if you plan to use the Ada DLL only from Ada applications.
30751
30752 @item
30753 Your Ada code must export an initialization routine which calls the routine
30754 @code{adainit} generated by @command{gnatbind} to perform the elaboration of
30755 the Ada code in the DLL (@pxref{Ada DLLs and Elaboration}). The initialization
30756 routine exported by the Ada DLL must be invoked by the clients of the DLL
30757 to initialize the DLL.
30758
30759 @item
30760 When useful, the DLL should also export a finalization routine which calls
30761 routine @code{adafinal} generated by @command{gnatbind} to perform the
30762 finalization of the Ada code in the DLL (@pxref{Ada DLLs and Finalization}).
30763 The finalization routine exported by the Ada DLL must be invoked by the
30764 clients of the DLL when the DLL services are no further needed.
30765
30766 @item
30767 You must provide a spec for the services exported by the Ada DLL in each
30768 of the programming languages to which you plan to make the DLL available.
30769
30770 @item
30771 You must provide a definition file listing the exported entities
30772 (@pxref{The Definition File}).
30773
30774 @item
30775 Finally you must use @code{gnatdll} to produce the DLL and the import
30776 library (@pxref{Using gnatdll}).
30777 @end enumerate
30778
30779 @noindent
30780 Note that a relocatable DLL stripped using the @code{strip}
30781 binutils tool will not be relocatable anymore. To build a DLL without
30782 debug information pass @code{-largs -s} to @code{gnatdll}. This
30783 restriction does not apply to a DLL built using a Library Project.
30784 @pxref{Library Projects}.
30785
30786 @node Limitations When Using Ada DLLs from Ada
30787 @subsection Limitations When Using Ada DLLs from Ada
30788
30789 @noindent
30790 When using Ada DLLs from Ada applications there is a limitation users
30791 should be aware of. Because on Windows the GNAT run time is not in a DLL of
30792 its own, each Ada DLL includes a part of the GNAT run time. Specifically,
30793 each Ada DLL includes the services of the GNAT run time that are necessary
30794 to the Ada code inside the DLL. As a result, when an Ada program uses an
30795 Ada DLL there are two independent GNAT run times: one in the Ada DLL and
30796 one in the main program.
30797
30798 It is therefore not possible to exchange GNAT run-time objects between the
30799 Ada DLL and the main Ada program. Example of GNAT run-time objects are file
30800 handles (e.g.@: @code{Text_IO.File_Type}), tasks types, protected objects
30801 types, etc.
30802
30803 It is completely safe to exchange plain elementary, array or record types,
30804 Windows object handles, etc.
30805
30806 @node Exporting Ada Entities
30807 @subsection Exporting Ada Entities
30808 @cindex Export table
30809
30810 @noindent
30811 Building a DLL is a way to encapsulate a set of services usable from any
30812 application. As a result, the Ada entities exported by a DLL should be
30813 exported with the @code{C} or @code{Stdcall} calling conventions to avoid
30814 any Ada name mangling. As an example here is an Ada package
30815 @code{API}, spec and body, exporting two procedures, a function, and a
30816 variable:
30817
30818 @smallexample @c ada
30819 @group
30820 @cartouche
30821 with Interfaces.C; use Interfaces;
30822 package API is
30823 Count : C.int := 0;
30824 function Factorial (Val : C.int) return C.int;
30825
30826 procedure Initialize_API;
30827 procedure Finalize_API;
30828 -- Initialization & Finalization routines. More in the next section.
30829 private
30830 pragma Export (C, Initialize_API);
30831 pragma Export (C, Finalize_API);
30832 pragma Export (C, Count);
30833 pragma Export (C, Factorial);
30834 end API;
30835 @end cartouche
30836 @end group
30837 @end smallexample
30838
30839 @smallexample @c ada
30840 @group
30841 @cartouche
30842 package body API is
30843 function Factorial (Val : C.int) return C.int is
30844 Fact : C.int := 1;
30845 begin
30846 Count := Count + 1;
30847 for K in 1 .. Val loop
30848 Fact := Fact * K;
30849 end loop;
30850 return Fact;
30851 end Factorial;
30852
30853 procedure Initialize_API is
30854 procedure Adainit;
30855 pragma Import (C, Adainit);
30856 begin
30857 Adainit;
30858 end Initialize_API;
30859
30860 procedure Finalize_API is
30861 procedure Adafinal;
30862 pragma Import (C, Adafinal);
30863 begin
30864 Adafinal;
30865 end Finalize_API;
30866 end API;
30867 @end cartouche
30868 @end group
30869 @end smallexample
30870
30871 @noindent
30872 If the Ada DLL you are building will only be used by Ada applications
30873 you do not have to export Ada entities with a @code{C} or @code{Stdcall}
30874 convention. As an example, the previous package could be written as
30875 follows:
30876
30877 @smallexample @c ada
30878 @group
30879 @cartouche
30880 package API is
30881 Count : Integer := 0;
30882 function Factorial (Val : Integer) return Integer;
30883
30884 procedure Initialize_API;
30885 procedure Finalize_API;
30886 -- Initialization and Finalization routines.
30887 end API;
30888 @end cartouche
30889 @end group
30890 @end smallexample
30891
30892 @smallexample @c ada
30893 @group
30894 @cartouche
30895 package body API is
30896 function Factorial (Val : Integer) return Integer is
30897 Fact : Integer := 1;
30898 begin
30899 Count := Count + 1;
30900 for K in 1 .. Val loop
30901 Fact := Fact * K;
30902 end loop;
30903 return Fact;
30904 end Factorial;
30905
30906 @dots{}
30907 -- The remainder of this package body is unchanged.
30908 end API;
30909 @end cartouche
30910 @end group
30911 @end smallexample
30912
30913 @noindent
30914 Note that if you do not export the Ada entities with a @code{C} or
30915 @code{Stdcall} convention you will have to provide the mangled Ada names
30916 in the definition file of the Ada DLL
30917 (@pxref{Creating the Definition File}).
30918
30919 @node Ada DLLs and Elaboration
30920 @subsection Ada DLLs and Elaboration
30921 @cindex DLLs and elaboration
30922
30923 @noindent
30924 The DLL that you are building contains your Ada code as well as all the
30925 routines in the Ada library that are needed by it. The first thing a
30926 user of your DLL must do is elaborate the Ada code
30927 (@pxref{Elaboration Order Handling in GNAT}).
30928
30929 To achieve this you must export an initialization routine
30930 (@code{Initialize_API} in the previous example), which must be invoked
30931 before using any of the DLL services. This elaboration routine must call
30932 the Ada elaboration routine @code{adainit} generated by the GNAT binder
30933 (@pxref{Binding with Non-Ada Main Programs}). See the body of
30934 @code{Initialize_Api} for an example. Note that the GNAT binder is
30935 automatically invoked during the DLL build process by the @code{gnatdll}
30936 tool (@pxref{Using gnatdll}).
30937
30938 When a DLL is loaded, Windows systematically invokes a routine called
30939 @code{DllMain}. It would therefore be possible to call @code{adainit}
30940 directly from @code{DllMain} without having to provide an explicit
30941 initialization routine. Unfortunately, it is not possible to call
30942 @code{adainit} from the @code{DllMain} if your program has library level
30943 tasks because access to the @code{DllMain} entry point is serialized by
30944 the system (that is, only a single thread can execute ``through'' it at a
30945 time), which means that the GNAT run time will deadlock waiting for the
30946 newly created task to complete its initialization.
30947
30948 @node Ada DLLs and Finalization
30949 @subsection Ada DLLs and Finalization
30950 @cindex DLLs and finalization
30951
30952 @noindent
30953 When the services of an Ada DLL are no longer needed, the client code should
30954 invoke the DLL finalization routine, if available. The DLL finalization
30955 routine is in charge of releasing all resources acquired by the DLL. In the
30956 case of the Ada code contained in the DLL, this is achieved by calling
30957 routine @code{adafinal} generated by the GNAT binder
30958 (@pxref{Binding with Non-Ada Main Programs}).
30959 See the body of @code{Finalize_Api} for an
30960 example. As already pointed out the GNAT binder is automatically invoked
30961 during the DLL build process by the @code{gnatdll} tool
30962 (@pxref{Using gnatdll}).
30963
30964 @node Creating a Spec for Ada DLLs
30965 @subsection Creating a Spec for Ada DLLs
30966
30967 @noindent
30968 To use the services exported by the Ada DLL from another programming
30969 language (e.g.@: C), you have to translate the specs of the exported Ada
30970 entities in that language. For instance in the case of @code{API.dll},
30971 the corresponding C header file could look like:
30972
30973 @smallexample
30974 @group
30975 @cartouche
30976 extern int *_imp__count;
30977 #define count (*_imp__count)
30978 int factorial (int);
30979 @end cartouche
30980 @end group
30981 @end smallexample
30982
30983 @noindent
30984 It is important to understand that when building an Ada DLL to be used by
30985 other Ada applications, you need two different specs for the packages
30986 contained in the DLL: one for building the DLL and the other for using
30987 the DLL. This is because the @code{DLL} calling convention is needed to
30988 use a variable defined in a DLL, but when building the DLL, the variable
30989 must have either the @code{Ada} or @code{C} calling convention. As an
30990 example consider a DLL comprising the following package @code{API}:
30991
30992 @smallexample @c ada
30993 @group
30994 @cartouche
30995 package API is
30996 Count : Integer := 0;
30997 @dots{}
30998 -- Remainder of the package omitted.
30999 end API;
31000 @end cartouche
31001 @end group
31002 @end smallexample
31003
31004 @noindent
31005 After producing a DLL containing package @code{API}, the spec that
31006 must be used to import @code{API.Count} from Ada code outside of the
31007 DLL is:
31008
31009 @smallexample @c ada
31010 @group
31011 @cartouche
31012 package API is
31013 Count : Integer;
31014 pragma Import (DLL, Count);
31015 end API;
31016 @end cartouche
31017 @end group
31018 @end smallexample
31019
31020 @node Creating the Definition File
31021 @subsection Creating the Definition File
31022
31023 @noindent
31024 The definition file is the last file needed to build the DLL. It lists
31025 the exported symbols. As an example, the definition file for a DLL
31026 containing only package @code{API} (where all the entities are exported
31027 with a @code{C} calling convention) is:
31028
31029 @smallexample
31030 @group
31031 @cartouche
31032 EXPORTS
31033 count
31034 factorial
31035 finalize_api
31036 initialize_api
31037 @end cartouche
31038 @end group
31039 @end smallexample
31040
31041 @noindent
31042 If the @code{C} calling convention is missing from package @code{API},
31043 then the definition file contains the mangled Ada names of the above
31044 entities, which in this case are:
31045
31046 @smallexample
31047 @group
31048 @cartouche
31049 EXPORTS
31050 api__count
31051 api__factorial
31052 api__finalize_api
31053 api__initialize_api
31054 @end cartouche
31055 @end group
31056 @end smallexample
31057
31058 @node Using gnatdll
31059 @subsection Using @code{gnatdll}
31060 @findex gnatdll
31061
31062 @menu
31063 * gnatdll Example::
31064 * gnatdll behind the Scenes::
31065 * Using dlltool::
31066 @end menu
31067
31068 @noindent
31069 @code{gnatdll} is a tool to automate the DLL build process once all the Ada
31070 and non-Ada sources that make up your DLL have been compiled.
31071 @code{gnatdll} is actually in charge of two distinct tasks: build the
31072 static import library for the DLL and the actual DLL. The form of the
31073 @code{gnatdll} command is
31074
31075 @smallexample
31076 @cartouche
31077 @c $ gnatdll @ovar{switches} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
31078 @c Expanding @ovar macro inline (explanation in macro def comments)
31079 $ gnatdll @r{[}@var{switches}@r{]} @var{list-of-files} @r{[}-largs @var{opts}@r{]}
31080 @end cartouche
31081 @end smallexample
31082
31083 @noindent
31084 where @var{list-of-files} is a list of ALI and object files. The object
31085 file list must be the exact list of objects corresponding to the non-Ada
31086 sources whose services are to be included in the DLL. The ALI file list
31087 must be the exact list of ALI files for the corresponding Ada sources
31088 whose services are to be included in the DLL. If @var{list-of-files} is
31089 missing, only the static import library is generated.
31090
31091 @noindent
31092 You may specify any of the following switches to @code{gnatdll}:
31093
31094 @table @code
31095 @c @item -a@ovar{address}
31096 @c Expanding @ovar macro inline (explanation in macro def comments)
31097 @item -a@r{[}@var{address}@r{]}
31098 @cindex @option{-a} (@code{gnatdll})
31099 Build a non-relocatable DLL at @var{address}. If @var{address} is not
31100 specified the default address @var{0x11000000} will be used. By default,
31101 when this switch is missing, @code{gnatdll} builds relocatable DLL. We
31102 advise the reader to build relocatable DLL.
31103
31104 @item -b @var{address}
31105 @cindex @option{-b} (@code{gnatdll})
31106 Set the relocatable DLL base address. By default the address is
31107 @code{0x11000000}.
31108
31109 @item -bargs @var{opts}
31110 @cindex @option{-bargs} (@code{gnatdll})
31111 Binder options. Pass @var{opts} to the binder.
31112
31113 @item -d @var{dllfile}
31114 @cindex @option{-d} (@code{gnatdll})
31115 @var{dllfile} is the name of the DLL. This switch must be present for
31116 @code{gnatdll} to do anything. The name of the generated import library is
31117 obtained algorithmically from @var{dllfile} as shown in the following
31118 example: if @var{dllfile} is @code{xyz.dll}, the import library name is
31119 @code{libxyz.dll.a}. The name of the definition file to use (if not specified
31120 by option @option{-e}) is obtained algorithmically from @var{dllfile}
31121 as shown in the following example:
31122 if @var{dllfile} is @code{xyz.dll}, the definition
31123 file used is @code{xyz.def}.
31124
31125 @item -e @var{deffile}
31126 @cindex @option{-e} (@code{gnatdll})
31127 @var{deffile} is the name of the definition file.
31128
31129 @item -g
31130 @cindex @option{-g} (@code{gnatdll})
31131 Generate debugging information. This information is stored in the object
31132 file and copied from there to the final DLL file by the linker,
31133 where it can be read by the debugger. You must use the
31134 @option{-g} switch if you plan on using the debugger or the symbolic
31135 stack traceback.
31136
31137 @item -h
31138 @cindex @option{-h} (@code{gnatdll})
31139 Help mode. Displays @code{gnatdll} switch usage information.
31140
31141 @item -Idir
31142 @cindex @option{-I} (@code{gnatdll})
31143 Direct @code{gnatdll} to search the @var{dir} directory for source and
31144 object files needed to build the DLL.
31145 (@pxref{Search Paths and the Run-Time Library (RTL)}).
31146
31147 @item -k
31148 @cindex @option{-k} (@code{gnatdll})
31149 Removes the @code{@@}@var{nn} suffix from the import library's exported
31150 names, but keeps them for the link names. You must specify this
31151 option if you want to use a @code{Stdcall} function in a DLL for which
31152 the @code{@@}@var{nn} suffix has been removed. This is the case for most
31153 of the Windows NT DLL for example. This option has no effect when
31154 @option{-n} option is specified.
31155
31156 @item -l @var{file}
31157 @cindex @option{-l} (@code{gnatdll})
31158 The list of ALI and object files used to build the DLL are listed in
31159 @var{file}, instead of being given in the command line. Each line in
31160 @var{file} contains the name of an ALI or object file.
31161
31162 @item -n
31163 @cindex @option{-n} (@code{gnatdll})
31164 No Import. Do not create the import library.
31165
31166 @item -q
31167 @cindex @option{-q} (@code{gnatdll})
31168 Quiet mode. Do not display unnecessary messages.
31169
31170 @item -v
31171 @cindex @option{-v} (@code{gnatdll})
31172 Verbose mode. Display extra information.
31173
31174 @item -largs @var{opts}
31175 @cindex @option{-largs} (@code{gnatdll})
31176 Linker options. Pass @var{opts} to the linker.
31177 @end table
31178
31179 @node gnatdll Example
31180 @subsubsection @code{gnatdll} Example
31181
31182 @noindent
31183 As an example the command to build a relocatable DLL from @file{api.adb}
31184 once @file{api.adb} has been compiled and @file{api.def} created is
31185
31186 @smallexample
31187 $ gnatdll -d api.dll api.ali
31188 @end smallexample
31189
31190 @noindent
31191 The above command creates two files: @file{libapi.dll.a} (the import
31192 library) and @file{api.dll} (the actual DLL). If you want to create
31193 only the DLL, just type:
31194
31195 @smallexample
31196 $ gnatdll -d api.dll -n api.ali
31197 @end smallexample
31198
31199 @noindent
31200 Alternatively if you want to create just the import library, type:
31201
31202 @smallexample
31203 $ gnatdll -d api.dll
31204 @end smallexample
31205
31206 @node gnatdll behind the Scenes
31207 @subsubsection @code{gnatdll} behind the Scenes
31208
31209 @noindent
31210 This section details the steps involved in creating a DLL. @code{gnatdll}
31211 does these steps for you. Unless you are interested in understanding what
31212 goes on behind the scenes, you should skip this section.
31213
31214 We use the previous example of a DLL containing the Ada package @code{API},
31215 to illustrate the steps necessary to build a DLL. The starting point is a
31216 set of objects that will make up the DLL and the corresponding ALI
31217 files. In the case of this example this means that @file{api.o} and
31218 @file{api.ali} are available. To build a relocatable DLL, @code{gnatdll} does
31219 the following:
31220
31221 @enumerate
31222 @item
31223 @code{gnatdll} builds the base file (@file{api.base}). A base file gives
31224 the information necessary to generate relocation information for the
31225 DLL.
31226
31227 @smallexample
31228 @group
31229 $ gnatbind -n api
31230 $ gnatlink api -o api.jnk -mdll -Wl,--base-file,api.base
31231 @end group
31232 @end smallexample
31233
31234 @noindent
31235 In addition to the base file, the @command{gnatlink} command generates an
31236 output file @file{api.jnk} which can be discarded. The @option{-mdll} switch
31237 asks @command{gnatlink} to generate the routines @code{DllMain} and
31238 @code{DllMainCRTStartup} that are called by the Windows loader when the DLL
31239 is loaded into memory.
31240
31241 @item
31242 @code{gnatdll} uses @code{dlltool} (@pxref{Using dlltool}) to build the
31243 export table (@file{api.exp}). The export table contains the relocation
31244 information in a form which can be used during the final link to ensure
31245 that the Windows loader is able to place the DLL anywhere in memory.
31246
31247 @smallexample
31248 @group
31249 $ dlltool --dllname api.dll --def api.def --base-file api.base \
31250 --output-exp api.exp
31251 @end group
31252 @end smallexample
31253
31254 @item
31255 @code{gnatdll} builds the base file using the new export table. Note that
31256 @command{gnatbind} must be called once again since the binder generated file
31257 has been deleted during the previous call to @command{gnatlink}.
31258
31259 @smallexample
31260 @group
31261 $ gnatbind -n api
31262 $ gnatlink api -o api.jnk api.exp -mdll
31263 -Wl,--base-file,api.base
31264 @end group
31265 @end smallexample
31266
31267 @item
31268 @code{gnatdll} builds the new export table using the new base file and
31269 generates the DLL import library @file{libAPI.dll.a}.
31270
31271 @smallexample
31272 @group
31273 $ dlltool --dllname api.dll --def api.def --base-file api.base \
31274 --output-exp api.exp --output-lib libAPI.a
31275 @end group
31276 @end smallexample
31277
31278 @item
31279 Finally @code{gnatdll} builds the relocatable DLL using the final export
31280 table.
31281
31282 @smallexample
31283 @group
31284 $ gnatbind -n api
31285 $ gnatlink api api.exp -o api.dll -mdll
31286 @end group
31287 @end smallexample
31288 @end enumerate
31289
31290 @node Using dlltool
31291 @subsubsection Using @code{dlltool}
31292
31293 @noindent
31294 @code{dlltool} is the low-level tool used by @code{gnatdll} to build
31295 DLLs and static import libraries. This section summarizes the most
31296 common @code{dlltool} switches. The form of the @code{dlltool} command
31297 is
31298
31299 @smallexample
31300 @c $ dlltool @ovar{switches}
31301 @c Expanding @ovar macro inline (explanation in macro def comments)
31302 $ dlltool @r{[}@var{switches}@r{]}
31303 @end smallexample
31304
31305 @noindent
31306 @code{dlltool} switches include:
31307
31308 @table @option
31309 @item --base-file @var{basefile}
31310 @cindex @option{--base-file} (@command{dlltool})
31311 Read the base file @var{basefile} generated by the linker. This switch
31312 is used to create a relocatable DLL.
31313
31314 @item --def @var{deffile}
31315 @cindex @option{--def} (@command{dlltool})
31316 Read the definition file.
31317
31318 @item --dllname @var{name}
31319 @cindex @option{--dllname} (@command{dlltool})
31320 Gives the name of the DLL. This switch is used to embed the name of the
31321 DLL in the static import library generated by @code{dlltool} with switch
31322 @option{--output-lib}.
31323
31324 @item -k
31325 @cindex @option{-k} (@command{dlltool})
31326 Kill @code{@@}@var{nn} from exported names
31327 (@pxref{Windows Calling Conventions}
31328 for a discussion about @code{Stdcall}-style symbols.
31329
31330 @item --help
31331 @cindex @option{--help} (@command{dlltool})
31332 Prints the @code{dlltool} switches with a concise description.
31333
31334 @item --output-exp @var{exportfile}
31335 @cindex @option{--output-exp} (@command{dlltool})
31336 Generate an export file @var{exportfile}. The export file contains the
31337 export table (list of symbols in the DLL) and is used to create the DLL.
31338
31339 @item --output-lib @var{libfile}
31340 @cindex @option{--output-lib} (@command{dlltool})
31341 Generate a static import library @var{libfile}.
31342
31343 @item -v
31344 @cindex @option{-v} (@command{dlltool})
31345 Verbose mode.
31346
31347 @item --as @var{assembler-name}
31348 @cindex @option{--as} (@command{dlltool})
31349 Use @var{assembler-name} as the assembler. The default is @code{as}.
31350 @end table
31351
31352 @node GNAT and Windows Resources
31353 @section GNAT and Windows Resources
31354 @cindex Resources, windows
31355
31356 @menu
31357 * Building Resources::
31358 * Compiling Resources::
31359 * Using Resources::
31360 @end menu
31361
31362 @noindent
31363 Resources are an easy way to add Windows specific objects to your
31364 application. The objects that can be added as resources include:
31365
31366 @itemize @bullet
31367 @item menus
31368
31369 @item accelerators
31370
31371 @item dialog boxes
31372
31373 @item string tables
31374
31375 @item bitmaps
31376
31377 @item cursors
31378
31379 @item icons
31380
31381 @item fonts
31382
31383 @item version information
31384 @end itemize
31385
31386 For example, a version information resource can be defined as follow and
31387 embedded into an executable or DLL:
31388
31389 A version information resource can be used to embed information into an
31390 executable or a DLL. These information can be viewed using the file properties
31391 from the Windows Explorer. Here is an example of a version information
31392 resource:
31393
31394 @smallexample
31395 @group
31396 1 VERSIONINFO
31397 FILEVERSION 1,0,0,0
31398 PRODUCTVERSION 1,0,0,0
31399 BEGIN
31400 BLOCK "StringFileInfo"
31401 BEGIN
31402 BLOCK "080904E4"
31403 BEGIN
31404 VALUE "CompanyName", "My Company Name"
31405 VALUE "FileDescription", "My application"
31406 VALUE "FileVersion", "1.0"
31407 VALUE "InternalName", "my_app"
31408 VALUE "LegalCopyright", "My Name"
31409 VALUE "OriginalFilename", "my_app.exe"
31410 VALUE "ProductName", "My App"
31411 VALUE "ProductVersion", "1.0"
31412 END
31413 END
31414
31415 BLOCK "VarFileInfo"
31416 BEGIN
31417 VALUE "Translation", 0x809, 1252
31418 END
31419 END
31420 @end group
31421 @end smallexample
31422
31423 The value @code{0809} (langID) is for the U.K English language and
31424 @code{04E4} (charsetID), which is equal to @code{1252} decimal, for
31425 multilingual.
31426
31427 @noindent
31428 This section explains how to build, compile and use resources. Note that this
31429 section does not cover all resource objects, for a complete description see
31430 the corresponding Microsoft documentation.
31431
31432 @node Building Resources
31433 @subsection Building Resources
31434 @cindex Resources, building
31435
31436 @noindent
31437 A resource file is an ASCII file. By convention resource files have an
31438 @file{.rc} extension.
31439 The easiest way to build a resource file is to use Microsoft tools
31440 such as @code{imagedit.exe} to build bitmaps, icons and cursors and
31441 @code{dlgedit.exe} to build dialogs.
31442 It is always possible to build an @file{.rc} file yourself by writing a
31443 resource script.
31444
31445 It is not our objective to explain how to write a resource file. A
31446 complete description of the resource script language can be found in the
31447 Microsoft documentation.
31448
31449 @node Compiling Resources
31450 @subsection Compiling Resources
31451 @findex rc
31452 @findex windres
31453 @cindex Resources, compiling
31454
31455 @noindent
31456 This section describes how to build a GNAT-compatible (COFF) object file
31457 containing the resources. This is done using the Resource Compiler
31458 @code{windres} as follows:
31459
31460 @smallexample
31461 $ windres -i myres.rc -o myres.o
31462 @end smallexample
31463
31464 @noindent
31465 By default @code{windres} will run @command{gcc} to preprocess the @file{.rc}
31466 file. You can specify an alternate preprocessor (usually named
31467 @file{cpp.exe}) using the @code{windres} @option{--preprocessor}
31468 parameter. A list of all possible options may be obtained by entering
31469 the command @code{windres} @option{--help}.
31470
31471 It is also possible to use the Microsoft resource compiler @code{rc.exe}
31472 to produce a @file{.res} file (binary resource file). See the
31473 corresponding Microsoft documentation for further details. In this case
31474 you need to use @code{windres} to translate the @file{.res} file to a
31475 GNAT-compatible object file as follows:
31476
31477 @smallexample
31478 $ windres -i myres.res -o myres.o
31479 @end smallexample
31480
31481 @node Using Resources
31482 @subsection Using Resources
31483 @cindex Resources, using
31484
31485 @noindent
31486 To include the resource file in your program just add the
31487 GNAT-compatible object file for the resource(s) to the linker
31488 arguments. With @command{gnatmake} this is done by using the @option{-largs}
31489 option:
31490
31491 @smallexample
31492 $ gnatmake myprog -largs myres.o
31493 @end smallexample
31494
31495 @node Debugging a DLL
31496 @section Debugging a DLL
31497 @cindex DLL debugging
31498
31499 @menu
31500 * Program and DLL Both Built with GCC/GNAT::
31501 * Program Built with Foreign Tools and DLL Built with GCC/GNAT::
31502 @end menu
31503
31504 @noindent
31505 Debugging a DLL is similar to debugging a standard program. But
31506 we have to deal with two different executable parts: the DLL and the
31507 program that uses it. We have the following four possibilities:
31508
31509 @enumerate 1
31510 @item
31511 The program and the DLL are built with @code{GCC/GNAT}.
31512 @item
31513 The program is built with foreign tools and the DLL is built with
31514 @code{GCC/GNAT}.
31515 @item
31516 The program is built with @code{GCC/GNAT} and the DLL is built with
31517 foreign tools.
31518 @end enumerate
31519
31520 @noindent
31521 In this section we address only cases one and two above.
31522 There is no point in trying to debug
31523 a DLL with @code{GNU/GDB}, if there is no GDB-compatible debugging
31524 information in it. To do so you must use a debugger compatible with the
31525 tools suite used to build the DLL.
31526
31527 @node Program and DLL Both Built with GCC/GNAT
31528 @subsection Program and DLL Both Built with GCC/GNAT
31529
31530 @noindent
31531 This is the simplest case. Both the DLL and the program have @code{GDB}
31532 compatible debugging information. It is then possible to break anywhere in
31533 the process. Let's suppose here that the main procedure is named
31534 @code{ada_main} and that in the DLL there is an entry point named
31535 @code{ada_dll}.
31536
31537 @noindent
31538 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) and
31539 program must have been built with the debugging information (see GNAT -g
31540 switch). Here are the step-by-step instructions for debugging it:
31541
31542 @enumerate 1
31543 @item Launch @code{GDB} on the main program.
31544
31545 @smallexample
31546 $ gdb -nw ada_main
31547 @end smallexample
31548
31549 @item Start the program and stop at the beginning of the main procedure
31550
31551 @smallexample
31552 (gdb) start
31553 @end smallexample
31554
31555 @noindent
31556 This step is required to be able to set a breakpoint inside the DLL. As long
31557 as the program is not run, the DLL is not loaded. This has the
31558 consequence that the DLL debugging information is also not loaded, so it is not
31559 possible to set a breakpoint in the DLL.
31560
31561 @item Set a breakpoint inside the DLL
31562
31563 @smallexample
31564 (gdb) break ada_dll
31565 (gdb) cont
31566 @end smallexample
31567
31568 @end enumerate
31569
31570 @noindent
31571 At this stage a breakpoint is set inside the DLL. From there on
31572 you can use the standard approach to debug the whole program
31573 (@pxref{Running and Debugging Ada Programs}).
31574
31575 @ignore
31576 @c This used to work, probably because the DLLs were non-relocatable
31577 @c keep this section around until the problem is sorted out.
31578
31579 To break on the @code{DllMain} routine it is not possible to follow
31580 the procedure above. At the time the program stop on @code{ada_main}
31581 the @code{DllMain} routine as already been called. Either you can use
31582 the procedure below @pxref{Debugging the DLL Directly} or this procedure:
31583
31584 @enumerate 1
31585 @item Launch @code{GDB} on the main program.
31586
31587 @smallexample
31588 $ gdb ada_main
31589 @end smallexample
31590
31591 @item Load DLL symbols
31592
31593 @smallexample
31594 (gdb) add-sym api.dll
31595 @end smallexample
31596
31597 @item Set a breakpoint inside the DLL
31598
31599 @smallexample
31600 (gdb) break ada_dll.adb:45
31601 @end smallexample
31602
31603 Note that at this point it is not possible to break using the routine symbol
31604 directly as the program is not yet running. The solution is to break
31605 on the proper line (break in @file{ada_dll.adb} line 45).
31606
31607 @item Start the program
31608
31609 @smallexample
31610 (gdb) run
31611 @end smallexample
31612
31613 @end enumerate
31614 @end ignore
31615
31616 @node Program Built with Foreign Tools and DLL Built with GCC/GNAT
31617 @subsection Program Built with Foreign Tools and DLL Built with GCC/GNAT
31618
31619 @menu
31620 * Debugging the DLL Directly::
31621 * Attaching to a Running Process::
31622 @end menu
31623
31624 @noindent
31625 In this case things are slightly more complex because it is not possible to
31626 start the main program and then break at the beginning to load the DLL and the
31627 associated DLL debugging information. It is not possible to break at the
31628 beginning of the program because there is no @code{GDB} debugging information,
31629 and therefore there is no direct way of getting initial control. This
31630 section addresses this issue by describing some methods that can be used
31631 to break somewhere in the DLL to debug it.
31632
31633 @noindent
31634 First suppose that the main procedure is named @code{main} (this is for
31635 example some C code built with Microsoft Visual C) and that there is a
31636 DLL named @code{test.dll} containing an Ada entry point named
31637 @code{ada_dll}.
31638
31639 @noindent
31640 The DLL (@pxref{Introduction to Dynamic Link Libraries (DLLs)}) must have
31641 been built with debugging information (see GNAT -g option).
31642
31643 @node Debugging the DLL Directly
31644 @subsubsection Debugging the DLL Directly
31645
31646 @enumerate 1
31647 @item
31648 Find out the executable starting address
31649
31650 @smallexample
31651 $ objdump --file-header main.exe
31652 @end smallexample
31653
31654 The starting address is reported on the last line. For example:
31655
31656 @smallexample
31657 main.exe: file format pei-i386
31658 architecture: i386, flags 0x0000010a:
31659 EXEC_P, HAS_DEBUG, D_PAGED
31660 start address 0x00401010
31661 @end smallexample
31662
31663 @item
31664 Launch the debugger on the executable.
31665
31666 @smallexample
31667 $ gdb main.exe
31668 @end smallexample
31669
31670 @item
31671 Set a breakpoint at the starting address, and launch the program.
31672
31673 @smallexample
31674 $ (gdb) break *0x00401010
31675 $ (gdb) run
31676 @end smallexample
31677
31678 The program will stop at the given address.
31679
31680 @item
31681 Set a breakpoint on a DLL subroutine.
31682
31683 @smallexample
31684 (gdb) break ada_dll.adb:45
31685 @end smallexample
31686
31687 Or if you want to break using a symbol on the DLL, you need first to
31688 select the Ada language (language used by the DLL).
31689
31690 @smallexample
31691 (gdb) set language ada
31692 (gdb) break ada_dll
31693 @end smallexample
31694
31695 @item
31696 Continue the program.
31697
31698 @smallexample
31699 (gdb) cont
31700 @end smallexample
31701
31702 @noindent
31703 This will run the program until it reaches the breakpoint that has been
31704 set. From that point you can use the standard way to debug a program
31705 as described in (@pxref{Running and Debugging Ada Programs}).
31706
31707 @end enumerate
31708
31709 @noindent
31710 It is also possible to debug the DLL by attaching to a running process.
31711
31712 @node Attaching to a Running Process
31713 @subsubsection Attaching to a Running Process
31714 @cindex DLL debugging, attach to process
31715
31716 @noindent
31717 With @code{GDB} it is always possible to debug a running process by
31718 attaching to it. It is possible to debug a DLL this way. The limitation
31719 of this approach is that the DLL must run long enough to perform the
31720 attach operation. It may be useful for instance to insert a time wasting
31721 loop in the code of the DLL to meet this criterion.
31722
31723 @enumerate 1
31724
31725 @item Launch the main program @file{main.exe}.
31726
31727 @smallexample
31728 $ main
31729 @end smallexample
31730
31731 @item Use the Windows @i{Task Manager} to find the process ID. Let's say
31732 that the process PID for @file{main.exe} is 208.
31733
31734 @item Launch gdb.
31735
31736 @smallexample
31737 $ gdb
31738 @end smallexample
31739
31740 @item Attach to the running process to be debugged.
31741
31742 @smallexample
31743 (gdb) attach 208
31744 @end smallexample
31745
31746 @item Load the process debugging information.
31747
31748 @smallexample
31749 (gdb) symbol-file main.exe
31750 @end smallexample
31751
31752 @item Break somewhere in the DLL.
31753
31754 @smallexample
31755 (gdb) break ada_dll
31756 @end smallexample
31757
31758 @item Continue process execution.
31759
31760 @smallexample
31761 (gdb) cont
31762 @end smallexample
31763
31764 @end enumerate
31765
31766 @noindent
31767 This last step will resume the process execution, and stop at
31768 the breakpoint we have set. From there you can use the standard
31769 approach to debug a program as described in
31770 (@pxref{Running and Debugging Ada Programs}).
31771
31772 @node Setting Stack Size from gnatlink
31773 @section Setting Stack Size from @command{gnatlink}
31774
31775 @noindent
31776 It is possible to specify the program stack size at link time. On modern
31777 versions of Windows, starting with XP, this is mostly useful to set the size of
31778 the main stack (environment task). The other task stacks are set with pragma
31779 Storage_Size or with the @command{gnatbind -d} command.
31780
31781 Since older versions of Windows (2000, NT4, etc.) do not allow setting the
31782 reserve size of individual tasks, the link-time stack size applies to all
31783 tasks, and pragma Storage_Size has no effect.
31784 In particular, Stack Overflow checks are made against this
31785 link-time specified size.
31786
31787 This setting can be done with
31788 @command{gnatlink} using either:
31789
31790 @itemize @bullet
31791
31792 @item using @option{-Xlinker} linker option
31793
31794 @smallexample
31795 $ gnatlink hello -Xlinker --stack=0x10000,0x1000
31796 @end smallexample
31797
31798 This sets the stack reserve size to 0x10000 bytes and the stack commit
31799 size to 0x1000 bytes.
31800
31801 @item using @option{-Wl} linker option
31802
31803 @smallexample
31804 $ gnatlink hello -Wl,--stack=0x1000000
31805 @end smallexample
31806
31807 This sets the stack reserve size to 0x1000000 bytes. Note that with
31808 @option{-Wl} option it is not possible to set the stack commit size
31809 because the coma is a separator for this option.
31810
31811 @end itemize
31812
31813 @node Setting Heap Size from gnatlink
31814 @section Setting Heap Size from @command{gnatlink}
31815
31816 @noindent
31817 Under Windows systems, it is possible to specify the program heap size from
31818 @command{gnatlink} using either:
31819
31820 @itemize @bullet
31821
31822 @item using @option{-Xlinker} linker option
31823
31824 @smallexample
31825 $ gnatlink hello -Xlinker --heap=0x10000,0x1000
31826 @end smallexample
31827
31828 This sets the heap reserve size to 0x10000 bytes and the heap commit
31829 size to 0x1000 bytes.
31830
31831 @item using @option{-Wl} linker option
31832
31833 @smallexample
31834 $ gnatlink hello -Wl,--heap=0x1000000
31835 @end smallexample
31836
31837 This sets the heap reserve size to 0x1000000 bytes. Note that with
31838 @option{-Wl} option it is not possible to set the heap commit size
31839 because the coma is a separator for this option.
31840
31841 @end itemize
31842
31843 @node Mac OS Topics
31844 @appendix Mac OS Topics
31845 @cindex OS X
31846
31847 @noindent
31848 This chapter describes topics that are specific to Apple's OS X
31849 platform.
31850
31851 @menu
31852 * Codesigning the Debugger::
31853 @end menu
31854
31855 @node Codesigning the Debugger
31856 @section Codesigning the Debugger
31857
31858 @noindent
31859 The Darwin Kernel requires the debugger to have special permissions
31860 before it is allowed to control other processes. These permissions
31861 are granted by codesigning the GDB executable. Without these
31862 permissions, the debugger will report error messages such as:
31863
31864 @smallexample
31865 Starting program: /x/y/foo
31866 Unable to find Mach task port for process-id 28885: (os/kern) failure (0x5).
31867 (please check gdb is codesigned - see taskgated(8))
31868 @end smallexample
31869
31870 Codesigning requires a certificate. The following procedure explains
31871 how to create one:
31872
31873 @itemize @bullet
31874 @item Start the Keychain Access application (in
31875 /Applications/Utilities/Keychain Access.app)
31876
31877 @item Select the Keychain Access -> Certificate Assistant ->
31878 Create a Certificate... menu
31879
31880 @item Then:
31881
31882 @itemize @bullet
31883 @item Choose a name for the new certificate (this procedure will use
31884 "gdb-cert" as an example)
31885
31886 @item Set "Identity Type" to "Self Signed Root"
31887
31888 @item Set "Certificate Type" to "Code Signing"
31889
31890 @item Activate the "Let me override defaults" option
31891
31892 @end itemize
31893
31894 @item Click several times on "Continue" until the "Specify a Location
31895 For The Certificate" screen appears, then set "Keychain" to "System"
31896
31897 @item Click on "Continue" until the certificate is created
31898
31899 @item Finally, in the view, double-click on the new certificate,
31900 and set "When using this certificate" to "Always Trust"
31901
31902 @item Exit the Keychain Access application and restart the computer
31903 (this is unfortunately required)
31904
31905 @end itemize
31906
31907 Once a certificate has been created, the debugger can be codesigned
31908 as follow. In a Terminal, run the following command...
31909
31910 @smallexample
31911 codesign -f -s "gdb-cert" <gnat_install_prefix>/bin/gdb
31912 @end smallexample
31913
31914 ... where "gdb-cert" should be replaced by the actual certificate
31915 name chosen above, and <gnat_install_prefix> should be replaced by
31916 the location where you installed GNAT.
31917
31918 @c **********************************
31919 @c * GNU Free Documentation License *
31920 @c **********************************
31921 @include fdl.texi
31922 @c GNU Free Documentation License
31923
31924 @node Index
31925 @unnumbered Index
31926
31927 @printindex cp
31928
31929 @contents
31930 @c Put table of contents at end, otherwise it precedes the "title page" in
31931 @c the .txt version
31932 @c Edit the pdf file to move the contents to the beginning, after the title
31933 @c page
31934
31935 @bye